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 = std::move(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 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
856 Data = nullptr;
858 Diag->~PartialDiagnosticAt();
859 HasDiagnostic = false;
860 }
861 break;
862
863 // Unhandled
866 break;
867 }
868}
869
871 if (HasDiagnostic)
872 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
873 return nullptr;
874}
875
909
945
977
1009
1011 switch (static_cast<TemplateDeductionResult>(Result)) {
1014 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1015
1016 default:
1017 return std::nullopt;
1018 }
1019}
1020
1022 const FunctionDecl *Y) {
1023 if (!X || !Y)
1024 return false;
1025 if (X->getNumParams() != Y->getNumParams())
1026 return false;
1027 // FIXME: when do rewritten comparison operators
1028 // with explicit object parameters correspond?
1029 // https://cplusplus.github.io/CWG/issues/2797.html
1030 for (unsigned I = 0; I < X->getNumParams(); ++I)
1031 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1032 Y->getParamDecl(I)->getType()))
1033 return false;
1034 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1035 auto *FTY = Y->getDescribedFunctionTemplate();
1036 if (!FTY)
1037 return false;
1038 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1039 FTY->getTemplateParameters()))
1040 return false;
1041 }
1042 return true;
1043}
1044
1046 Expr *FirstOperand, FunctionDecl *EqFD) {
1047 assert(EqFD->getOverloadedOperator() ==
1048 OverloadedOperatorKind::OO_EqualEqual);
1049 // C++2a [over.match.oper]p4:
1050 // A non-template function or function template F named operator== is a
1051 // rewrite target with first operand o unless a search for the name operator!=
1052 // in the scope S from the instantiation context of the operator expression
1053 // finds a function or function template that would correspond
1054 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1055 // scope of the class type of o if F is a class member, and the namespace
1056 // scope of which F is a member otherwise. A function template specialization
1057 // named operator== is a rewrite target if its function template is a rewrite
1058 // target.
1060 OverloadedOperatorKind::OO_ExclaimEqual);
1061 if (isa<CXXMethodDecl>(EqFD)) {
1062 // If F is a class member, search scope is class type of first operand.
1063 QualType RHS = FirstOperand->getType();
1064 auto *RHSRec = RHS->getAsCXXRecordDecl();
1065 if (!RHSRec)
1066 return true;
1067 LookupResult Members(S, NotEqOp, OpLoc,
1069 S.LookupQualifiedName(Members, RHSRec);
1070 Members.suppressAccessDiagnostics();
1071 for (NamedDecl *Op : Members)
1072 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1073 return false;
1074 return true;
1075 }
1076 // Otherwise the search scope is the namespace scope of which F is a member.
1077 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1078 auto *NotEqFD = Op->getAsFunction();
1079 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1080 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1081 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1083 cast<Decl>(Op->getLexicalDeclContext())))
1084 return false;
1085 }
1086 return true;
1087}
1088
1090 OverloadedOperatorKind Op) const {
1092 return false;
1093 return Op == OO_EqualEqual || Op == OO_Spaceship;
1094}
1095
1097 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1098 auto Op = FD->getOverloadedOperator();
1099 if (!allowsReversed(Op))
1100 return false;
1101 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1102 assert(OriginalArgs.size() == 2);
1104 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1105 return false;
1106 }
1107 // Don't bother adding a reversed candidate that can never be a better
1108 // match than the non-reversed version.
1109 return FD->getNumNonObjectParams() != 2 ||
1111 FD->getParamDecl(1)->getType()) ||
1112 FD->hasAttr<EnableIfAttr>();
1113}
1114
1115void OverloadCandidateSet::destroyCandidates() {
1116 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1117 for (auto &C : i->Conversions)
1118 C.~ImplicitConversionSequence();
1119 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1120 i->DeductionFailure.Destroy();
1121 }
1122}
1123
1125 destroyCandidates();
1126 SlabAllocator.Reset();
1127 NumInlineBytesUsed = 0;
1128 Candidates.clear();
1129 Functions.clear();
1130 Kind = CSK;
1131 FirstDeferredCandidate = nullptr;
1132 DeferredCandidatesCount = 0;
1133 HasDeferredTemplateConstructors = false;
1134 ResolutionByPerfectCandidateIsDisabled = false;
1135}
1136
1137namespace {
1138 class UnbridgedCastsSet {
1139 struct Entry {
1140 Expr **Addr;
1141 Expr *Saved;
1142 };
1143 SmallVector<Entry, 2> Entries;
1144
1145 public:
1146 void save(Sema &S, Expr *&E) {
1147 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1148 Entry entry = { &E, E };
1149 Entries.push_back(entry);
1150 E = S.ObjC().stripARCUnbridgedCast(E);
1151 }
1152
1153 void restore() {
1154 for (SmallVectorImpl<Entry>::iterator
1155 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1156 *i->Addr = i->Saved;
1157 }
1158 };
1159}
1160
1161/// checkPlaceholderForOverload - Do any interesting placeholder-like
1162/// preprocessing on the given expression.
1163///
1164/// \param unbridgedCasts a collection to which to add unbridged casts;
1165/// without this, they will be immediately diagnosed as errors
1166///
1167/// Return true on unrecoverable error.
1168static bool
1170 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1171 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1172 // We can't handle overloaded expressions here because overload
1173 // resolution might reasonably tweak them.
1174 if (placeholder->getKind() == BuiltinType::Overload) return false;
1175
1176 // If the context potentially accepts unbridged ARC casts, strip
1177 // the unbridged cast and add it to the collection for later restoration.
1178 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1179 unbridgedCasts) {
1180 unbridgedCasts->save(S, E);
1181 return false;
1182 }
1183
1184 // Go ahead and check everything else.
1185 ExprResult result = S.CheckPlaceholderExpr(E);
1186 if (result.isInvalid())
1187 return true;
1188
1189 E = result.get();
1190 return false;
1191 }
1192
1193 // Nothing to do.
1194 return false;
1195}
1196
1197/// checkArgPlaceholdersForOverload - Check a set of call operands for
1198/// placeholders.
1200 UnbridgedCastsSet &unbridged) {
1201 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1202 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1203 return true;
1204
1205 return false;
1206}
1207
1209 const LookupResult &Old, NamedDecl *&Match,
1210 bool NewIsUsingDecl) {
1211 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1212 I != E; ++I) {
1213 NamedDecl *OldD = *I;
1214
1215 bool OldIsUsingDecl = false;
1216 if (isa<UsingShadowDecl>(OldD)) {
1217 OldIsUsingDecl = true;
1218
1219 // We can always introduce two using declarations into the same
1220 // context, even if they have identical signatures.
1221 if (NewIsUsingDecl) continue;
1222
1223 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1224 }
1225
1226 // A using-declaration does not conflict with another declaration
1227 // if one of them is hidden.
1228 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1229 continue;
1230
1231 // If either declaration was introduced by a using declaration,
1232 // we'll need to use slightly different rules for matching.
1233 // Essentially, these rules are the normal rules, except that
1234 // function templates hide function templates with different
1235 // return types or template parameter lists.
1236 bool UseMemberUsingDeclRules =
1237 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1238 !New->getFriendObjectKind();
1239
1240 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1241 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1242 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1244 continue;
1245 }
1246
1247 if (!isa<FunctionTemplateDecl>(OldD) &&
1248 !shouldLinkPossiblyHiddenDecl(*I, New))
1249 continue;
1250
1251 Match = *I;
1252 return OverloadKind::Match;
1253 }
1254
1255 // Builtins that have custom typechecking or have a reference should
1256 // not be overloadable or redeclarable.
1257 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1258 Match = *I;
1260 }
1261 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1262 // We can overload with these, which can show up when doing
1263 // redeclaration checks for UsingDecls.
1264 assert(Old.getLookupKind() == LookupUsingDeclName);
1265 } else if (isa<TagDecl>(OldD)) {
1266 // We can always overload with tags by hiding them.
1267 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1268 // Optimistically assume that an unresolved using decl will
1269 // overload; if it doesn't, we'll have to diagnose during
1270 // template instantiation.
1271 //
1272 // Exception: if the scope is dependent and this is not a class
1273 // member, the using declaration can only introduce an enumerator.
1274 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1275 Match = *I;
1277 }
1278 } else {
1279 // (C++ 13p1):
1280 // Only function declarations can be overloaded; object and type
1281 // declarations cannot be overloaded.
1282 Match = *I;
1284 }
1285 }
1286
1287 // C++ [temp.friend]p1:
1288 // For a friend function declaration that is not a template declaration:
1289 // -- if the name of the friend is a qualified or unqualified template-id,
1290 // [...], otherwise
1291 // -- if the name of the friend is a qualified-id and a matching
1292 // non-template function is found in the specified class or namespace,
1293 // the friend declaration refers to that function, otherwise,
1294 // -- if the name of the friend is a qualified-id and a matching function
1295 // template is found in the specified class or namespace, the friend
1296 // declaration refers to the deduced specialization of that function
1297 // template, otherwise
1298 // -- the name shall be an unqualified-id [...]
1299 // If we get here for a qualified friend declaration, we've just reached the
1300 // third bullet. If the type of the friend is dependent, skip this lookup
1301 // until instantiation.
1302 if (New->getFriendObjectKind() && New->getQualifier() &&
1303 !New->getDescribedFunctionTemplate() &&
1304 !New->getDependentSpecializationInfo() &&
1305 !New->getType()->isDependentType()) {
1306 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1307 TemplateSpecResult.addAllDecls(Old);
1308 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1309 /*QualifiedFriend*/true)) {
1310 New->setInvalidDecl();
1312 }
1313
1314 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1315 return OverloadKind::Match;
1316 }
1317
1319}
1320
1321template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1322 assert(D && "function decl should not be null");
1323 if (auto *A = D->getAttr<AttrT>())
1324 return !A->isImplicit();
1325 return false;
1326}
1327
1329 FunctionDecl *Old,
1330 bool UseMemberUsingDeclRules,
1331 bool ConsiderCudaAttrs,
1332 bool UseOverrideRules = false) {
1333 // C++ [basic.start.main]p2: This function shall not be overloaded.
1334 if (New->isMain())
1335 return false;
1336
1337 // MSVCRT user defined entry points cannot be overloaded.
1338 if (New->isMSVCRTEntryPoint())
1339 return false;
1340
1341 NamedDecl *OldDecl = Old;
1342 NamedDecl *NewDecl = New;
1344 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1345
1346 // C++ [temp.fct]p2:
1347 // A function template can be overloaded with other function templates
1348 // and with normal (non-template) functions.
1349 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1350 return true;
1351
1352 // Is the function New an overload of the function Old?
1353 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1354 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1355
1356 // Compare the signatures (C++ 1.3.10) of the two functions to
1357 // determine whether they are overloads. If we find any mismatch
1358 // in the signature, they are overloads.
1359
1360 // If either of these functions is a K&R-style function (no
1361 // prototype), then we consider them to have matching signatures.
1362 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1364 return false;
1365
1366 const auto *OldType = cast<FunctionProtoType>(OldQType);
1367 const auto *NewType = cast<FunctionProtoType>(NewQType);
1368
1369 // The signature of a function includes the types of its
1370 // parameters (C++ 1.3.10), which includes the presence or absence
1371 // of the ellipsis; see C++ DR 357).
1372 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1373 return true;
1374
1375 // For member-like friends, the enclosing class is part of the signature.
1376 if ((New->isMemberLikeConstrainedFriend() ||
1378 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1379 return true;
1380
1381 // Compare the parameter lists.
1382 // This can only be done once we have establish that friend functions
1383 // inhabit the same context, otherwise we might tried to instantiate
1384 // references to non-instantiated entities during constraint substitution.
1385 // GH78101.
1386 if (NewTemplate) {
1387 OldDecl = OldTemplate;
1388 NewDecl = NewTemplate;
1389 // C++ [temp.over.link]p4:
1390 // The signature of a function template consists of its function
1391 // signature, its return type and its template parameter list. The names
1392 // of the template parameters are significant only for establishing the
1393 // relationship between the template parameters and the rest of the
1394 // signature.
1395 //
1396 // We check the return type and template parameter lists for function
1397 // templates first; the remaining checks follow.
1398 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1399 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1400 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1401 bool SameReturnType = SemaRef.Context.hasSameType(
1402 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1403 // FIXME(GH58571): Match template parameter list even for non-constrained
1404 // template heads. This currently ensures that the code prior to C++20 is
1405 // not newly broken.
1406 bool ConstraintsInTemplateHead =
1409 // C++ [namespace.udecl]p11:
1410 // The set of declarations named by a using-declarator that inhabits a
1411 // class C does not include member functions and member function
1412 // templates of a base class that "correspond" to (and thus would
1413 // conflict with) a declaration of a function or function template in
1414 // C.
1415 // Comparing return types is not required for the "correspond" check to
1416 // decide whether a member introduced by a shadow declaration is hidden.
1417 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1418 !SameTemplateParameterList)
1419 return true;
1420 if (!UseMemberUsingDeclRules &&
1421 (!SameTemplateParameterList || !SameReturnType))
1422 return true;
1423 }
1424
1425 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1426 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1427
1428 int OldParamsOffset = 0;
1429 int NewParamsOffset = 0;
1430
1431 // When determining if a method is an overload from a base class, act as if
1432 // the implicit object parameter are of the same type.
1433
1434 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1436 auto ThisType = M->getFunctionObjectParameterReferenceType();
1437 if (ThisType.isConstQualified())
1438 Q.removeConst();
1439 return Q;
1440 }
1441
1442 // We do not allow overloading based off of '__restrict'.
1443 Q.removeRestrict();
1444
1445 // We may not have applied the implicit const for a constexpr member
1446 // function yet (because we haven't yet resolved whether this is a static
1447 // or non-static member function). Add it now, on the assumption that this
1448 // is a redeclaration of OldMethod.
1449 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1450 (M->isConstexpr() || M->isConsteval()) &&
1451 !isa<CXXConstructorDecl>(NewMethod))
1452 Q.addConst();
1453 return Q;
1454 };
1455
1456 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1457 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1458 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1459
1460 if (OldMethod->isExplicitObjectMemberFunction()) {
1461 BS.Quals.removeVolatile();
1462 DS.Quals.removeVolatile();
1463 }
1464
1465 return BS.Quals == DS.Quals;
1466 };
1467
1468 auto CompareType = [&](QualType Base, QualType D) {
1469 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1470 auto DS = D.getNonReferenceType().getCanonicalType().split();
1471
1472 if (!AreQualifiersEqual(BS, DS))
1473 return false;
1474
1475 if (OldMethod->isImplicitObjectMemberFunction() &&
1476 OldMethod->getParent() != NewMethod->getParent()) {
1477 CanQualType ParentType =
1478 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1479 if (ParentType.getTypePtr() != BS.Ty)
1480 return false;
1481 BS.Ty = DS.Ty;
1482 }
1483
1484 // FIXME: should we ignore some type attributes here?
1485 if (BS.Ty != DS.Ty)
1486 return false;
1487
1488 if (Base->isLValueReferenceType())
1489 return D->isLValueReferenceType();
1490 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1491 };
1492
1493 // If the function is a class member, its signature includes the
1494 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1495 auto DiagnoseInconsistentRefQualifiers = [&]() {
1496 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1497 return false;
1498 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1499 return false;
1500 if (OldMethod->isExplicitObjectMemberFunction() ||
1501 NewMethod->isExplicitObjectMemberFunction())
1502 return false;
1503 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1504 NewMethod->getRefQualifier() == RQ_None)) {
1505 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1506 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1507 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1508 return true;
1509 }
1510 return false;
1511 };
1512
1513 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1514 OldParamsOffset++;
1515 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1516 NewParamsOffset++;
1517
1518 if (OldType->getNumParams() - OldParamsOffset !=
1519 NewType->getNumParams() - NewParamsOffset ||
1521 {OldType->param_type_begin() + OldParamsOffset,
1522 OldType->param_type_end()},
1523 {NewType->param_type_begin() + NewParamsOffset,
1524 NewType->param_type_end()},
1525 nullptr)) {
1526 return true;
1527 }
1528
1529 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1530 !NewMethod->isStatic()) {
1531 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1532 const CXXMethodDecl *New) {
1533 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1534 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1535
1536 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1537 return F->getRefQualifier() == RQ_None &&
1538 !F->isExplicitObjectMemberFunction();
1539 };
1540
1541 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1542 CompareType(OldObjectType.getNonReferenceType(),
1543 NewObjectType.getNonReferenceType()))
1544 return true;
1545 return CompareType(OldObjectType, NewObjectType);
1546 }(OldMethod, NewMethod);
1547
1548 if (!HaveCorrespondingObjectParameters) {
1549 if (DiagnoseInconsistentRefQualifiers())
1550 return true;
1551 // CWG2554
1552 // and, if at least one is an explicit object member function, ignoring
1553 // object parameters
1554 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1555 !OldMethod->isExplicitObjectMemberFunction()))
1556 return true;
1557 }
1558 }
1559
1560 if (!UseOverrideRules &&
1561 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1562 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1563 OldRC = Old->getTrailingRequiresClause();
1564 if (!NewRC != !OldRC)
1565 return true;
1566 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1567 return true;
1568 if (NewRC &&
1569 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1570 NewDecl, NewRC.ConstraintExpr))
1571 return true;
1572 }
1573
1574 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1575 NewMethod->isImplicitObjectMemberFunction()) {
1576 if (DiagnoseInconsistentRefQualifiers())
1577 return true;
1578 }
1579
1580 // Though pass_object_size is placed on parameters and takes an argument, we
1581 // consider it to be a function-level modifier for the sake of function
1582 // identity. Either the function has one or more parameters with
1583 // pass_object_size or it doesn't.
1586 return true;
1587
1588 // enable_if attributes are an order-sensitive part of the signature.
1590 NewI = New->specific_attr_begin<EnableIfAttr>(),
1591 NewE = New->specific_attr_end<EnableIfAttr>(),
1592 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1593 OldE = Old->specific_attr_end<EnableIfAttr>();
1594 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1595 if (NewI == NewE || OldI == OldE)
1596 return true;
1597 llvm::FoldingSetNodeID NewID, OldID;
1598 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1599 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1600 if (NewID != OldID)
1601 return true;
1602 }
1603
1604 // At this point, it is known that the two functions have the same signature.
1605 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1606 // Don't allow overloading of destructors. (In theory we could, but it
1607 // would be a giant change to clang.)
1609 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1610 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1611 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1612 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1613 "Unexpected invalid target.");
1614
1615 // Allow overloading of functions with same signature and different CUDA
1616 // target attributes.
1617 if (NewTarget != OldTarget) {
1618 // Special case: non-constexpr function is allowed to override
1619 // constexpr virtual function
1620 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1621 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1626 return false;
1627 }
1628 return true;
1629 }
1630 }
1631 }
1632 }
1633
1634 // The signatures match; this is not an overload.
1635 return false;
1636}
1637
1639 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1640 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1641 ConsiderCudaAttrs);
1642}
1643
1645 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1646 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1647 /*UseMemberUsingDeclRules=*/false,
1648 /*ConsiderCudaAttrs=*/true,
1649 /*UseOverrideRules=*/true);
1650}
1651
1652/// Tries a user-defined conversion from From to ToType.
1653///
1654/// Produces an implicit conversion sequence for when a standard conversion
1655/// is not an option. See TryImplicitConversion for more information.
1658 bool SuppressUserConversions,
1659 AllowedExplicit AllowExplicit,
1660 bool InOverloadResolution,
1661 bool CStyle,
1662 bool AllowObjCWritebackConversion,
1663 bool AllowObjCConversionOnExplicit) {
1665
1666 if (SuppressUserConversions) {
1667 // We're not in the case above, so there is no conversion that
1668 // we can perform.
1670 return ICS;
1671 }
1672
1673 // Attempt user-defined conversion.
1674 OverloadCandidateSet Conversions(From->getExprLoc(),
1676 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1677 Conversions, AllowExplicit,
1678 AllowObjCConversionOnExplicit)) {
1679 case OR_Success:
1680 case OR_Deleted:
1681 ICS.setUserDefined();
1682 // C++ [over.ics.user]p4:
1683 // A conversion of an expression of class type to the same class
1684 // type is given Exact Match rank, and a conversion of an
1685 // expression of class type to a base class of that type is
1686 // given Conversion rank, in spite of the fact that a copy
1687 // constructor (i.e., a user-defined conversion function) is
1688 // called for those cases.
1690 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1691 QualType FromType;
1692 SourceLocation FromLoc;
1693 // C++11 [over.ics.list]p6, per DR2137:
1694 // C++17 [over.ics.list]p6:
1695 // If C is not an initializer-list constructor and the initializer list
1696 // has a single element of type cv U, where U is X or a class derived
1697 // from X, the implicit conversion sequence has Exact Match rank if U is
1698 // X, or Conversion rank if U is derived from X.
1699 bool FromListInit = false;
1700 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1701 InitList && InitList->getNumInits() == 1 &&
1703 const Expr *SingleInit = InitList->getInit(0);
1704 FromType = SingleInit->getType();
1705 FromLoc = SingleInit->getBeginLoc();
1706 FromListInit = true;
1707 } else {
1708 FromType = From->getType();
1709 FromLoc = From->getBeginLoc();
1710 }
1711 QualType FromCanon =
1713 QualType ToCanon
1715 if ((FromCanon == ToCanon ||
1716 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1717 // Turn this into a "standard" conversion sequence, so that it
1718 // gets ranked with standard conversion sequences.
1720 ICS.setStandard();
1722 ICS.Standard.setFromType(FromType);
1723 ICS.Standard.setAllToTypes(ToType);
1724 ICS.Standard.FromBracedInitList = FromListInit;
1727 if (ToCanon != FromCanon)
1729 }
1730 }
1731 break;
1732
1733 case OR_Ambiguous:
1734 ICS.setAmbiguous();
1735 ICS.Ambiguous.setFromType(From->getType());
1736 ICS.Ambiguous.setToType(ToType);
1737 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1738 Cand != Conversions.end(); ++Cand)
1739 if (Cand->Best)
1740 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1741 break;
1742
1743 // Fall through.
1746 break;
1747 }
1748
1749 return ICS;
1750}
1751
1752/// TryImplicitConversion - Attempt to perform an implicit conversion
1753/// from the given expression (Expr) to the given type (ToType). This
1754/// function returns an implicit conversion sequence that can be used
1755/// to perform the initialization. Given
1756///
1757/// void f(float f);
1758/// void g(int i) { f(i); }
1759///
1760/// this routine would produce an implicit conversion sequence to
1761/// describe the initialization of f from i, which will be a standard
1762/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1763/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1764//
1765/// Note that this routine only determines how the conversion can be
1766/// performed; it does not actually perform the conversion. As such,
1767/// it will not produce any diagnostics if no conversion is available,
1768/// but will instead return an implicit conversion sequence of kind
1769/// "BadConversion".
1770///
1771/// If @p SuppressUserConversions, then user-defined conversions are
1772/// not permitted.
1773/// If @p AllowExplicit, then explicit user-defined conversions are
1774/// permitted.
1775///
1776/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1777/// writeback conversion, which allows __autoreleasing id* parameters to
1778/// be initialized with __strong id* or __weak id* arguments.
1779static ImplicitConversionSequence
1781 bool SuppressUserConversions,
1782 AllowedExplicit AllowExplicit,
1783 bool InOverloadResolution,
1784 bool CStyle,
1785 bool AllowObjCWritebackConversion,
1786 bool AllowObjCConversionOnExplicit) {
1788 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1789 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1790 ICS.setStandard();
1791 return ICS;
1792 }
1793
1794 if (!S.getLangOpts().CPlusPlus) {
1796 return ICS;
1797 }
1798
1799 // C++ [over.ics.user]p4:
1800 // A conversion of an expression of class type to the same class
1801 // type is given Exact Match rank, and a conversion of an
1802 // expression of class type to a base class of that type is
1803 // given Conversion rank, in spite of the fact that a copy/move
1804 // constructor (i.e., a user-defined conversion function) is
1805 // called for those cases.
1806 QualType FromType = From->getType();
1807 if (ToType->isRecordType() &&
1808 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1809 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1810 ICS.setStandard();
1812 ICS.Standard.setFromType(FromType);
1813 ICS.Standard.setAllToTypes(ToType);
1814
1815 // We don't actually check at this point whether there is a valid
1816 // copy/move constructor, since overloading just assumes that it
1817 // exists. When we actually perform initialization, we'll find the
1818 // appropriate constructor to copy the returned object, if needed.
1819 ICS.Standard.CopyConstructor = nullptr;
1820
1821 // Determine whether this is considered a derived-to-base conversion.
1822 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1824
1825 return ICS;
1826 }
1827
1828 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1829 FromType->isHLSLAttributedResourceType()) {
1830 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1831 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1832 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1833 FromResType->getWrappedType()) &&
1834 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1835 FromResType->getContainedType()) &&
1836 ToResType->getAttrs() == FromResType->getAttrs()) {
1837 ICS.setStandard();
1839 ICS.Standard.setFromType(FromType);
1840 ICS.Standard.setAllToTypes(ToType);
1841 return ICS;
1842 }
1843 }
1844
1845 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1846 AllowExplicit, InOverloadResolution, CStyle,
1847 AllowObjCWritebackConversion,
1848 AllowObjCConversionOnExplicit);
1849}
1850
1851ImplicitConversionSequence
1853 bool SuppressUserConversions,
1854 AllowedExplicit AllowExplicit,
1855 bool InOverloadResolution,
1856 bool CStyle,
1857 bool AllowObjCWritebackConversion) {
1858 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1859 AllowExplicit, InOverloadResolution, CStyle,
1860 AllowObjCWritebackConversion,
1861 /*AllowObjCConversionOnExplicit=*/false);
1862}
1863
1865 AssignmentAction Action,
1866 bool AllowExplicit) {
1867 if (checkPlaceholderForOverload(*this, From))
1868 return ExprError();
1869
1870 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1871 bool AllowObjCWritebackConversion =
1872 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1873 Action == AssignmentAction::Sending);
1874 if (getLangOpts().ObjC)
1875 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1876 From->getType(), From);
1878 *this, From, ToType,
1879 /*SuppressUserConversions=*/false,
1880 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1881 /*InOverloadResolution=*/false,
1882 /*CStyle=*/false, AllowObjCWritebackConversion,
1883 /*AllowObjCConversionOnExplicit=*/false);
1884 return PerformImplicitConversion(From, ToType, ICS, Action);
1885}
1886
1888 QualType &ResultTy) const {
1889 bool Changed = IsFunctionConversion(FromType, ToType);
1890 if (Changed)
1891 ResultTy = ToType;
1892 return Changed;
1893}
1894
1895bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1896 if (Context.hasSameUnqualifiedType(FromType, ToType))
1897 return false;
1898
1899 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1900 // or F(t noexcept) -> F(t)
1901 // where F adds one of the following at most once:
1902 // - a pointer
1903 // - a member pointer
1904 // - a block pointer
1905 // Changes here need matching changes in FindCompositePointerType.
1906 CanQualType CanTo = Context.getCanonicalType(ToType);
1907 CanQualType CanFrom = Context.getCanonicalType(FromType);
1908 Type::TypeClass TyClass = CanTo->getTypeClass();
1909 if (TyClass != CanFrom->getTypeClass()) return false;
1910 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1911 if (TyClass == Type::Pointer) {
1912 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1913 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1914 } else if (TyClass == Type::BlockPointer) {
1915 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1916 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1917 } else if (TyClass == Type::MemberPointer) {
1918 auto ToMPT = CanTo.castAs<MemberPointerType>();
1919 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1920 // A function pointer conversion cannot change the class of the function.
1921 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1922 FromMPT->getMostRecentCXXRecordDecl()))
1923 return false;
1924 CanTo = ToMPT->getPointeeType();
1925 CanFrom = FromMPT->getPointeeType();
1926 } else {
1927 return false;
1928 }
1929
1930 TyClass = CanTo->getTypeClass();
1931 if (TyClass != CanFrom->getTypeClass()) return false;
1932 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1933 return false;
1934 }
1935
1936 const auto *FromFn = cast<FunctionType>(CanFrom);
1937 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1938
1939 const auto *ToFn = cast<FunctionType>(CanTo);
1940 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1941
1942 bool Changed = false;
1943
1944 // Drop 'noreturn' if not present in target type.
1945 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1946 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1947 Changed = true;
1948 }
1949
1950 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1951 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1952
1953 if (FromFPT && ToFPT) {
1954 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1955 QualType NewTy = Context.getFunctionType(
1956 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1957 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1958 ToFPT->hasCFIUncheckedCallee()));
1959 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1960 FromFn = FromFPT;
1961 Changed = true;
1962 }
1963 }
1964
1965 // Drop 'noexcept' if not present in target type.
1966 if (FromFPT && ToFPT) {
1967 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1968 FromFn = cast<FunctionType>(
1969 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1970 EST_None)
1971 .getTypePtr());
1972 Changed = true;
1973 }
1974
1975 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1976 // only if the ExtParameterInfo lists of the two function prototypes can be
1977 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1979 bool CanUseToFPT, CanUseFromFPT;
1980 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1981 CanUseFromFPT, NewParamInfos) &&
1982 CanUseToFPT && !CanUseFromFPT) {
1983 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1984 ExtInfo.ExtParameterInfos =
1985 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1986 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1987 FromFPT->getParamTypes(), ExtInfo);
1988 FromFn = QT->getAs<FunctionType>();
1989 Changed = true;
1990 }
1991
1992 if (Context.hasAnyFunctionEffects()) {
1993 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1994
1995 // Transparently add/drop effects; here we are concerned with
1996 // language rules/canonicalization. Adding/dropping effects is a warning.
1997 const auto FromFX = FromFPT->getFunctionEffects();
1998 const auto ToFX = ToFPT->getFunctionEffects();
1999 if (FromFX != ToFX) {
2000 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2001 ExtInfo.FunctionEffects = ToFX;
2002 QualType QT = Context.getFunctionType(
2003 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2004 FromFn = QT->getAs<FunctionType>();
2005 Changed = true;
2006 }
2007 }
2008 }
2009
2010 if (!Changed)
2011 return false;
2012
2013 assert(QualType(FromFn, 0).isCanonical());
2014 if (QualType(FromFn, 0) != CanTo) return false;
2015
2016 return true;
2017}
2018
2019/// Determine whether the conversion from FromType to ToType is a valid
2020/// floating point conversion.
2021///
2022static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2023 QualType ToType) {
2024 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2025 return false;
2026 // FIXME: disable conversions between long double, __ibm128 and __float128
2027 // if their representation is different until there is back end support
2028 // We of course allow this conversion if long double is really double.
2029
2030 // Conversions between bfloat16 and float16 are currently not supported.
2031 if ((FromType->isBFloat16Type() &&
2032 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2033 (ToType->isBFloat16Type() &&
2034 (FromType->isFloat16Type() || FromType->isHalfType())))
2035 return false;
2036
2037 // Conversions between IEEE-quad and IBM-extended semantics are not
2038 // permitted.
2039 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2040 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2041 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2042 &ToSem == &llvm::APFloat::IEEEquad()) ||
2043 (&FromSem == &llvm::APFloat::IEEEquad() &&
2044 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2045 return false;
2046 return true;
2047}
2048
2049static bool IsVectorElementConversion(Sema &S, QualType FromType,
2050 QualType ToType,
2051 ImplicitConversionKind &ICK, Expr *From) {
2052 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2053 return true;
2054
2055 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2057 return true;
2058 }
2059
2060 if (IsFloatingPointConversion(S, FromType, ToType)) {
2062 return true;
2063 }
2064
2065 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2067 return true;
2068 }
2069
2070 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2072 ToType->isRealFloatingType())) {
2074 return true;
2075 }
2076
2077 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2079 return true;
2080 }
2081
2082 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2083 ToType->isIntegralType(S.Context)) {
2085 return true;
2086 }
2087
2088 return false;
2089}
2090
2091/// Determine whether the conversion from FromType to ToType is a valid
2092/// vector conversion.
2093///
2094/// \param ICK Will be set to the vector conversion kind, if this is a vector
2095/// conversion.
2096static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2098 ImplicitConversionKind &ElConv, Expr *From,
2099 bool InOverloadResolution, bool CStyle) {
2100 // We need at least one of these types to be a vector type to have a vector
2101 // conversion.
2102 if (!ToType->isVectorType() && !FromType->isVectorType())
2103 return false;
2104
2105 // Identical types require no conversions.
2106 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2107 return false;
2108
2109 // HLSL allows implicit truncation of vector types.
2110 if (S.getLangOpts().HLSL) {
2111 auto *ToExtType = ToType->getAs<ExtVectorType>();
2112 auto *FromExtType = FromType->getAs<ExtVectorType>();
2113
2114 // If both arguments are vectors, handle possible vector truncation and
2115 // element conversion.
2116 if (ToExtType && FromExtType) {
2117 unsigned FromElts = FromExtType->getNumElements();
2118 unsigned ToElts = ToExtType->getNumElements();
2119 if (FromElts < ToElts)
2120 return false;
2121 if (FromElts == ToElts)
2122 ElConv = ICK_Identity;
2123 else
2125
2126 QualType FromElTy = FromExtType->getElementType();
2127 QualType ToElTy = ToExtType->getElementType();
2128 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2129 return true;
2130 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2131 }
2132 if (FromExtType && !ToExtType) {
2134 QualType FromElTy = FromExtType->getElementType();
2135 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2136 return true;
2137 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2138 }
2139 // Fallthrough for the case where ToType is a vector and FromType is not.
2140 }
2141
2142 // There are no conversions between extended vector types, only identity.
2143 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2144 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2145 // Implicit conversions require the same number of elements.
2146 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2147 return false;
2148
2149 // Permit implicit conversions from integral values to boolean vectors.
2150 if (ToType->isExtVectorBoolType() &&
2151 FromExtType->getElementType()->isIntegerType()) {
2153 return true;
2154 }
2155 // There are no other conversions between extended vector types.
2156 return false;
2157 }
2158
2159 // Vector splat from any arithmetic type to a vector.
2160 if (FromType->isArithmeticType()) {
2161 if (S.getLangOpts().HLSL) {
2162 ElConv = ICK_HLSL_Vector_Splat;
2163 QualType ToElTy = ToExtType->getElementType();
2164 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2165 }
2166 ICK = ICK_Vector_Splat;
2167 return true;
2168 }
2169 }
2170
2171 if (ToType->isSVESizelessBuiltinType() ||
2172 FromType->isSVESizelessBuiltinType())
2173 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2174 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2176 return true;
2177 }
2178
2179 if (ToType->isRVVSizelessBuiltinType() ||
2180 FromType->isRVVSizelessBuiltinType())
2181 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2182 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2184 return true;
2185 }
2186
2187 // We can perform the conversion between vector types in the following cases:
2188 // 1)vector types are equivalent AltiVec and GCC vector types
2189 // 2)lax vector conversions are permitted and the vector types are of the
2190 // same size
2191 // 3)the destination type does not have the ARM MVE strict-polymorphism
2192 // attribute, which inhibits lax vector conversion for overload resolution
2193 // only
2194 if (ToType->isVectorType() && FromType->isVectorType()) {
2195 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2196 (S.isLaxVectorConversion(FromType, ToType) &&
2197 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2198 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2199 S.isLaxVectorConversion(FromType, ToType) &&
2200 S.anyAltivecTypes(FromType, ToType) &&
2201 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2202 !InOverloadResolution && !CStyle) {
2203 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2204 << FromType << ToType;
2205 }
2207 return true;
2208 }
2209 }
2210
2211 return false;
2212}
2213
2214static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2215 bool InOverloadResolution,
2216 StandardConversionSequence &SCS,
2217 bool CStyle);
2218
2219/// IsStandardConversion - Determines whether there is a standard
2220/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2221/// expression From to the type ToType. Standard conversion sequences
2222/// only consider non-class types; for conversions that involve class
2223/// types, use TryImplicitConversion. If a conversion exists, SCS will
2224/// contain the standard conversion sequence required to perform this
2225/// conversion and this routine will return true. Otherwise, this
2226/// routine will return false and the value of SCS is unspecified.
2227static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2228 bool InOverloadResolution,
2230 bool CStyle,
2231 bool AllowObjCWritebackConversion) {
2232 QualType FromType = From->getType();
2233
2234 // Standard conversions (C++ [conv])
2236 SCS.IncompatibleObjC = false;
2237 SCS.setFromType(FromType);
2238 SCS.CopyConstructor = nullptr;
2239
2240 // There are no standard conversions for class types in C++, so
2241 // abort early. When overloading in C, however, we do permit them.
2242 if (S.getLangOpts().CPlusPlus &&
2243 (FromType->isRecordType() || ToType->isRecordType()))
2244 return false;
2245
2246 // The first conversion can be an lvalue-to-rvalue conversion,
2247 // array-to-pointer conversion, or function-to-pointer conversion
2248 // (C++ 4p1).
2249
2250 if (FromType == S.Context.OverloadTy) {
2251 DeclAccessPair AccessPair;
2252 if (FunctionDecl *Fn
2253 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2254 AccessPair)) {
2255 // We were able to resolve the address of the overloaded function,
2256 // so we can convert to the type of that function.
2257 FromType = Fn->getType();
2258 SCS.setFromType(FromType);
2259
2260 // we can sometimes resolve &foo<int> regardless of ToType, so check
2261 // if the type matches (identity) or we are converting to bool
2263 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2264 // if the function type matches except for [[noreturn]], it's ok
2265 if (!S.IsFunctionConversion(FromType,
2267 // otherwise, only a boolean conversion is standard
2268 if (!ToType->isBooleanType())
2269 return false;
2270 }
2271
2272 // Check if the "from" expression is taking the address of an overloaded
2273 // function and recompute the FromType accordingly. Take advantage of the
2274 // fact that non-static member functions *must* have such an address-of
2275 // expression.
2276 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2277 if (Method && !Method->isStatic() &&
2278 !Method->isExplicitObjectMemberFunction()) {
2279 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2280 "Non-unary operator on non-static member address");
2281 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2282 == UO_AddrOf &&
2283 "Non-address-of operator on non-static member address");
2284 FromType = S.Context.getMemberPointerType(
2285 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2286 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2287 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2288 UO_AddrOf &&
2289 "Non-address-of operator for overloaded function expression");
2290 FromType = S.Context.getPointerType(FromType);
2291 }
2292 } else {
2293 return false;
2294 }
2295 }
2296
2297 bool argIsLValue = From->isGLValue();
2298 // To handle conversion from ArrayParameterType to ConstantArrayType
2299 // this block must be above the one below because Array parameters
2300 // do not decay and when handling HLSLOutArgExprs and
2301 // the From expression is an LValue.
2302 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2303 ToType->isConstantArrayType()) {
2304 // HLSL constant array parameters do not decay, so if the argument is a
2305 // constant array and the parameter is an ArrayParameterType we have special
2306 // handling here.
2307 if (ToType->isArrayParameterType()) {
2308 FromType = S.Context.getArrayParameterType(FromType);
2309 } else if (FromType->isArrayParameterType()) {
2310 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2311 FromType = APT->getConstantArrayType(S.Context);
2312 }
2313
2315
2316 // Don't consider qualifiers, which include things like address spaces
2317 if (FromType.getCanonicalType().getUnqualifiedType() !=
2319 return false;
2320
2321 SCS.setAllToTypes(ToType);
2322 return true;
2323 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2324 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2325 // Lvalue-to-rvalue conversion (C++11 4.1):
2326 // A glvalue (3.10) of a non-function, non-array type T can
2327 // be converted to a prvalue.
2328
2330
2331 // C11 6.3.2.1p2:
2332 // ... if the lvalue has atomic type, the value has the non-atomic version
2333 // of the type of the lvalue ...
2334 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2335 FromType = Atomic->getValueType();
2336
2337 // If T is a non-class type, the type of the rvalue is the
2338 // cv-unqualified version of T. Otherwise, the type of the rvalue
2339 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2340 // just strip the qualifiers because they don't matter.
2341 FromType = FromType.getUnqualifiedType();
2342 } else if (FromType->isArrayType()) {
2343 // Array-to-pointer conversion (C++ 4.2)
2345
2346 // An lvalue or rvalue of type "array of N T" or "array of unknown
2347 // bound of T" can be converted to an rvalue of type "pointer to
2348 // T" (C++ 4.2p1).
2349 FromType = S.Context.getArrayDecayedType(FromType);
2350
2351 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2352 // This conversion is deprecated in C++03 (D.4)
2354
2355 // For the purpose of ranking in overload resolution
2356 // (13.3.3.1.1), this conversion is considered an
2357 // array-to-pointer conversion followed by a qualification
2358 // conversion (4.4). (C++ 4.2p2)
2359 SCS.Second = ICK_Identity;
2362 SCS.setAllToTypes(FromType);
2363 return true;
2364 }
2365 } else if (FromType->isFunctionType() && argIsLValue) {
2366 // Function-to-pointer conversion (C++ 4.3).
2368
2369 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2370 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2372 return false;
2373
2374 // An lvalue of function type T can be converted to an rvalue of
2375 // type "pointer to T." The result is a pointer to the
2376 // function. (C++ 4.3p1).
2377 FromType = S.Context.getPointerType(FromType);
2378 } else {
2379 // We don't require any conversions for the first step.
2380 SCS.First = ICK_Identity;
2381 }
2382 SCS.setToType(0, FromType);
2383
2384 // The second conversion can be an integral promotion, floating
2385 // point promotion, integral conversion, floating point conversion,
2386 // floating-integral conversion, pointer conversion,
2387 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2388 // For overloading in C, this can also be a "compatible-type"
2389 // conversion.
2390 bool IncompatibleObjC = false;
2392 ImplicitConversionKind DimensionICK = ICK_Identity;
2393 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2394 // The unqualified versions of the types are the same: there's no
2395 // conversion to do.
2396 SCS.Second = ICK_Identity;
2397 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2398 // Integral promotion (C++ 4.5).
2400 FromType = ToType.getUnqualifiedType();
2401 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2402 // Floating point promotion (C++ 4.6).
2404 FromType = ToType.getUnqualifiedType();
2405 } else if (S.IsComplexPromotion(FromType, ToType)) {
2406 // Complex promotion (Clang extension)
2408 FromType = ToType.getUnqualifiedType();
2409 } else if (ToType->isBooleanType() &&
2410 (FromType->isArithmeticType() ||
2411 FromType->isAnyPointerType() ||
2412 FromType->isBlockPointerType() ||
2413 FromType->isMemberPointerType())) {
2414 // Boolean conversions (C++ 4.12).
2416 FromType = S.Context.BoolTy;
2417 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2418 ToType->isIntegralType(S.Context)) {
2419 // Integral conversions (C++ 4.7).
2421 FromType = ToType.getUnqualifiedType();
2422 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2423 // Complex conversions (C99 6.3.1.6)
2425 FromType = ToType.getUnqualifiedType();
2426 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2427 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2428 // Complex-real conversions (C99 6.3.1.7)
2430 FromType = ToType.getUnqualifiedType();
2431 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2432 // Floating point conversions (C++ 4.8).
2434 FromType = ToType.getUnqualifiedType();
2435 } else if ((FromType->isRealFloatingType() &&
2436 ToType->isIntegralType(S.Context)) ||
2438 ToType->isRealFloatingType())) {
2439
2440 // Floating-integral conversions (C++ 4.9).
2442 FromType = ToType.getUnqualifiedType();
2443 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2445 } else if (AllowObjCWritebackConversion &&
2446 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2448 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2449 FromType, IncompatibleObjC)) {
2450 // Pointer conversions (C++ 4.10).
2452 SCS.IncompatibleObjC = IncompatibleObjC;
2453 FromType = FromType.getUnqualifiedType();
2454 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2455 InOverloadResolution, FromType)) {
2456 // Pointer to member conversions (4.11).
2458 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2459 From, InOverloadResolution, CStyle)) {
2460 SCS.Second = SecondICK;
2461 SCS.Dimension = DimensionICK;
2462 FromType = ToType.getUnqualifiedType();
2463 } else if (!S.getLangOpts().CPlusPlus &&
2464 S.Context.typesAreCompatible(ToType, FromType)) {
2465 // Compatible conversions (Clang extension for C function overloading)
2467 FromType = ToType.getUnqualifiedType();
2469 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2471 FromType = ToType;
2472 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2473 CStyle)) {
2474 // tryAtomicConversion has updated the standard conversion sequence
2475 // appropriately.
2476 return true;
2477 } else if (ToType->isEventT() &&
2479 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2481 FromType = ToType;
2482 } else if (ToType->isQueueT() &&
2484 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2486 FromType = ToType;
2487 } else if (ToType->isSamplerT() &&
2490 FromType = ToType;
2491 } else if ((ToType->isFixedPointType() &&
2492 FromType->isConvertibleToFixedPointType()) ||
2493 (FromType->isFixedPointType() &&
2494 ToType->isConvertibleToFixedPointType())) {
2496 FromType = ToType;
2497 } else {
2498 // No second conversion required.
2499 SCS.Second = ICK_Identity;
2500 }
2501 SCS.setToType(1, FromType);
2502
2503 // The third conversion can be a function pointer conversion or a
2504 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2505 bool ObjCLifetimeConversion;
2506 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2507 // Function pointer conversions (removing 'noexcept') including removal of
2508 // 'noreturn' (Clang extension).
2510 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2511 ObjCLifetimeConversion)) {
2513 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2514 FromType = ToType;
2515 } else {
2516 // No conversion required
2517 SCS.Third = ICK_Identity;
2518 }
2519
2520 // C++ [over.best.ics]p6:
2521 // [...] Any difference in top-level cv-qualification is
2522 // subsumed by the initialization itself and does not constitute
2523 // a conversion. [...]
2524 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2525 QualType CanonTo = S.Context.getCanonicalType(ToType);
2526 if (CanonFrom.getLocalUnqualifiedType()
2527 == CanonTo.getLocalUnqualifiedType() &&
2528 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2529 FromType = ToType;
2530 CanonFrom = CanonTo;
2531 }
2532
2533 SCS.setToType(2, FromType);
2534
2535 // If we have not converted the argument type to the parameter type,
2536 // this is a bad conversion sequence, unless we're resolving an overload in C.
2537 //
2538 // Permit conversions from a function without `cfi_unchecked_callee` to a
2539 // function with `cfi_unchecked_callee`.
2540 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(CanonFrom, CanonTo))
2541 return true;
2542
2543 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2544 return false;
2545
2546 ExprResult ER = ExprResult{From};
2547 AssignConvertType Conv =
2549 /*Diagnose=*/false,
2550 /*DiagnoseCFAudited=*/false,
2551 /*ConvertRHS=*/false);
2552 ImplicitConversionKind SecondConv;
2553 switch (Conv) {
2555 case AssignConvertType::
2556 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2557 SecondConv = ICK_C_Only_Conversion;
2558 break;
2559 // For our purposes, discarding qualifiers is just as bad as using an
2560 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2561 // qualifiers, as well.
2566 break;
2567 default:
2568 return false;
2569 }
2570
2571 // First can only be an lvalue conversion, so we pretend that this was the
2572 // second conversion. First should already be valid from earlier in the
2573 // function.
2574 SCS.Second = SecondConv;
2575 SCS.setToType(1, ToType);
2576
2577 // Third is Identity, because Second should rank us worse than any other
2578 // conversion. This could also be ICK_Qualification, but it's simpler to just
2579 // lump everything in with the second conversion, and we don't gain anything
2580 // from making this ICK_Qualification.
2581 SCS.Third = ICK_Identity;
2582 SCS.setToType(2, ToType);
2583 return true;
2584}
2585
2586static bool
2588 QualType &ToType,
2589 bool InOverloadResolution,
2591 bool CStyle) {
2592
2593 const RecordType *UT = ToType->getAsUnionType();
2594 if (!UT)
2595 return false;
2596 // The field to initialize within the transparent union.
2597 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2598 if (!UD->hasAttr<TransparentUnionAttr>())
2599 return false;
2600 // It's compatible if the expression matches any of the fields.
2601 for (const auto *it : UD->fields()) {
2602 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2603 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2604 ToType = it->getType();
2605 return true;
2606 }
2607 }
2608 return false;
2609}
2610
2611bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2612 const BuiltinType *To = ToType->getAs<BuiltinType>();
2613 // All integers are built-in.
2614 if (!To) {
2615 return false;
2616 }
2617
2618 // An rvalue of type char, signed char, unsigned char, short int, or
2619 // unsigned short int can be converted to an rvalue of type int if
2620 // int can represent all the values of the source type; otherwise,
2621 // the source rvalue can be converted to an rvalue of type unsigned
2622 // int (C++ 4.5p1).
2623 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2624 !FromType->isEnumeralType()) {
2625 if ( // We can promote any signed, promotable integer type to an int
2626 (FromType->isSignedIntegerType() ||
2627 // We can promote any unsigned integer type whose size is
2628 // less than int to an int.
2629 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2630 return To->getKind() == BuiltinType::Int;
2631 }
2632
2633 return To->getKind() == BuiltinType::UInt;
2634 }
2635
2636 // C++11 [conv.prom]p3:
2637 // A prvalue of an unscoped enumeration type whose underlying type is not
2638 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2639 // following types that can represent all the values of the enumeration
2640 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2641 // unsigned int, long int, unsigned long int, long long int, or unsigned
2642 // long long int. If none of the types in that list can represent all the
2643 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2644 // type can be converted to an rvalue a prvalue of the extended integer type
2645 // with lowest integer conversion rank (4.13) greater than the rank of long
2646 // long in which all the values of the enumeration can be represented. If
2647 // there are two such extended types, the signed one is chosen.
2648 // C++11 [conv.prom]p4:
2649 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2650 // can be converted to a prvalue of its underlying type. Moreover, if
2651 // integral promotion can be applied to its underlying type, a prvalue of an
2652 // unscoped enumeration type whose underlying type is fixed can also be
2653 // converted to a prvalue of the promoted underlying type.
2654 if (const auto *FromED = FromType->getAsEnumDecl()) {
2655 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2656 // provided for a scoped enumeration.
2657 if (FromED->isScoped())
2658 return false;
2659
2660 // We can perform an integral promotion to the underlying type of the enum,
2661 // even if that's not the promoted type. Note that the check for promoting
2662 // the underlying type is based on the type alone, and does not consider
2663 // the bitfield-ness of the actual source expression.
2664 if (FromED->isFixed()) {
2665 QualType Underlying = FromED->getIntegerType();
2666 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2667 IsIntegralPromotion(nullptr, Underlying, ToType);
2668 }
2669
2670 // We have already pre-calculated the promotion type, so this is trivial.
2671 if (ToType->isIntegerType() &&
2672 isCompleteType(From->getBeginLoc(), FromType))
2673 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2674
2675 // C++ [conv.prom]p5:
2676 // If the bit-field has an enumerated type, it is treated as any other
2677 // value of that type for promotion purposes.
2678 //
2679 // ... so do not fall through into the bit-field checks below in C++.
2680 if (getLangOpts().CPlusPlus)
2681 return false;
2682 }
2683
2684 // C++0x [conv.prom]p2:
2685 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2686 // to an rvalue a prvalue of the first of the following types that can
2687 // represent all the values of its underlying type: int, unsigned int,
2688 // long int, unsigned long int, long long int, or unsigned long long int.
2689 // If none of the types in that list can represent all the values of its
2690 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2691 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2692 // type.
2693 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2694 ToType->isIntegerType()) {
2695 // Determine whether the type we're converting from is signed or
2696 // unsigned.
2697 bool FromIsSigned = FromType->isSignedIntegerType();
2698 uint64_t FromSize = Context.getTypeSize(FromType);
2699
2700 // The types we'll try to promote to, in the appropriate
2701 // order. Try each of these types.
2702 QualType PromoteTypes[6] = {
2703 Context.IntTy, Context.UnsignedIntTy,
2704 Context.LongTy, Context.UnsignedLongTy ,
2705 Context.LongLongTy, Context.UnsignedLongLongTy
2706 };
2707 for (int Idx = 0; Idx < 6; ++Idx) {
2708 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2709 if (FromSize < ToSize ||
2710 (FromSize == ToSize &&
2711 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2712 // We found the type that we can promote to. If this is the
2713 // type we wanted, we have a promotion. Otherwise, no
2714 // promotion.
2715 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2716 }
2717 }
2718 }
2719
2720 // An rvalue for an integral bit-field (9.6) can be converted to an
2721 // rvalue of type int if int can represent all the values of the
2722 // bit-field; otherwise, it can be converted to unsigned int if
2723 // unsigned int can represent all the values of the bit-field. If
2724 // the bit-field is larger yet, no integral promotion applies to
2725 // it. If the bit-field has an enumerated type, it is treated as any
2726 // other value of that type for promotion purposes (C++ 4.5p3).
2727 // FIXME: We should delay checking of bit-fields until we actually perform the
2728 // conversion.
2729 //
2730 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2731 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2732 // bit-fields and those whose underlying type is larger than int) for GCC
2733 // compatibility.
2734 if (From) {
2735 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2736 std::optional<llvm::APSInt> BitWidth;
2737 if (FromType->isIntegralType(Context) &&
2738 (BitWidth =
2739 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2740 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2741 ToSize = Context.getTypeSize(ToType);
2742
2743 // Are we promoting to an int from a bitfield that fits in an int?
2744 if (*BitWidth < ToSize ||
2745 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2746 return To->getKind() == BuiltinType::Int;
2747 }
2748
2749 // Are we promoting to an unsigned int from an unsigned bitfield
2750 // that fits into an unsigned int?
2751 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2752 return To->getKind() == BuiltinType::UInt;
2753 }
2754
2755 return false;
2756 }
2757 }
2758 }
2759
2760 // An rvalue of type bool can be converted to an rvalue of type int,
2761 // with false becoming zero and true becoming one (C++ 4.5p4).
2762 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2763 return true;
2764 }
2765
2766 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2767 // integral type.
2768 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2769 ToType->isIntegerType())
2770 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2771
2772 return false;
2773}
2774
2776 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2777 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2778 /// An rvalue of type float can be converted to an rvalue of type
2779 /// double. (C++ 4.6p1).
2780 if (FromBuiltin->getKind() == BuiltinType::Float &&
2781 ToBuiltin->getKind() == BuiltinType::Double)
2782 return true;
2783
2784 // C99 6.3.1.5p1:
2785 // When a float is promoted to double or long double, or a
2786 // double is promoted to long double [...].
2787 if (!getLangOpts().CPlusPlus &&
2788 (FromBuiltin->getKind() == BuiltinType::Float ||
2789 FromBuiltin->getKind() == BuiltinType::Double) &&
2790 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2791 ToBuiltin->getKind() == BuiltinType::Float128 ||
2792 ToBuiltin->getKind() == BuiltinType::Ibm128))
2793 return true;
2794
2795 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2796 // or not native half types are enabled.
2797 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2798 (ToBuiltin->getKind() == BuiltinType::Float ||
2799 ToBuiltin->getKind() == BuiltinType::Double))
2800 return true;
2801
2802 // Half can be promoted to float.
2803 if (!getLangOpts().NativeHalfType &&
2804 FromBuiltin->getKind() == BuiltinType::Half &&
2805 ToBuiltin->getKind() == BuiltinType::Float)
2806 return true;
2807 }
2808
2809 return false;
2810}
2811
2813 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2814 if (!FromComplex)
2815 return false;
2816
2817 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2818 if (!ToComplex)
2819 return false;
2820
2821 return IsFloatingPointPromotion(FromComplex->getElementType(),
2822 ToComplex->getElementType()) ||
2823 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2824 ToComplex->getElementType());
2825}
2826
2827/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2828/// the pointer type FromPtr to a pointer to type ToPointee, with the
2829/// same type qualifiers as FromPtr has on its pointee type. ToType,
2830/// if non-empty, will be a pointer to ToType that may or may not have
2831/// the right set of qualifiers on its pointee.
2832///
2833static QualType
2835 QualType ToPointee, QualType ToType,
2836 ASTContext &Context,
2837 bool StripObjCLifetime = false) {
2838 assert((FromPtr->getTypeClass() == Type::Pointer ||
2839 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2840 "Invalid similarly-qualified pointer type");
2841
2842 /// Conversions to 'id' subsume cv-qualifier conversions.
2843 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2844 return ToType.getUnqualifiedType();
2845
2846 QualType CanonFromPointee
2847 = Context.getCanonicalType(FromPtr->getPointeeType());
2848 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2849 Qualifiers Quals = CanonFromPointee.getQualifiers();
2850
2851 if (StripObjCLifetime)
2852 Quals.removeObjCLifetime();
2853
2854 // Exact qualifier match -> return the pointer type we're converting to.
2855 if (CanonToPointee.getLocalQualifiers() == Quals) {
2856 // ToType is exactly what we need. Return it.
2857 if (!ToType.isNull())
2858 return ToType.getUnqualifiedType();
2859
2860 // Build a pointer to ToPointee. It has the right qualifiers
2861 // already.
2862 if (isa<ObjCObjectPointerType>(ToType))
2863 return Context.getObjCObjectPointerType(ToPointee);
2864 return Context.getPointerType(ToPointee);
2865 }
2866
2867 // Just build a canonical type that has the right qualifiers.
2868 QualType QualifiedCanonToPointee
2869 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2870
2871 if (isa<ObjCObjectPointerType>(ToType))
2872 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2873 return Context.getPointerType(QualifiedCanonToPointee);
2874}
2875
2877 bool InOverloadResolution,
2878 ASTContext &Context) {
2879 // Handle value-dependent integral null pointer constants correctly.
2880 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2881 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2883 return !InOverloadResolution;
2884
2885 return Expr->isNullPointerConstant(Context,
2886 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2888}
2889
2891 bool InOverloadResolution,
2892 QualType& ConvertedType,
2893 bool &IncompatibleObjC) {
2894 IncompatibleObjC = false;
2895 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2896 IncompatibleObjC))
2897 return true;
2898
2899 // Conversion from a null pointer constant to any Objective-C pointer type.
2900 if (ToType->isObjCObjectPointerType() &&
2901 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2902 ConvertedType = ToType;
2903 return true;
2904 }
2905
2906 // Blocks: Block pointers can be converted to void*.
2907 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2908 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2909 ConvertedType = ToType;
2910 return true;
2911 }
2912 // Blocks: A null pointer constant can be converted to a block
2913 // pointer type.
2914 if (ToType->isBlockPointerType() &&
2915 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2916 ConvertedType = ToType;
2917 return true;
2918 }
2919
2920 // If the left-hand-side is nullptr_t, the right side can be a null
2921 // pointer constant.
2922 if (ToType->isNullPtrType() &&
2923 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2924 ConvertedType = ToType;
2925 return true;
2926 }
2927
2928 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2929 if (!ToTypePtr)
2930 return false;
2931
2932 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2933 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2934 ConvertedType = ToType;
2935 return true;
2936 }
2937
2938 // Beyond this point, both types need to be pointers
2939 // , including objective-c pointers.
2940 QualType ToPointeeType = ToTypePtr->getPointeeType();
2941 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2942 !getLangOpts().ObjCAutoRefCount) {
2943 ConvertedType = BuildSimilarlyQualifiedPointerType(
2944 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2945 Context);
2946 return true;
2947 }
2948 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2949 if (!FromTypePtr)
2950 return false;
2951
2952 QualType FromPointeeType = FromTypePtr->getPointeeType();
2953
2954 // If the unqualified pointee types are the same, this can't be a
2955 // pointer conversion, so don't do all of the work below.
2956 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2957 return false;
2958
2959 // An rvalue of type "pointer to cv T," where T is an object type,
2960 // can be converted to an rvalue of type "pointer to cv void" (C++
2961 // 4.10p2).
2962 if (FromPointeeType->isIncompleteOrObjectType() &&
2963 ToPointeeType->isVoidType()) {
2964 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2965 ToPointeeType,
2966 ToType, Context,
2967 /*StripObjCLifetime=*/true);
2968 return true;
2969 }
2970
2971 // MSVC allows implicit function to void* type conversion.
2972 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2973 ToPointeeType->isVoidType()) {
2974 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2975 ToPointeeType,
2976 ToType, Context);
2977 return true;
2978 }
2979
2980 // When we're overloading in C, we allow a special kind of pointer
2981 // conversion for compatible-but-not-identical pointee types.
2982 if (!getLangOpts().CPlusPlus &&
2983 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2984 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2985 ToPointeeType,
2986 ToType, Context);
2987 return true;
2988 }
2989
2990 // C++ [conv.ptr]p3:
2991 //
2992 // An rvalue of type "pointer to cv D," where D is a class type,
2993 // can be converted to an rvalue of type "pointer to cv B," where
2994 // B is a base class (clause 10) of D. If B is an inaccessible
2995 // (clause 11) or ambiguous (10.2) base class of D, a program that
2996 // necessitates this conversion is ill-formed. The result of the
2997 // conversion is a pointer to the base class sub-object of the
2998 // derived class object. The null pointer value is converted to
2999 // the null pointer value of the destination type.
3000 //
3001 // Note that we do not check for ambiguity or inaccessibility
3002 // here. That is handled by CheckPointerConversion.
3003 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3004 ToPointeeType->isRecordType() &&
3005 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3006 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3007 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3008 ToPointeeType,
3009 ToType, Context);
3010 return true;
3011 }
3012
3013 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3014 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3015 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3016 ToPointeeType,
3017 ToType, Context);
3018 return true;
3019 }
3020
3021 return false;
3022}
3023
3024/// Adopt the given qualifiers for the given type.
3026 Qualifiers TQs = T.getQualifiers();
3027
3028 // Check whether qualifiers already match.
3029 if (TQs == Qs)
3030 return T;
3031
3032 if (Qs.compatiblyIncludes(TQs, Context))
3033 return Context.getQualifiedType(T, Qs);
3034
3035 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3036}
3037
3039 QualType& ConvertedType,
3040 bool &IncompatibleObjC) {
3041 if (!getLangOpts().ObjC)
3042 return false;
3043
3044 // The set of qualifiers on the type we're converting from.
3045 Qualifiers FromQualifiers = FromType.getQualifiers();
3046
3047 // First, we handle all conversions on ObjC object pointer types.
3048 const ObjCObjectPointerType* ToObjCPtr =
3049 ToType->getAs<ObjCObjectPointerType>();
3050 const ObjCObjectPointerType *FromObjCPtr =
3051 FromType->getAs<ObjCObjectPointerType>();
3052
3053 if (ToObjCPtr && FromObjCPtr) {
3054 // If the pointee types are the same (ignoring qualifications),
3055 // then this is not a pointer conversion.
3056 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3057 FromObjCPtr->getPointeeType()))
3058 return false;
3059
3060 // Conversion between Objective-C pointers.
3061 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3062 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3063 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3064 if (getLangOpts().CPlusPlus && LHS && RHS &&
3066 FromObjCPtr->getPointeeType(), getASTContext()))
3067 return false;
3068 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3069 ToObjCPtr->getPointeeType(),
3070 ToType, Context);
3071 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3072 return true;
3073 }
3074
3075 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3076 // Okay: this is some kind of implicit downcast of Objective-C
3077 // interfaces, which is permitted. However, we're going to
3078 // complain about it.
3079 IncompatibleObjC = true;
3080 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3081 ToObjCPtr->getPointeeType(),
3082 ToType, Context);
3083 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3084 return true;
3085 }
3086 }
3087 // Beyond this point, both types need to be C pointers or block pointers.
3088 QualType ToPointeeType;
3089 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3090 ToPointeeType = ToCPtr->getPointeeType();
3091 else if (const BlockPointerType *ToBlockPtr =
3092 ToType->getAs<BlockPointerType>()) {
3093 // Objective C++: We're able to convert from a pointer to any object
3094 // to a block pointer type.
3095 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3096 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3097 return true;
3098 }
3099 ToPointeeType = ToBlockPtr->getPointeeType();
3100 }
3101 else if (FromType->getAs<BlockPointerType>() &&
3102 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3103 // Objective C++: We're able to convert from a block pointer type to a
3104 // pointer to any object.
3105 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3106 return true;
3107 }
3108 else
3109 return false;
3110
3111 QualType FromPointeeType;
3112 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3113 FromPointeeType = FromCPtr->getPointeeType();
3114 else if (const BlockPointerType *FromBlockPtr =
3115 FromType->getAs<BlockPointerType>())
3116 FromPointeeType = FromBlockPtr->getPointeeType();
3117 else
3118 return false;
3119
3120 // If we have pointers to pointers, recursively check whether this
3121 // is an Objective-C conversion.
3122 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3123 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3124 IncompatibleObjC)) {
3125 // We always complain about this conversion.
3126 IncompatibleObjC = true;
3127 ConvertedType = Context.getPointerType(ConvertedType);
3128 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3129 return true;
3130 }
3131 // Allow conversion of pointee being objective-c pointer to another one;
3132 // as in I* to id.
3133 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3134 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3135 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3136 IncompatibleObjC)) {
3137
3138 ConvertedType = Context.getPointerType(ConvertedType);
3139 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3140 return true;
3141 }
3142
3143 // If we have pointers to functions or blocks, check whether the only
3144 // differences in the argument and result types are in Objective-C
3145 // pointer conversions. If so, we permit the conversion (but
3146 // complain about it).
3147 const FunctionProtoType *FromFunctionType
3148 = FromPointeeType->getAs<FunctionProtoType>();
3149 const FunctionProtoType *ToFunctionType
3150 = ToPointeeType->getAs<FunctionProtoType>();
3151 if (FromFunctionType && ToFunctionType) {
3152 // If the function types are exactly the same, this isn't an
3153 // Objective-C pointer conversion.
3154 if (Context.getCanonicalType(FromPointeeType)
3155 == Context.getCanonicalType(ToPointeeType))
3156 return false;
3157
3158 // Perform the quick checks that will tell us whether these
3159 // function types are obviously different.
3160 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3161 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3162 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3163 return false;
3164
3165 bool HasObjCConversion = false;
3166 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3167 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3168 // Okay, the types match exactly. Nothing to do.
3169 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3170 ToFunctionType->getReturnType(),
3171 ConvertedType, IncompatibleObjC)) {
3172 // Okay, we have an Objective-C pointer conversion.
3173 HasObjCConversion = true;
3174 } else {
3175 // Function types are too different. Abort.
3176 return false;
3177 }
3178
3179 // Check argument types.
3180 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3181 ArgIdx != NumArgs; ++ArgIdx) {
3182 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3183 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3184 if (Context.getCanonicalType(FromArgType)
3185 == Context.getCanonicalType(ToArgType)) {
3186 // Okay, the types match exactly. Nothing to do.
3187 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3188 ConvertedType, IncompatibleObjC)) {
3189 // Okay, we have an Objective-C pointer conversion.
3190 HasObjCConversion = true;
3191 } else {
3192 // Argument types are too different. Abort.
3193 return false;
3194 }
3195 }
3196
3197 if (HasObjCConversion) {
3198 // We had an Objective-C conversion. Allow this pointer
3199 // conversion, but complain about it.
3200 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3201 IncompatibleObjC = true;
3202 return true;
3203 }
3204 }
3205
3206 return false;
3207}
3208
3210 QualType& ConvertedType) {
3211 QualType ToPointeeType;
3212 if (const BlockPointerType *ToBlockPtr =
3213 ToType->getAs<BlockPointerType>())
3214 ToPointeeType = ToBlockPtr->getPointeeType();
3215 else
3216 return false;
3217
3218 QualType FromPointeeType;
3219 if (const BlockPointerType *FromBlockPtr =
3220 FromType->getAs<BlockPointerType>())
3221 FromPointeeType = FromBlockPtr->getPointeeType();
3222 else
3223 return false;
3224 // We have pointer to blocks, check whether the only
3225 // differences in the argument and result types are in Objective-C
3226 // pointer conversions. If so, we permit the conversion.
3227
3228 const FunctionProtoType *FromFunctionType
3229 = FromPointeeType->getAs<FunctionProtoType>();
3230 const FunctionProtoType *ToFunctionType
3231 = ToPointeeType->getAs<FunctionProtoType>();
3232
3233 if (!FromFunctionType || !ToFunctionType)
3234 return false;
3235
3236 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3237 return true;
3238
3239 // Perform the quick checks that will tell us whether these
3240 // function types are obviously different.
3241 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3242 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3243 return false;
3244
3245 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3246 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3247 if (FromEInfo != ToEInfo)
3248 return false;
3249
3250 bool IncompatibleObjC = false;
3251 if (Context.hasSameType(FromFunctionType->getReturnType(),
3252 ToFunctionType->getReturnType())) {
3253 // Okay, the types match exactly. Nothing to do.
3254 } else {
3255 QualType RHS = FromFunctionType->getReturnType();
3256 QualType LHS = ToFunctionType->getReturnType();
3257 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3258 !RHS.hasQualifiers() && LHS.hasQualifiers())
3259 LHS = LHS.getUnqualifiedType();
3260
3261 if (Context.hasSameType(RHS,LHS)) {
3262 // OK exact match.
3263 } else if (isObjCPointerConversion(RHS, LHS,
3264 ConvertedType, IncompatibleObjC)) {
3265 if (IncompatibleObjC)
3266 return false;
3267 // Okay, we have an Objective-C pointer conversion.
3268 }
3269 else
3270 return false;
3271 }
3272
3273 // Check argument types.
3274 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3275 ArgIdx != NumArgs; ++ArgIdx) {
3276 IncompatibleObjC = false;
3277 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3278 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3279 if (Context.hasSameType(FromArgType, ToArgType)) {
3280 // Okay, the types match exactly. Nothing to do.
3281 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3282 ConvertedType, IncompatibleObjC)) {
3283 if (IncompatibleObjC)
3284 return false;
3285 // Okay, we have an Objective-C pointer conversion.
3286 } else
3287 // Argument types are too different. Abort.
3288 return false;
3289 }
3290
3292 bool CanUseToFPT, CanUseFromFPT;
3293 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3294 CanUseToFPT, CanUseFromFPT,
3295 NewParamInfos))
3296 return false;
3297
3298 ConvertedType = ToType;
3299 return true;
3300}
3301
3302enum {
3310};
3311
3312/// Attempts to get the FunctionProtoType from a Type. Handles
3313/// MemberFunctionPointers properly.
3315 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3316 return FPT;
3317
3318 if (auto *MPT = FromType->getAs<MemberPointerType>())
3319 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3320
3321 return nullptr;
3322}
3323
3325 QualType FromType, QualType ToType) {
3326 // If either type is not valid, include no extra info.
3327 if (FromType.isNull() || ToType.isNull()) {
3328 PDiag << ft_default;
3329 return;
3330 }
3331
3332 // Get the function type from the pointers.
3333 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3334 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3335 *ToMember = ToType->castAs<MemberPointerType>();
3336 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3337 ToMember->getMostRecentCXXRecordDecl())) {
3339 if (ToMember->isSugared())
3340 PDiag << Context.getCanonicalTagType(
3341 ToMember->getMostRecentCXXRecordDecl());
3342 else
3343 PDiag << ToMember->getQualifier();
3344 if (FromMember->isSugared())
3345 PDiag << Context.getCanonicalTagType(
3346 FromMember->getMostRecentCXXRecordDecl());
3347 else
3348 PDiag << FromMember->getQualifier();
3349 return;
3350 }
3351 FromType = FromMember->getPointeeType();
3352 ToType = ToMember->getPointeeType();
3353 }
3354
3355 if (FromType->isPointerType())
3356 FromType = FromType->getPointeeType();
3357 if (ToType->isPointerType())
3358 ToType = ToType->getPointeeType();
3359
3360 // Remove references.
3361 FromType = FromType.getNonReferenceType();
3362 ToType = ToType.getNonReferenceType();
3363
3364 // Don't print extra info for non-specialized template functions.
3365 if (FromType->isInstantiationDependentType() &&
3366 !FromType->getAs<TemplateSpecializationType>()) {
3367 PDiag << ft_default;
3368 return;
3369 }
3370
3371 // No extra info for same types.
3372 if (Context.hasSameType(FromType, ToType)) {
3373 PDiag << ft_default;
3374 return;
3375 }
3376
3377 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3378 *ToFunction = tryGetFunctionProtoType(ToType);
3379
3380 // Both types need to be function types.
3381 if (!FromFunction || !ToFunction) {
3382 PDiag << ft_default;
3383 return;
3384 }
3385
3386 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3387 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3388 << FromFunction->getNumParams();
3389 return;
3390 }
3391
3392 // Handle different parameter types.
3393 unsigned ArgPos;
3394 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3395 PDiag << ft_parameter_mismatch << ArgPos + 1
3396 << ToFunction->getParamType(ArgPos)
3397 << FromFunction->getParamType(ArgPos);
3398 return;
3399 }
3400
3401 // Handle different return type.
3402 if (!Context.hasSameType(FromFunction->getReturnType(),
3403 ToFunction->getReturnType())) {
3404 PDiag << ft_return_type << ToFunction->getReturnType()
3405 << FromFunction->getReturnType();
3406 return;
3407 }
3408
3409 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3410 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3411 << FromFunction->getMethodQuals();
3412 return;
3413 }
3414
3415 // Handle exception specification differences on canonical type (in C++17
3416 // onwards).
3418 ->isNothrow() !=
3419 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3420 ->isNothrow()) {
3421 PDiag << ft_noexcept;
3422 return;
3423 }
3424
3425 // Unable to find a difference, so add no extra info.
3426 PDiag << ft_default;
3427}
3428
3430 ArrayRef<QualType> New, unsigned *ArgPos,
3431 bool Reversed) {
3432 assert(llvm::size(Old) == llvm::size(New) &&
3433 "Can't compare parameters of functions with different number of "
3434 "parameters!");
3435
3436 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3437 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3438 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3439
3440 // Ignore address spaces in pointee type. This is to disallow overloading
3441 // on __ptr32/__ptr64 address spaces.
3442 QualType OldType =
3443 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3444 QualType NewType =
3445 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3446
3447 if (!Context.hasSameType(OldType, NewType)) {
3448 if (ArgPos)
3449 *ArgPos = Idx;
3450 return false;
3451 }
3452 }
3453 return true;
3454}
3455
3457 const FunctionProtoType *NewType,
3458 unsigned *ArgPos, bool Reversed) {
3459 return FunctionParamTypesAreEqual(OldType->param_types(),
3460 NewType->param_types(), ArgPos, Reversed);
3461}
3462
3464 const FunctionDecl *NewFunction,
3465 unsigned *ArgPos,
3466 bool Reversed) {
3467
3468 if (OldFunction->getNumNonObjectParams() !=
3469 NewFunction->getNumNonObjectParams())
3470 return false;
3471
3472 unsigned OldIgnore =
3474 unsigned NewIgnore =
3476
3477 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3478 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3479
3480 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3481 NewPT->param_types().slice(NewIgnore),
3482 ArgPos, Reversed);
3483}
3484
3486 CastKind &Kind,
3487 CXXCastPath& BasePath,
3488 bool IgnoreBaseAccess,
3489 bool Diagnose) {
3490 QualType FromType = From->getType();
3491 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3492
3493 Kind = CK_BitCast;
3494
3495 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3498 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3499 DiagRuntimeBehavior(From->getExprLoc(), From,
3500 PDiag(diag::warn_impcast_bool_to_null_pointer)
3501 << ToType << From->getSourceRange());
3502 else if (!isUnevaluatedContext())
3503 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3504 << ToType << From->getSourceRange();
3505 }
3506 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3507 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3508 QualType FromPointeeType = FromPtrType->getPointeeType(),
3509 ToPointeeType = ToPtrType->getPointeeType();
3510
3511 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3512 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3513 // We must have a derived-to-base conversion. Check an
3514 // ambiguous or inaccessible conversion.
3515 unsigned InaccessibleID = 0;
3516 unsigned AmbiguousID = 0;
3517 if (Diagnose) {
3518 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3519 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3520 }
3522 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3523 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3524 &BasePath, IgnoreBaseAccess))
3525 return true;
3526
3527 // The conversion was successful.
3528 Kind = CK_DerivedToBase;
3529 }
3530
3531 if (Diagnose && !IsCStyleOrFunctionalCast &&
3532 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3533 assert(getLangOpts().MSVCCompat &&
3534 "this should only be possible with MSVCCompat!");
3535 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3536 << From->getSourceRange();
3537 }
3538 }
3539 } else if (const ObjCObjectPointerType *ToPtrType =
3540 ToType->getAs<ObjCObjectPointerType>()) {
3541 if (const ObjCObjectPointerType *FromPtrType =
3542 FromType->getAs<ObjCObjectPointerType>()) {
3543 // Objective-C++ conversions are always okay.
3544 // FIXME: We should have a different class of conversions for the
3545 // Objective-C++ implicit conversions.
3546 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3547 return false;
3548 } else if (FromType->isBlockPointerType()) {
3549 Kind = CK_BlockPointerToObjCPointerCast;
3550 } else {
3551 Kind = CK_CPointerToObjCPointerCast;
3552 }
3553 } else if (ToType->isBlockPointerType()) {
3554 if (!FromType->isBlockPointerType())
3555 Kind = CK_AnyPointerToBlockPointerCast;
3556 }
3557
3558 // We shouldn't fall into this case unless it's valid for other
3559 // reasons.
3561 Kind = CK_NullToPointer;
3562
3563 return false;
3564}
3565
3567 QualType ToType,
3568 bool InOverloadResolution,
3569 QualType &ConvertedType) {
3570 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3571 if (!ToTypePtr)
3572 return false;
3573
3574 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3576 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3578 ConvertedType = ToType;
3579 return true;
3580 }
3581
3582 // Otherwise, both types have to be member pointers.
3583 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3584 if (!FromTypePtr)
3585 return false;
3586
3587 // A pointer to member of B can be converted to a pointer to member of D,
3588 // where D is derived from B (C++ 4.11p2).
3589 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3590 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3591
3592 if (!declaresSameEntity(FromClass, ToClass) &&
3593 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3594 ConvertedType = Context.getMemberPointerType(
3595 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3596 return true;
3597 }
3598
3599 return false;
3600}
3601
3603 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3604 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3605 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3606 // Lock down the inheritance model right now in MS ABI, whether or not the
3607 // pointee types are the same.
3608 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3609 (void)isCompleteType(CheckLoc, FromType);
3610 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3611 }
3612
3613 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3614 if (!FromPtrType) {
3615 // This must be a null pointer to member pointer conversion
3616 Kind = CK_NullToMemberPointer;
3618 }
3619
3620 // T == T, modulo cv
3622 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3623 ToPtrType->getPointeeType()))
3625
3626 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3627 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3628
3629 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3630 const CXXRecordDecl *Cls) {
3631 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3632 PD << Qual;
3633 else
3634 PD << Context.getCanonicalTagType(Cls);
3635 };
3636 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3637 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3638 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3639 return PD;
3640 };
3641
3642 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3644 std::swap(Base, Derived);
3645
3646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3647 /*DetectVirtual=*/true);
3648 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3650
3651 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3652 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3653 PD << int(Direction);
3654 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3655 Diag(CheckLoc, PD);
3657 }
3658
3659 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3660 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3661 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3662 Diag(CheckLoc, PD);
3664 }
3665
3666 // Must be a base to derived member conversion.
3667 BuildBasePathArray(Paths, BasePath);
3669 ? CK_DerivedToBaseMemberPointer
3670 : CK_BaseToDerivedMemberPointer;
3671
3672 if (!IgnoreBaseAccess)
3673 switch (CheckBaseClassAccess(
3674 CheckLoc, Base, Derived, Paths.front(),
3676 ? diag::err_upcast_to_inaccessible_base
3677 : diag::err_downcast_from_inaccessible_base,
3678 [&](PartialDiagnostic &PD) {
3679 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3680 DerivedQual = ToPtrType->getQualifier();
3681 if (Direction == MemberPointerConversionDirection::Upcast)
3682 std::swap(BaseQual, DerivedQual);
3683 DiagCls(PD, DerivedQual, Derived);
3684 DiagCls(PD, BaseQual, Base);
3685 })) {
3687 case Sema::AR_delayed:
3688 case Sema::AR_dependent:
3689 // Optimistically assume that the delayed and dependent cases
3690 // will work out.
3691 break;
3692
3695 }
3696
3698}
3699
3700/// Determine whether the lifetime conversion between the two given
3701/// qualifiers sets is nontrivial.
3703 Qualifiers ToQuals) {
3704 // Converting anything to const __unsafe_unretained is trivial.
3705 if (ToQuals.hasConst() &&
3707 return false;
3708
3709 return true;
3710}
3711
3712/// Perform a single iteration of the loop for checking if a qualification
3713/// conversion is valid.
3714///
3715/// Specifically, check whether any change between the qualifiers of \p
3716/// FromType and \p ToType is permissible, given knowledge about whether every
3717/// outer layer is const-qualified.
3719 bool CStyle, bool IsTopLevel,
3720 bool &PreviousToQualsIncludeConst,
3721 bool &ObjCLifetimeConversion,
3722 const ASTContext &Ctx) {
3723 Qualifiers FromQuals = FromType.getQualifiers();
3724 Qualifiers ToQuals = ToType.getQualifiers();
3725
3726 // Ignore __unaligned qualifier.
3727 FromQuals.removeUnaligned();
3728
3729 // Objective-C ARC:
3730 // Check Objective-C lifetime conversions.
3731 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3732 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3733 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3734 ObjCLifetimeConversion = true;
3735 FromQuals.removeObjCLifetime();
3736 ToQuals.removeObjCLifetime();
3737 } else {
3738 // Qualification conversions cannot cast between different
3739 // Objective-C lifetime qualifiers.
3740 return false;
3741 }
3742 }
3743
3744 // Allow addition/removal of GC attributes but not changing GC attributes.
3745 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3746 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3747 FromQuals.removeObjCGCAttr();
3748 ToQuals.removeObjCGCAttr();
3749 }
3750
3751 // __ptrauth qualifiers must match exactly.
3752 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3753 return false;
3754
3755 // -- for every j > 0, if const is in cv 1,j then const is in cv
3756 // 2,j, and similarly for volatile.
3757 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3758 return false;
3759
3760 // If address spaces mismatch:
3761 // - in top level it is only valid to convert to addr space that is a
3762 // superset in all cases apart from C-style casts where we allow
3763 // conversions between overlapping address spaces.
3764 // - in non-top levels it is not a valid conversion.
3765 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3766 (!IsTopLevel ||
3767 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3768 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3769 return false;
3770
3771 // -- if the cv 1,j and cv 2,j are different, then const is in
3772 // every cv for 0 < k < j.
3773 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3774 !PreviousToQualsIncludeConst)
3775 return false;
3776
3777 // The following wording is from C++20, where the result of the conversion
3778 // is T3, not T2.
3779 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3780 // "array of unknown bound of"
3781 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3782 return false;
3783
3784 // -- if the resulting P3,i is different from P1,i [...], then const is
3785 // added to every cv 3_k for 0 < k < i.
3786 if (!CStyle && FromType->isConstantArrayType() &&
3787 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3788 return false;
3789
3790 // Keep track of whether all prior cv-qualifiers in the "to" type
3791 // include const.
3792 PreviousToQualsIncludeConst =
3793 PreviousToQualsIncludeConst && ToQuals.hasConst();
3794 return true;
3795}
3796
3797bool
3799 bool CStyle, bool &ObjCLifetimeConversion) {
3800 FromType = Context.getCanonicalType(FromType);
3801 ToType = Context.getCanonicalType(ToType);
3802 ObjCLifetimeConversion = false;
3803
3804 // If FromType and ToType are the same type, this is not a
3805 // qualification conversion.
3806 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3807 return false;
3808
3809 // (C++ 4.4p4):
3810 // A conversion can add cv-qualifiers at levels other than the first
3811 // in multi-level pointers, subject to the following rules: [...]
3812 bool PreviousToQualsIncludeConst = true;
3813 bool UnwrappedAnyPointer = false;
3814 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3815 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3816 !UnwrappedAnyPointer,
3817 PreviousToQualsIncludeConst,
3818 ObjCLifetimeConversion, getASTContext()))
3819 return false;
3820 UnwrappedAnyPointer = true;
3821 }
3822
3823 // We are left with FromType and ToType being the pointee types
3824 // after unwrapping the original FromType and ToType the same number
3825 // of times. If we unwrapped any pointers, and if FromType and
3826 // ToType have the same unqualified type (since we checked
3827 // qualifiers above), then this is a qualification conversion.
3828 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3829}
3830
3831/// - Determine whether this is a conversion from a scalar type to an
3832/// atomic type.
3833///
3834/// If successful, updates \c SCS's second and third steps in the conversion
3835/// sequence to finish the conversion.
3836static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3837 bool InOverloadResolution,
3839 bool CStyle) {
3840 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3841 if (!ToAtomic)
3842 return false;
3843
3845 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3846 InOverloadResolution, InnerSCS,
3847 CStyle, /*AllowObjCWritebackConversion=*/false))
3848 return false;
3849
3850 SCS.Second = InnerSCS.Second;
3851 SCS.setToType(1, InnerSCS.getToType(1));
3852 SCS.Third = InnerSCS.Third;
3855 SCS.setToType(2, InnerSCS.getToType(2));
3856 return true;
3857}
3858
3861 QualType Type) {
3862 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3863 if (CtorType->getNumParams() > 0) {
3864 QualType FirstArg = CtorType->getParamType(0);
3865 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3866 return true;
3867 }
3868 return false;
3869}
3870
3871static OverloadingResult
3873 CXXRecordDecl *To,
3875 OverloadCandidateSet &CandidateSet,
3876 bool AllowExplicit) {
3878 for (auto *D : S.LookupConstructors(To)) {
3879 auto Info = getConstructorInfo(D);
3880 if (!Info)
3881 continue;
3882
3883 bool Usable = !Info.Constructor->isInvalidDecl() &&
3884 S.isInitListConstructor(Info.Constructor);
3885 if (Usable) {
3886 bool SuppressUserConversions = false;
3887 if (Info.ConstructorTmpl)
3888 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3889 /*ExplicitArgs*/ nullptr, From,
3890 CandidateSet, SuppressUserConversions,
3891 /*PartialOverloading*/ false,
3892 AllowExplicit);
3893 else
3894 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3895 CandidateSet, SuppressUserConversions,
3896 /*PartialOverloading*/ false, AllowExplicit);
3897 }
3898 }
3899
3900 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3901
3903 switch (auto Result =
3904 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3905 case OR_Deleted:
3906 case OR_Success: {
3907 // Record the standard conversion we used and the conversion function.
3909 QualType ThisType = Constructor->getFunctionObjectParameterType();
3910 // Initializer lists don't have conversions as such.
3912 User.HadMultipleCandidates = HadMultipleCandidates;
3914 User.FoundConversionFunction = Best->FoundDecl;
3916 User.After.setFromType(ThisType);
3917 User.After.setAllToTypes(ToType);
3918 return Result;
3919 }
3920
3922 return OR_No_Viable_Function;
3923 case OR_Ambiguous:
3924 return OR_Ambiguous;
3925 }
3926
3927 llvm_unreachable("Invalid OverloadResult!");
3928}
3929
3930/// Determines whether there is a user-defined conversion sequence
3931/// (C++ [over.ics.user]) that converts expression From to the type
3932/// ToType. If such a conversion exists, User will contain the
3933/// user-defined conversion sequence that performs such a conversion
3934/// and this routine will return true. Otherwise, this routine returns
3935/// false and User is unspecified.
3936///
3937/// \param AllowExplicit true if the conversion should consider C++0x
3938/// "explicit" conversion functions as well as non-explicit conversion
3939/// functions (C++0x [class.conv.fct]p2).
3940///
3941/// \param AllowObjCConversionOnExplicit true if the conversion should
3942/// allow an extra Objective-C pointer conversion on uses of explicit
3943/// constructors. Requires \c AllowExplicit to also be set.
3944static OverloadingResult
3947 OverloadCandidateSet &CandidateSet,
3948 AllowedExplicit AllowExplicit,
3949 bool AllowObjCConversionOnExplicit) {
3950 assert(AllowExplicit != AllowedExplicit::None ||
3951 !AllowObjCConversionOnExplicit);
3953
3954 // Whether we will only visit constructors.
3955 bool ConstructorsOnly = false;
3956
3957 // If the type we are conversion to is a class type, enumerate its
3958 // constructors.
3959 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3960 // C++ [over.match.ctor]p1:
3961 // When objects of class type are direct-initialized (8.5), or
3962 // copy-initialized from an expression of the same or a
3963 // derived class type (8.5), overload resolution selects the
3964 // constructor. [...] For copy-initialization, the candidate
3965 // functions are all the converting constructors (12.3.1) of
3966 // that class. The argument list is the expression-list within
3967 // the parentheses of the initializer.
3968 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3969 (From->getType()->isRecordType() &&
3970 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3971 ConstructorsOnly = true;
3972
3973 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3974 // We're not going to find any constructors.
3975 } else if (auto *ToRecordDecl =
3976 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3977 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
3978
3979 Expr **Args = &From;
3980 unsigned NumArgs = 1;
3981 bool ListInitializing = false;
3982 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3983 // But first, see if there is an init-list-constructor that will work.
3985 S, From, ToType, ToRecordDecl, User, CandidateSet,
3986 AllowExplicit == AllowedExplicit::All);
3987 if (Result != OR_No_Viable_Function)
3988 return Result;
3989 // Never mind.
3990 CandidateSet.clear(
3992
3993 // If we're list-initializing, we pass the individual elements as
3994 // arguments, not the entire list.
3995 Args = InitList->getInits();
3996 NumArgs = InitList->getNumInits();
3997 ListInitializing = true;
3998 }
3999
4000 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4001 auto Info = getConstructorInfo(D);
4002 if (!Info)
4003 continue;
4004
4005 bool Usable = !Info.Constructor->isInvalidDecl();
4006 if (!ListInitializing)
4007 Usable = Usable && Info.Constructor->isConvertingConstructor(
4008 /*AllowExplicit*/ true);
4009 if (Usable) {
4010 bool SuppressUserConversions = !ConstructorsOnly;
4011 // C++20 [over.best.ics.general]/4.5:
4012 // if the target is the first parameter of a constructor [of class
4013 // X] and the constructor [...] is a candidate by [...] the second
4014 // phase of [over.match.list] when the initializer list has exactly
4015 // one element that is itself an initializer list, [...] and the
4016 // conversion is to X or reference to cv X, user-defined conversion
4017 // sequences are not considered.
4018 if (SuppressUserConversions && ListInitializing) {
4019 SuppressUserConversions =
4020 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4021 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4022 ToType);
4023 }
4024 if (Info.ConstructorTmpl)
4026 Info.ConstructorTmpl, Info.FoundDecl,
4027 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4028 CandidateSet, SuppressUserConversions,
4029 /*PartialOverloading*/ false,
4030 AllowExplicit == AllowedExplicit::All);
4031 else
4032 // Allow one user-defined conversion when user specifies a
4033 // From->ToType conversion via an static cast (c-style, etc).
4034 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4035 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4036 SuppressUserConversions,
4037 /*PartialOverloading*/ false,
4038 AllowExplicit == AllowedExplicit::All);
4039 }
4040 }
4041 }
4042 }
4043
4044 // Enumerate conversion functions, if we're allowed to.
4045 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4046 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4047 // No conversion functions from incomplete types.
4048 } else if (const RecordType *FromRecordType =
4049 From->getType()->getAsCanonical<RecordType>()) {
4050 if (auto *FromRecordDecl =
4051 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4052 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4053 // Add all of the conversion functions as candidates.
4054 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4055 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4056 DeclAccessPair FoundDecl = I.getPair();
4057 NamedDecl *D = FoundDecl.getDecl();
4058 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4059 if (isa<UsingShadowDecl>(D))
4060 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4061
4062 CXXConversionDecl *Conv;
4063 FunctionTemplateDecl *ConvTemplate;
4064 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4065 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4066 else
4067 Conv = cast<CXXConversionDecl>(D);
4068
4069 if (ConvTemplate)
4071 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4072 CandidateSet, AllowObjCConversionOnExplicit,
4073 AllowExplicit != AllowedExplicit::None);
4074 else
4075 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4076 CandidateSet, AllowObjCConversionOnExplicit,
4077 AllowExplicit != AllowedExplicit::None);
4078 }
4079 }
4080 }
4081
4082 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4083
4085 switch (auto Result =
4086 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4087 case OR_Success:
4088 case OR_Deleted:
4089 // Record the standard conversion we used and the conversion function.
4091 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4092 // C++ [over.ics.user]p1:
4093 // If the user-defined conversion is specified by a
4094 // constructor (12.3.1), the initial standard conversion
4095 // sequence converts the source type to the type required by
4096 // the argument of the constructor.
4097 //
4098 if (isa<InitListExpr>(From)) {
4099 // Initializer lists don't have conversions as such.
4101 User.Before.FromBracedInitList = true;
4102 } else {
4103 if (Best->Conversions[0].isEllipsis())
4104 User.EllipsisConversion = true;
4105 else {
4106 User.Before = Best->Conversions[0].Standard;
4107 User.EllipsisConversion = false;
4108 }
4109 }
4110 User.HadMultipleCandidates = HadMultipleCandidates;
4112 User.FoundConversionFunction = Best->FoundDecl;
4114 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4115 User.After.setAllToTypes(ToType);
4116 return Result;
4117 }
4118 if (CXXConversionDecl *Conversion
4119 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4120
4121 assert(Best->HasFinalConversion);
4122
4123 // C++ [over.ics.user]p1:
4124 //
4125 // [...] If the user-defined conversion is specified by a
4126 // conversion function (12.3.2), the initial standard
4127 // conversion sequence converts the source type to the
4128 // implicit object parameter of the conversion function.
4129 User.Before = Best->Conversions[0].Standard;
4130 User.HadMultipleCandidates = HadMultipleCandidates;
4131 User.ConversionFunction = Conversion;
4132 User.FoundConversionFunction = Best->FoundDecl;
4133 User.EllipsisConversion = false;
4134
4135 // C++ [over.ics.user]p2:
4136 // The second standard conversion sequence converts the
4137 // result of the user-defined conversion to the target type
4138 // for the sequence. Since an implicit conversion sequence
4139 // is an initialization, the special rules for
4140 // initialization by user-defined conversion apply when
4141 // selecting the best user-defined conversion for a
4142 // user-defined conversion sequence (see 13.3.3 and
4143 // 13.3.3.1).
4144 User.After = Best->FinalConversion;
4145 return Result;
4146 }
4147 llvm_unreachable("Not a constructor or conversion function?");
4148
4150 return OR_No_Viable_Function;
4151
4152 case OR_Ambiguous:
4153 return OR_Ambiguous;
4154 }
4155
4156 llvm_unreachable("Invalid OverloadResult!");
4157}
4158
4159bool
4162 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4164 OverloadingResult OvResult =
4165 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4166 CandidateSet, AllowedExplicit::None, false);
4167
4168 if (!(OvResult == OR_Ambiguous ||
4169 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4170 return false;
4171
4172 auto Cands = CandidateSet.CompleteCandidates(
4173 *this,
4175 From);
4176 if (OvResult == OR_Ambiguous)
4177 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4178 << From->getType() << ToType << From->getSourceRange();
4179 else { // OR_No_Viable_Function && !CandidateSet.empty()
4180 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4181 diag::err_typecheck_nonviable_condition_incomplete,
4182 From->getType(), From->getSourceRange()))
4183 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4184 << false << From->getType() << From->getSourceRange() << ToType;
4185 }
4186
4187 CandidateSet.NoteCandidates(
4188 *this, From, Cands);
4189 return true;
4190}
4191
4192// Helper for compareConversionFunctions that gets the FunctionType that the
4193// conversion-operator return value 'points' to, or nullptr.
4194static const FunctionType *
4196 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4197 const PointerType *RetPtrTy =
4198 ConvFuncTy->getReturnType()->getAs<PointerType>();
4199
4200 if (!RetPtrTy)
4201 return nullptr;
4202
4203 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4204}
4205
4206/// Compare the user-defined conversion functions or constructors
4207/// of two user-defined conversion sequences to determine whether any ordering
4208/// is possible.
4211 FunctionDecl *Function2) {
4212 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4213 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4214 if (!Conv1 || !Conv2)
4216
4217 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4219
4220 // Objective-C++:
4221 // If both conversion functions are implicitly-declared conversions from
4222 // a lambda closure type to a function pointer and a block pointer,
4223 // respectively, always prefer the conversion to a function pointer,
4224 // because the function pointer is more lightweight and is more likely
4225 // to keep code working.
4226 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4227 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4228 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4229 if (Block1 != Block2)
4230 return Block1 ? ImplicitConversionSequence::Worse
4232 }
4233
4234 // In order to support multiple calling conventions for the lambda conversion
4235 // operator (such as when the free and member function calling convention is
4236 // different), prefer the 'free' mechanism, followed by the calling-convention
4237 // of operator(). The latter is in place to support the MSVC-like solution of
4238 // defining ALL of the possible conversions in regards to calling-convention.
4239 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4240 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4241
4242 if (Conv1FuncRet && Conv2FuncRet &&
4243 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4244 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4245 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4246
4247 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4248 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4249
4250 CallingConv CallOpCC =
4251 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4253 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4255 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4256
4257 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4258 for (CallingConv CC : PrefOrder) {
4259 if (Conv1CC == CC)
4261 if (Conv2CC == CC)
4263 }
4264 }
4265
4267}
4268
4275
4276/// CompareImplicitConversionSequences - Compare two implicit
4277/// conversion sequences to determine whether one is better than the
4278/// other or if they are indistinguishable (C++ 13.3.3.2).
4281 const ImplicitConversionSequence& ICS1,
4282 const ImplicitConversionSequence& ICS2)
4283{
4284 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4285 // conversion sequences (as defined in 13.3.3.1)
4286 // -- a standard conversion sequence (13.3.3.1.1) is a better
4287 // conversion sequence than a user-defined conversion sequence or
4288 // an ellipsis conversion sequence, and
4289 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4290 // conversion sequence than an ellipsis conversion sequence
4291 // (13.3.3.1.3).
4292 //
4293 // C++0x [over.best.ics]p10:
4294 // For the purpose of ranking implicit conversion sequences as
4295 // described in 13.3.3.2, the ambiguous conversion sequence is
4296 // treated as a user-defined sequence that is indistinguishable
4297 // from any other user-defined conversion sequence.
4298
4299 // String literal to 'char *' conversion has been deprecated in C++03. It has
4300 // been removed from C++11. We still accept this conversion, if it happens at
4301 // the best viable function. Otherwise, this conversion is considered worse
4302 // than ellipsis conversion. Consider this as an extension; this is not in the
4303 // standard. For example:
4304 //
4305 // int &f(...); // #1
4306 // void f(char*); // #2
4307 // void g() { int &r = f("foo"); }
4308 //
4309 // In C++03, we pick #2 as the best viable function.
4310 // In C++11, we pick #1 as the best viable function, because ellipsis
4311 // conversion is better than string-literal to char* conversion (since there
4312 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4313 // convert arguments, #2 would be the best viable function in C++11.
4314 // If the best viable function has this conversion, a warning will be issued
4315 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4316
4317 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4320 // Ill-formedness must not differ
4321 ICS1.isBad() == ICS2.isBad())
4325
4326 if (ICS1.getKindRank() < ICS2.getKindRank())
4328 if (ICS2.getKindRank() < ICS1.getKindRank())
4330
4331 // The following checks require both conversion sequences to be of
4332 // the same kind.
4333 if (ICS1.getKind() != ICS2.getKind())
4335
4338
4339 // Two implicit conversion sequences of the same form are
4340 // indistinguishable conversion sequences unless one of the
4341 // following rules apply: (C++ 13.3.3.2p3):
4342
4343 // List-initialization sequence L1 is a better conversion sequence than
4344 // list-initialization sequence L2 if:
4345 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4346 // if not that,
4347 // — L1 and L2 convert to arrays of the same element type, and either the
4348 // number of elements n_1 initialized by L1 is less than the number of
4349 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4350 // an array of unknown bound and L1 does not,
4351 // even if one of the other rules in this paragraph would otherwise apply.
4352 if (!ICS1.isBad()) {
4353 bool StdInit1 = false, StdInit2 = false;
4356 nullptr);
4359 nullptr);
4360 if (StdInit1 != StdInit2)
4361 return StdInit1 ? ImplicitConversionSequence::Better
4363
4366 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4368 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4370 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4371 CAT2->getElementType())) {
4372 // Both to arrays of the same element type
4373 if (CAT1->getSize() != CAT2->getSize())
4374 // Different sized, the smaller wins
4375 return CAT1->getSize().ult(CAT2->getSize())
4380 // One is incomplete, it loses
4384 }
4385 }
4386 }
4387
4388 if (ICS1.isStandard())
4389 // Standard conversion sequence S1 is a better conversion sequence than
4390 // standard conversion sequence S2 if [...]
4391 Result = CompareStandardConversionSequences(S, Loc,
4392 ICS1.Standard, ICS2.Standard);
4393 else if (ICS1.isUserDefined()) {
4394 // With lazy template loading, it is possible to find non-canonical
4395 // FunctionDecls, depending on when redecl chains are completed. Make sure
4396 // to compare the canonical decls of conversion functions. This avoids
4397 // ambiguity problems for templated conversion operators.
4398 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4399 if (ConvFunc1)
4400 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4401 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4402 if (ConvFunc2)
4403 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4404 // User-defined conversion sequence U1 is a better conversion
4405 // sequence than another user-defined conversion sequence U2 if
4406 // they contain the same user-defined conversion function or
4407 // constructor and if the second standard conversion sequence of
4408 // U1 is better than the second standard conversion sequence of
4409 // U2 (C++ 13.3.3.2p3).
4410 if (ConvFunc1 == ConvFunc2)
4411 Result = CompareStandardConversionSequences(S, Loc,
4412 ICS1.UserDefined.After,
4413 ICS2.UserDefined.After);
4414 else
4415 Result = compareConversionFunctions(S,
4418 }
4419
4420 return Result;
4421}
4422
4423// Per 13.3.3.2p3, compare the given standard conversion sequences to
4424// determine if one is a proper subset of the other.
4427 const StandardConversionSequence& SCS1,
4428 const StandardConversionSequence& SCS2) {
4431
4432 // the identity conversion sequence is considered to be a subsequence of
4433 // any non-identity conversion sequence
4434 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4436 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4438
4439 if (SCS1.Second != SCS2.Second) {
4440 if (SCS1.Second == ICK_Identity)
4442 else if (SCS2.Second == ICK_Identity)
4444 else
4446 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4448
4449 if (SCS1.Third == SCS2.Third) {
4450 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4452 }
4453
4454 if (SCS1.Third == ICK_Identity)
4455 return Result == ImplicitConversionSequence::Worse
4458
4459 if (SCS2.Third == ICK_Identity)
4460 return Result == ImplicitConversionSequence::Better
4463
4465}
4466
4467/// Determine whether one of the given reference bindings is better
4468/// than the other based on what kind of bindings they are.
4469static bool
4471 const StandardConversionSequence &SCS2) {
4472 // C++0x [over.ics.rank]p3b4:
4473 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4474 // implicit object parameter of a non-static member function declared
4475 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4476 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4477 // lvalue reference to a function lvalue and S2 binds an rvalue
4478 // reference*.
4479 //
4480 // FIXME: Rvalue references. We're going rogue with the above edits,
4481 // because the semantics in the current C++0x working paper (N3225 at the
4482 // time of this writing) break the standard definition of std::forward
4483 // and std::reference_wrapper when dealing with references to functions.
4484 // Proposed wording changes submitted to CWG for consideration.
4487 return false;
4488
4489 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4490 SCS2.IsLvalueReference) ||
4493}
4494
4500
4501/// Returns kind of fixed enum promotion the \a SCS uses.
4502static FixedEnumPromotion
4504
4505 if (SCS.Second != ICK_Integral_Promotion)
4507
4508 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4509 if (!Enum)
4511
4512 if (!Enum->isFixed())
4514
4515 QualType UnderlyingType = Enum->getIntegerType();
4516 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4518
4520}
4521
4522/// CompareStandardConversionSequences - Compare two standard
4523/// conversion sequences to determine whether one is better than the
4524/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4527 const StandardConversionSequence& SCS1,
4528 const StandardConversionSequence& SCS2)
4529{
4530 // Standard conversion sequence S1 is a better conversion sequence
4531 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4532
4533 // -- S1 is a proper subsequence of S2 (comparing the conversion
4534 // sequences in the canonical form defined by 13.3.3.1.1,
4535 // excluding any Lvalue Transformation; the identity conversion
4536 // sequence is considered to be a subsequence of any
4537 // non-identity conversion sequence) or, if not that,
4540 return CK;
4541
4542 // -- the rank of S1 is better than the rank of S2 (by the rules
4543 // defined below), or, if not that,
4544 ImplicitConversionRank Rank1 = SCS1.getRank();
4545 ImplicitConversionRank Rank2 = SCS2.getRank();
4546 if (Rank1 < Rank2)
4548 else if (Rank2 < Rank1)
4550
4551 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4552 // are indistinguishable unless one of the following rules
4553 // applies:
4554
4555 // A conversion that is not a conversion of a pointer, or
4556 // pointer to member, to bool is better than another conversion
4557 // that is such a conversion.
4559 return SCS2.isPointerConversionToBool()
4562
4563 // C++14 [over.ics.rank]p4b2:
4564 // This is retroactively applied to C++11 by CWG 1601.
4565 //
4566 // A conversion that promotes an enumeration whose underlying type is fixed
4567 // to its underlying type is better than one that promotes to the promoted
4568 // underlying type, if the two are different.
4571 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4572 FEP1 != FEP2)
4576
4577 // C++ [over.ics.rank]p4b2:
4578 //
4579 // If class B is derived directly or indirectly from class A,
4580 // conversion of B* to A* is better than conversion of B* to
4581 // void*, and conversion of A* to void* is better than conversion
4582 // of B* to void*.
4583 bool SCS1ConvertsToVoid
4585 bool SCS2ConvertsToVoid
4587 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4588 // Exactly one of the conversion sequences is a conversion to
4589 // a void pointer; it's the worse conversion.
4590 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4592 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4593 // Neither conversion sequence converts to a void pointer; compare
4594 // their derived-to-base conversions.
4596 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4597 return DerivedCK;
4598 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4599 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4600 // Both conversion sequences are conversions to void
4601 // pointers. Compare the source types to determine if there's an
4602 // inheritance relationship in their sources.
4603 QualType FromType1 = SCS1.getFromType();
4604 QualType FromType2 = SCS2.getFromType();
4605
4606 // Adjust the types we're converting from via the array-to-pointer
4607 // conversion, if we need to.
4608 if (SCS1.First == ICK_Array_To_Pointer)
4609 FromType1 = S.Context.getArrayDecayedType(FromType1);
4610 if (SCS2.First == ICK_Array_To_Pointer)
4611 FromType2 = S.Context.getArrayDecayedType(FromType2);
4612
4613 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4614 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4615
4616 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4618 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4620
4621 // Objective-C++: If one interface is more specific than the
4622 // other, it is the better one.
4623 const ObjCObjectPointerType* FromObjCPtr1
4624 = FromType1->getAs<ObjCObjectPointerType>();
4625 const ObjCObjectPointerType* FromObjCPtr2
4626 = FromType2->getAs<ObjCObjectPointerType>();
4627 if (FromObjCPtr1 && FromObjCPtr2) {
4628 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4629 FromObjCPtr2);
4630 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4631 FromObjCPtr1);
4632 if (AssignLeft != AssignRight) {
4633 return AssignLeft? ImplicitConversionSequence::Better
4635 }
4636 }
4637 }
4638
4639 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4640 // Check for a better reference binding based on the kind of bindings.
4641 if (isBetterReferenceBindingKind(SCS1, SCS2))
4643 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4645 }
4646
4647 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4648 // bullet 3).
4650 = CompareQualificationConversions(S, SCS1, SCS2))
4651 return QualCK;
4652
4653 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4654 // C++ [over.ics.rank]p3b4:
4655 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4656 // which the references refer are the same type except for
4657 // top-level cv-qualifiers, and the type to which the reference
4658 // initialized by S2 refers is more cv-qualified than the type
4659 // to which the reference initialized by S1 refers.
4660 QualType T1 = SCS1.getToType(2);
4661 QualType T2 = SCS2.getToType(2);
4662 T1 = S.Context.getCanonicalType(T1);
4663 T2 = S.Context.getCanonicalType(T2);
4664 Qualifiers T1Quals, T2Quals;
4665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4667 if (UnqualT1 == UnqualT2) {
4668 // Objective-C++ ARC: If the references refer to objects with different
4669 // lifetimes, prefer bindings that don't change lifetime.
4675 }
4676
4677 // If the type is an array type, promote the element qualifiers to the
4678 // type for comparison.
4679 if (isa<ArrayType>(T1) && T1Quals)
4680 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4681 if (isa<ArrayType>(T2) && T2Quals)
4682 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4683 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4685 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4687 }
4688 }
4689
4690 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4691 // floating-to-integral conversion if the integral conversion
4692 // is between types of the same size.
4693 // For example:
4694 // void f(float);
4695 // void f(int);
4696 // int main {
4697 // long a;
4698 // f(a);
4699 // }
4700 // Here, MSVC will call f(int) instead of generating a compile error
4701 // as clang will do in standard mode.
4702 if (S.getLangOpts().MSVCCompat &&
4705 SCS2.Second == ICK_Floating_Integral &&
4706 S.Context.getTypeSize(SCS1.getFromType()) ==
4707 S.Context.getTypeSize(SCS1.getToType(2)))
4709
4710 // Prefer a compatible vector conversion over a lax vector conversion
4711 // For example:
4712 //
4713 // typedef float __v4sf __attribute__((__vector_size__(16)));
4714 // void f(vector float);
4715 // void f(vector signed int);
4716 // int main() {
4717 // __v4sf a;
4718 // f(a);
4719 // }
4720 // Here, we'd like to choose f(vector float) and not
4721 // report an ambiguous call error
4722 if (SCS1.Second == ICK_Vector_Conversion &&
4723 SCS2.Second == ICK_Vector_Conversion) {
4724 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4725 SCS1.getFromType(), SCS1.getToType(2));
4726 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4727 SCS2.getFromType(), SCS2.getToType(2));
4728
4729 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4730 return SCS1IsCompatibleVectorConversion
4733 }
4734
4735 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4737 bool SCS1IsCompatibleSVEVectorConversion =
4738 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4739 bool SCS2IsCompatibleSVEVectorConversion =
4740 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4741
4742 if (SCS1IsCompatibleSVEVectorConversion !=
4743 SCS2IsCompatibleSVEVectorConversion)
4744 return SCS1IsCompatibleSVEVectorConversion
4747 }
4748
4749 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4751 bool SCS1IsCompatibleRVVVectorConversion =
4753 bool SCS2IsCompatibleRVVVectorConversion =
4755
4756 if (SCS1IsCompatibleRVVVectorConversion !=
4757 SCS2IsCompatibleRVVVectorConversion)
4758 return SCS1IsCompatibleRVVVectorConversion
4761 }
4763}
4764
4765/// CompareQualificationConversions - Compares two standard conversion
4766/// sequences to determine whether they can be ranked based on their
4767/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4770 const StandardConversionSequence& SCS1,
4771 const StandardConversionSequence& SCS2) {
4772 // C++ [over.ics.rank]p3:
4773 // -- S1 and S2 differ only in their qualification conversion and
4774 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4775 // [C++98]
4776 // [...] and the cv-qualification signature of type T1 is a proper subset
4777 // of the cv-qualification signature of type T2, and S1 is not the
4778 // deprecated string literal array-to-pointer conversion (4.2).
4779 // [C++2a]
4780 // [...] where T1 can be converted to T2 by a qualification conversion.
4781 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4782 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4784
4785 // FIXME: the example in the standard doesn't use a qualification
4786 // conversion (!)
4787 QualType T1 = SCS1.getToType(2);
4788 QualType T2 = SCS2.getToType(2);
4789 T1 = S.Context.getCanonicalType(T1);
4790 T2 = S.Context.getCanonicalType(T2);
4791 assert(!T1->isReferenceType() && !T2->isReferenceType());
4792 Qualifiers T1Quals, T2Quals;
4793 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4794 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4795
4796 // If the types are the same, we won't learn anything by unwrapping
4797 // them.
4798 if (UnqualT1 == UnqualT2)
4800
4801 // Don't ever prefer a standard conversion sequence that uses the deprecated
4802 // string literal array to pointer conversion.
4803 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4804 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4805
4806 // Objective-C++ ARC:
4807 // Prefer qualification conversions not involving a change in lifetime
4808 // to qualification conversions that do change lifetime.
4811 CanPick1 = false;
4814 CanPick2 = false;
4815
4816 bool ObjCLifetimeConversion;
4817 if (CanPick1 &&
4818 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4819 CanPick1 = false;
4820 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4821 // directions, so we can't short-cut this second check in general.
4822 if (CanPick2 &&
4823 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4824 CanPick2 = false;
4825
4826 if (CanPick1 != CanPick2)
4827 return CanPick1 ? ImplicitConversionSequence::Better
4830}
4831
4832/// CompareDerivedToBaseConversions - Compares two standard conversion
4833/// sequences to determine whether they can be ranked based on their
4834/// various kinds of derived-to-base conversions (C++
4835/// [over.ics.rank]p4b3). As part of these checks, we also look at
4836/// conversions between Objective-C interface types.
4839 const StandardConversionSequence& SCS1,
4840 const StandardConversionSequence& SCS2) {
4841 QualType FromType1 = SCS1.getFromType();
4842 QualType ToType1 = SCS1.getToType(1);
4843 QualType FromType2 = SCS2.getFromType();
4844 QualType ToType2 = SCS2.getToType(1);
4845
4846 // Adjust the types we're converting from via the array-to-pointer
4847 // conversion, if we need to.
4848 if (SCS1.First == ICK_Array_To_Pointer)
4849 FromType1 = S.Context.getArrayDecayedType(FromType1);
4850 if (SCS2.First == ICK_Array_To_Pointer)
4851 FromType2 = S.Context.getArrayDecayedType(FromType2);
4852
4853 // Canonicalize all of the types.
4854 FromType1 = S.Context.getCanonicalType(FromType1);
4855 ToType1 = S.Context.getCanonicalType(ToType1);
4856 FromType2 = S.Context.getCanonicalType(FromType2);
4857 ToType2 = S.Context.getCanonicalType(ToType2);
4858
4859 // C++ [over.ics.rank]p4b3:
4860 //
4861 // If class B is derived directly or indirectly from class A and
4862 // class C is derived directly or indirectly from B,
4863 //
4864 // Compare based on pointer conversions.
4865 if (SCS1.Second == ICK_Pointer_Conversion &&
4867 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4868 FromType1->isPointerType() && FromType2->isPointerType() &&
4869 ToType1->isPointerType() && ToType2->isPointerType()) {
4870 QualType FromPointee1 =
4872 QualType ToPointee1 =
4874 QualType FromPointee2 =
4876 QualType ToPointee2 =
4878
4879 // -- conversion of C* to B* is better than conversion of C* to A*,
4880 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4881 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4883 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4885 }
4886
4887 // -- conversion of B* to A* is better than conversion of C* to A*,
4888 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4889 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4891 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4893 }
4894 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4896 const ObjCObjectPointerType *FromPtr1
4897 = FromType1->getAs<ObjCObjectPointerType>();
4898 const ObjCObjectPointerType *FromPtr2
4899 = FromType2->getAs<ObjCObjectPointerType>();
4900 const ObjCObjectPointerType *ToPtr1
4901 = ToType1->getAs<ObjCObjectPointerType>();
4902 const ObjCObjectPointerType *ToPtr2
4903 = ToType2->getAs<ObjCObjectPointerType>();
4904
4905 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4906 // Apply the same conversion ranking rules for Objective-C pointer types
4907 // that we do for C++ pointers to class types. However, we employ the
4908 // Objective-C pseudo-subtyping relationship used for assignment of
4909 // Objective-C pointer types.
4910 bool FromAssignLeft
4911 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4912 bool FromAssignRight
4913 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4914 bool ToAssignLeft
4915 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4916 bool ToAssignRight
4917 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4918
4919 // A conversion to an a non-id object pointer type or qualified 'id'
4920 // type is better than a conversion to 'id'.
4921 if (ToPtr1->isObjCIdType() &&
4922 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4924 if (ToPtr2->isObjCIdType() &&
4925 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4927
4928 // A conversion to a non-id object pointer type is better than a
4929 // conversion to a qualified 'id' type
4930 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4932 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4934
4935 // A conversion to an a non-Class object pointer type or qualified 'Class'
4936 // type is better than a conversion to 'Class'.
4937 if (ToPtr1->isObjCClassType() &&
4938 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4940 if (ToPtr2->isObjCClassType() &&
4941 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4943
4944 // A conversion to a non-Class object pointer type is better than a
4945 // conversion to a qualified 'Class' type.
4946 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4948 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4950
4951 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4952 if (S.Context.hasSameType(FromType1, FromType2) &&
4953 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4954 (ToAssignLeft != ToAssignRight)) {
4955 if (FromPtr1->isSpecialized()) {
4956 // "conversion of B<A> * to B * is better than conversion of B * to
4957 // C *.
4958 bool IsFirstSame =
4959 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4960 bool IsSecondSame =
4961 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4962 if (IsFirstSame) {
4963 if (!IsSecondSame)
4965 } else if (IsSecondSame)
4967 }
4968 return ToAssignLeft? ImplicitConversionSequence::Worse
4970 }
4971
4972 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4973 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4974 (FromAssignLeft != FromAssignRight))
4975 return FromAssignLeft? ImplicitConversionSequence::Better
4977 }
4978 }
4979
4980 // Ranking of member-pointer types.
4981 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4982 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4983 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4984 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4985 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4986 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4987 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4988 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4989 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4990 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4991 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4992 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4993 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4994 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4996 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4998 }
4999 // conversion of B::* to C::* is better than conversion of A::* to C::*
5000 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5001 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5003 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5005 }
5006 }
5007
5008 if (SCS1.Second == ICK_Derived_To_Base) {
5009 // -- conversion of C to B is better than conversion of C to A,
5010 // -- binding of an expression of type C to a reference of type
5011 // B& is better than binding an expression of type C to a
5012 // reference of type A&,
5013 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5014 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5015 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5017 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5019 }
5020
5021 // -- conversion of B to A is better than conversion of C to A.
5022 // -- binding of an expression of type B to a reference of type
5023 // A& is better than binding an expression of type C to a
5024 // reference of type A&,
5025 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5026 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5027 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5029 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5031 }
5032 }
5033
5035}
5036
5038 if (!T.getQualifiers().hasUnaligned())
5039 return T;
5040
5041 Qualifiers Q;
5042 T = Ctx.getUnqualifiedArrayType(T, Q);
5043 Q.removeUnaligned();
5044 return Ctx.getQualifiedType(T, Q);
5045}
5046
5049 QualType OrigT1, QualType OrigT2,
5050 ReferenceConversions *ConvOut) {
5051 assert(!OrigT1->isReferenceType() &&
5052 "T1 must be the pointee type of the reference type");
5053 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5054
5055 QualType T1 = Context.getCanonicalType(OrigT1);
5056 QualType T2 = Context.getCanonicalType(OrigT2);
5057 Qualifiers T1Quals, T2Quals;
5058 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5059 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5060
5061 ReferenceConversions ConvTmp;
5062 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5063 Conv = ReferenceConversions();
5064
5065 // C++2a [dcl.init.ref]p4:
5066 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5067 // reference-related to "cv2 T2" if T1 is similar to T2, or
5068 // T1 is a base class of T2.
5069 // "cv1 T1" is reference-compatible with "cv2 T2" if
5070 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5071 // "pointer to cv1 T1" via a standard conversion sequence.
5072
5073 // Check for standard conversions we can apply to pointers: derived-to-base
5074 // conversions, ObjC pointer conversions, and function pointer conversions.
5075 // (Qualification conversions are checked last.)
5076 if (UnqualT1 == UnqualT2) {
5077 // Nothing to do.
5078 } else if (isCompleteType(Loc, OrigT2) &&
5079 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5080 Conv |= ReferenceConversions::DerivedToBase;
5081 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5082 UnqualT2->isObjCObjectOrInterfaceType() &&
5083 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5084 Conv |= ReferenceConversions::ObjC;
5085 else if (UnqualT2->isFunctionType() &&
5086 IsFunctionConversion(UnqualT2, UnqualT1)) {
5087 Conv |= ReferenceConversions::Function;
5088 // No need to check qualifiers; function types don't have them.
5089 return Ref_Compatible;
5090 }
5091 bool ConvertedReferent = Conv != 0;
5092
5093 // We can have a qualification conversion. Compute whether the types are
5094 // similar at the same time.
5095 bool PreviousToQualsIncludeConst = true;
5096 bool TopLevel = true;
5097 do {
5098 if (T1 == T2)
5099 break;
5100
5101 // We will need a qualification conversion.
5102 Conv |= ReferenceConversions::Qualification;
5103
5104 // Track whether we performed a qualification conversion anywhere other
5105 // than the top level. This matters for ranking reference bindings in
5106 // overload resolution.
5107 if (!TopLevel)
5108 Conv |= ReferenceConversions::NestedQualification;
5109
5110 // MS compiler ignores __unaligned qualifier for references; do the same.
5111 T1 = withoutUnaligned(Context, T1);
5112 T2 = withoutUnaligned(Context, T2);
5113
5114 // If we find a qualifier mismatch, the types are not reference-compatible,
5115 // but are still be reference-related if they're similar.
5116 bool ObjCLifetimeConversion = false;
5117 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5118 PreviousToQualsIncludeConst,
5119 ObjCLifetimeConversion, getASTContext()))
5120 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5121 ? Ref_Related
5123
5124 // FIXME: Should we track this for any level other than the first?
5125 if (ObjCLifetimeConversion)
5126 Conv |= ReferenceConversions::ObjCLifetime;
5127
5128 TopLevel = false;
5129 } while (Context.UnwrapSimilarTypes(T1, T2));
5130
5131 // At this point, if the types are reference-related, we must either have the
5132 // same inner type (ignoring qualifiers), or must have already worked out how
5133 // to convert the referent.
5134 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5137}
5138
5139/// Look for a user-defined conversion to a value reference-compatible
5140/// with DeclType. Return true if something definite is found.
5141static bool
5143 QualType DeclType, SourceLocation DeclLoc,
5144 Expr *Init, QualType T2, bool AllowRvalues,
5145 bool AllowExplicit) {
5146 assert(T2->isRecordType() && "Can only find conversions of record types.");
5147 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5148 OverloadCandidateSet CandidateSet(
5150 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5151 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5152 NamedDecl *D = *I;
5154 if (isa<UsingShadowDecl>(D))
5155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5156
5157 FunctionTemplateDecl *ConvTemplate
5158 = dyn_cast<FunctionTemplateDecl>(D);
5159 CXXConversionDecl *Conv;
5160 if (ConvTemplate)
5161 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5162 else
5163 Conv = cast<CXXConversionDecl>(D);
5164
5165 if (AllowRvalues) {
5166 // If we are initializing an rvalue reference, don't permit conversion
5167 // functions that return lvalues.
5168 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5169 const ReferenceType *RefType
5171 if (RefType && !RefType->getPointeeType()->isFunctionType())
5172 continue;
5173 }
5174
5175 if (!ConvTemplate &&
5177 DeclLoc,
5178 Conv->getConversionType()
5183 continue;
5184 } else {
5185 // If the conversion function doesn't return a reference type,
5186 // it can't be considered for this conversion. An rvalue reference
5187 // is only acceptable if its referencee is a function type.
5188
5189 const ReferenceType *RefType =
5191 if (!RefType ||
5192 (!RefType->isLValueReferenceType() &&
5193 !RefType->getPointeeType()->isFunctionType()))
5194 continue;
5195 }
5196
5197 if (ConvTemplate)
5199 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5200 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5201 else
5203 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5204 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5205 }
5206
5207 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5208
5210 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5211 case OR_Success:
5212
5213 assert(Best->HasFinalConversion);
5214
5215 // C++ [over.ics.ref]p1:
5216 //
5217 // [...] If the parameter binds directly to the result of
5218 // applying a conversion function to the argument
5219 // expression, the implicit conversion sequence is a
5220 // user-defined conversion sequence (13.3.3.1.2), with the
5221 // second standard conversion sequence either an identity
5222 // conversion or, if the conversion function returns an
5223 // entity of a type that is a derived class of the parameter
5224 // type, a derived-to-base Conversion.
5225 if (!Best->FinalConversion.DirectBinding)
5226 return false;
5227
5228 ICS.setUserDefined();
5229 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5230 ICS.UserDefined.After = Best->FinalConversion;
5231 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5232 ICS.UserDefined.ConversionFunction = Best->Function;
5233 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5234 ICS.UserDefined.EllipsisConversion = false;
5235 assert(ICS.UserDefined.After.ReferenceBinding &&
5237 "Expected a direct reference binding!");
5238 return true;
5239
5240 case OR_Ambiguous:
5241 ICS.setAmbiguous();
5242 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5243 Cand != CandidateSet.end(); ++Cand)
5244 if (Cand->Best)
5245 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5246 return true;
5247
5249 case OR_Deleted:
5250 // There was no suitable conversion, or we found a deleted
5251 // conversion; continue with other checks.
5252 return false;
5253 }
5254
5255 llvm_unreachable("Invalid OverloadResult!");
5256}
5257
5258/// Compute an implicit conversion sequence for reference
5259/// initialization.
5260static ImplicitConversionSequence
5262 SourceLocation DeclLoc,
5263 bool SuppressUserConversions,
5264 bool AllowExplicit) {
5265 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5266
5267 // Most paths end in a failed conversion.
5270
5271 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5272 QualType T2 = Init->getType();
5273
5274 // If the initializer is the address of an overloaded function, try
5275 // to resolve the overloaded function. If all goes well, T2 is the
5276 // type of the resulting function.
5277 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5280 false, Found))
5281 T2 = Fn->getType();
5282 }
5283
5284 // Compute some basic properties of the types and the initializer.
5285 bool isRValRef = DeclType->isRValueReferenceType();
5286 Expr::Classification InitCategory = Init->Classify(S.Context);
5287
5289 Sema::ReferenceCompareResult RefRelationship =
5290 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5291
5292 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5293 ICS.setStandard();
5295 // FIXME: A reference binding can be a function conversion too. We should
5296 // consider that when ordering reference-to-function bindings.
5297 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5299 : (RefConv & Sema::ReferenceConversions::ObjC)
5301 : ICK_Identity;
5303 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5304 // a reference binding that performs a non-top-level qualification
5305 // conversion as a qualification conversion, not as an identity conversion.
5306 ICS.Standard.Third = (RefConv &
5307 Sema::ReferenceConversions::NestedQualification)
5309 : ICK_Identity;
5310 ICS.Standard.setFromType(T2);
5311 ICS.Standard.setToType(0, T2);
5312 ICS.Standard.setToType(1, T1);
5313 ICS.Standard.setToType(2, T1);
5314 ICS.Standard.ReferenceBinding = true;
5315 ICS.Standard.DirectBinding = BindsDirectly;
5316 ICS.Standard.IsLvalueReference = !isRValRef;
5318 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5321 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5322 ICS.Standard.FromBracedInitList = false;
5323 ICS.Standard.CopyConstructor = nullptr;
5325 };
5326
5327 // C++0x [dcl.init.ref]p5:
5328 // A reference to type "cv1 T1" is initialized by an expression
5329 // of type "cv2 T2" as follows:
5330
5331 // -- If reference is an lvalue reference and the initializer expression
5332 if (!isRValRef) {
5333 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5334 // reference-compatible with "cv2 T2," or
5335 //
5336 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5337 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5338 // C++ [over.ics.ref]p1:
5339 // When a parameter of reference type binds directly (8.5.3)
5340 // to an argument expression, the implicit conversion sequence
5341 // is the identity conversion, unless the argument expression
5342 // has a type that is a derived class of the parameter type,
5343 // in which case the implicit conversion sequence is a
5344 // derived-to-base Conversion (13.3.3.1).
5345 SetAsReferenceBinding(/*BindsDirectly=*/true);
5346
5347 // Nothing more to do: the inaccessibility/ambiguity check for
5348 // derived-to-base conversions is suppressed when we're
5349 // computing the implicit conversion sequence (C++
5350 // [over.best.ics]p2).
5351 return ICS;
5352 }
5353
5354 // -- has a class type (i.e., T2 is a class type), where T1 is
5355 // not reference-related to T2, and can be implicitly
5356 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5357 // is reference-compatible with "cv3 T3" 92) (this
5358 // conversion is selected by enumerating the applicable
5359 // conversion functions (13.3.1.6) and choosing the best
5360 // one through overload resolution (13.3)),
5361 if (!SuppressUserConversions && T2->isRecordType() &&
5362 S.isCompleteType(DeclLoc, T2) &&
5363 RefRelationship == Sema::Ref_Incompatible) {
5364 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5365 Init, T2, /*AllowRvalues=*/false,
5366 AllowExplicit))
5367 return ICS;
5368 }
5369 }
5370
5371 // -- Otherwise, the reference shall be an lvalue reference to a
5372 // non-volatile const type (i.e., cv1 shall be const), or the reference
5373 // shall be an rvalue reference.
5374 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5375 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5377 return ICS;
5378 }
5379
5380 // -- If the initializer expression
5381 //
5382 // -- is an xvalue, class prvalue, array prvalue or function
5383 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5384 if (RefRelationship == Sema::Ref_Compatible &&
5385 (InitCategory.isXValue() ||
5386 (InitCategory.isPRValue() &&
5387 (T2->isRecordType() || T2->isArrayType())) ||
5388 (InitCategory.isLValue() && T2->isFunctionType()))) {
5389 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5390 // binding unless we're binding to a class prvalue.
5391 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5392 // allow the use of rvalue references in C++98/03 for the benefit of
5393 // standard library implementors; therefore, we need the xvalue check here.
5394 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5395 !(InitCategory.isPRValue() || T2->isRecordType()));
5396 return ICS;
5397 }
5398
5399 // -- has a class type (i.e., T2 is a class type), where T1 is not
5400 // reference-related to T2, and can be implicitly converted to
5401 // an xvalue, class prvalue, or function lvalue of type
5402 // "cv3 T3", where "cv1 T1" is reference-compatible with
5403 // "cv3 T3",
5404 //
5405 // then the reference is bound to the value of the initializer
5406 // expression in the first case and to the result of the conversion
5407 // in the second case (or, in either case, to an appropriate base
5408 // class subobject).
5409 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5410 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5411 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5412 Init, T2, /*AllowRvalues=*/true,
5413 AllowExplicit)) {
5414 // In the second case, if the reference is an rvalue reference
5415 // and the second standard conversion sequence of the
5416 // user-defined conversion sequence includes an lvalue-to-rvalue
5417 // conversion, the program is ill-formed.
5418 if (ICS.isUserDefined() && isRValRef &&
5421
5422 return ICS;
5423 }
5424
5425 // A temporary of function type cannot be created; don't even try.
5426 if (T1->isFunctionType())
5427 return ICS;
5428
5429 // -- Otherwise, a temporary of type "cv1 T1" is created and
5430 // initialized from the initializer expression using the
5431 // rules for a non-reference copy initialization (8.5). The
5432 // reference is then bound to the temporary. If T1 is
5433 // reference-related to T2, cv1 must be the same
5434 // cv-qualification as, or greater cv-qualification than,
5435 // cv2; otherwise, the program is ill-formed.
5436 if (RefRelationship == Sema::Ref_Related) {
5437 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5438 // we would be reference-compatible or reference-compatible with
5439 // added qualification. But that wasn't the case, so the reference
5440 // initialization fails.
5441 //
5442 // Note that we only want to check address spaces and cvr-qualifiers here.
5443 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5444 Qualifiers T1Quals = T1.getQualifiers();
5445 Qualifiers T2Quals = T2.getQualifiers();
5446 T1Quals.removeObjCGCAttr();
5447 T1Quals.removeObjCLifetime();
5448 T2Quals.removeObjCGCAttr();
5449 T2Quals.removeObjCLifetime();
5450 // MS compiler ignores __unaligned qualifier for references; do the same.
5451 T1Quals.removeUnaligned();
5452 T2Quals.removeUnaligned();
5453 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5454 return ICS;
5455 }
5456
5457 // If at least one of the types is a class type, the types are not
5458 // related, and we aren't allowed any user conversions, the
5459 // reference binding fails. This case is important for breaking
5460 // recursion, since TryImplicitConversion below will attempt to
5461 // create a temporary through the use of a copy constructor.
5462 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5463 (T1->isRecordType() || T2->isRecordType()))
5464 return ICS;
5465
5466 // If T1 is reference-related to T2 and the reference is an rvalue
5467 // reference, the initializer expression shall not be an lvalue.
5468 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5469 Init->Classify(S.Context).isLValue()) {
5471 return ICS;
5472 }
5473
5474 // C++ [over.ics.ref]p2:
5475 // When a parameter of reference type is not bound directly to
5476 // an argument expression, the conversion sequence is the one
5477 // required to convert the argument expression to the
5478 // underlying type of the reference according to
5479 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5480 // to copy-initializing a temporary of the underlying type with
5481 // the argument expression. Any difference in top-level
5482 // cv-qualification is subsumed by the initialization itself
5483 // and does not constitute a conversion.
5484 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5485 AllowedExplicit::None,
5486 /*InOverloadResolution=*/false,
5487 /*CStyle=*/false,
5488 /*AllowObjCWritebackConversion=*/false,
5489 /*AllowObjCConversionOnExplicit=*/false);
5490
5491 // Of course, that's still a reference binding.
5492 if (ICS.isStandard()) {
5493 ICS.Standard.ReferenceBinding = true;
5494 ICS.Standard.IsLvalueReference = !isRValRef;
5495 ICS.Standard.BindsToFunctionLvalue = false;
5496 ICS.Standard.BindsToRvalue = true;
5499 } else if (ICS.isUserDefined()) {
5500 const ReferenceType *LValRefType =
5503
5504 // C++ [over.ics.ref]p3:
5505 // Except for an implicit object parameter, for which see 13.3.1, a
5506 // standard conversion sequence cannot be formed if it requires [...]
5507 // binding an rvalue reference to an lvalue other than a function
5508 // lvalue.
5509 // Note that the function case is not possible here.
5510 if (isRValRef && LValRefType) {
5512 return ICS;
5513 }
5514
5516 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5518 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5522 }
5523
5524 return ICS;
5525}
5526
5527static ImplicitConversionSequence
5528TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5529 bool SuppressUserConversions,
5530 bool InOverloadResolution,
5531 bool AllowObjCWritebackConversion,
5532 bool AllowExplicit = false);
5533
5534/// TryListConversion - Try to copy-initialize a value of type ToType from the
5535/// initializer list From.
5536static ImplicitConversionSequence
5538 bool SuppressUserConversions,
5539 bool InOverloadResolution,
5540 bool AllowObjCWritebackConversion) {
5541 // C++11 [over.ics.list]p1:
5542 // When an argument is an initializer list, it is not an expression and
5543 // special rules apply for converting it to a parameter type.
5544
5546 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5547
5548 // We need a complete type for what follows. With one C++20 exception,
5549 // incomplete types can never be initialized from init lists.
5550 QualType InitTy = ToType;
5551 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5552 if (AT && S.getLangOpts().CPlusPlus20)
5553 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5554 // C++20 allows list initialization of an incomplete array type.
5555 InitTy = IAT->getElementType();
5556 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5557 return Result;
5558
5559 // C++20 [over.ics.list]/2:
5560 // If the initializer list is a designated-initializer-list, a conversion
5561 // is only possible if the parameter has an aggregate type
5562 //
5563 // FIXME: The exception for reference initialization here is not part of the
5564 // language rules, but follow other compilers in adding it as a tentative DR
5565 // resolution.
5566 bool IsDesignatedInit = From->hasDesignatedInit();
5567 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5568 IsDesignatedInit)
5569 return Result;
5570
5571 // Per DR1467 and DR2137:
5572 // If the parameter type is an aggregate class X and the initializer list
5573 // has a single element of type cv U, where U is X or a class derived from
5574 // X, the implicit conversion sequence is the one required to convert the
5575 // element to the parameter type.
5576 //
5577 // Otherwise, if the parameter type is a character array [... ]
5578 // and the initializer list has a single element that is an
5579 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5580 // implicit conversion sequence is the identity conversion.
5581 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5582 if (ToType->isRecordType() && ToType->isAggregateType()) {
5583 QualType InitType = From->getInit(0)->getType();
5584 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5585 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5586 return TryCopyInitialization(S, From->getInit(0), ToType,
5587 SuppressUserConversions,
5588 InOverloadResolution,
5589 AllowObjCWritebackConversion);
5590 }
5591
5592 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5593 InitializedEntity Entity =
5595 /*Consumed=*/false);
5596 if (S.CanPerformCopyInitialization(Entity, From)) {
5597 Result.setStandard();
5598 Result.Standard.setAsIdentityConversion();
5599 Result.Standard.setFromType(ToType);
5600 Result.Standard.setAllToTypes(ToType);
5601 return Result;
5602 }
5603 }
5604 }
5605
5606 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5607 // C++11 [over.ics.list]p2:
5608 // If the parameter type is std::initializer_list<X> or "array of X" and
5609 // all the elements can be implicitly converted to X, the implicit
5610 // conversion sequence is the worst conversion necessary to convert an
5611 // element of the list to X.
5612 //
5613 // C++14 [over.ics.list]p3:
5614 // Otherwise, if the parameter type is "array of N X", if the initializer
5615 // list has exactly N elements or if it has fewer than N elements and X is
5616 // default-constructible, and if all the elements of the initializer list
5617 // can be implicitly converted to X, the implicit conversion sequence is
5618 // the worst conversion necessary to convert an element of the list to X.
5619 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5620 unsigned e = From->getNumInits();
5623 QualType());
5624 QualType ContTy = ToType;
5625 bool IsUnbounded = false;
5626 if (AT) {
5627 InitTy = AT->getElementType();
5628 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5629 if (CT->getSize().ult(e)) {
5630 // Too many inits, fatally bad
5632 ToType);
5633 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5634 return Result;
5635 }
5636 if (CT->getSize().ugt(e)) {
5637 // Need an init from empty {}, is there one?
5638 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5639 From->getEndLoc());
5640 EmptyList.setType(S.Context.VoidTy);
5641 DfltElt = TryListConversion(
5642 S, &EmptyList, InitTy, SuppressUserConversions,
5643 InOverloadResolution, AllowObjCWritebackConversion);
5644 if (DfltElt.isBad()) {
5645 // No {} init, fatally bad
5647 ToType);
5648 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5649 return Result;
5650 }
5651 }
5652 } else {
5653 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5654 IsUnbounded = true;
5655 if (!e) {
5656 // Cannot convert to zero-sized.
5658 ToType);
5659 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5660 return Result;
5661 }
5662 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5663 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5665 }
5666 }
5667
5668 Result.setStandard();
5669 Result.Standard.setAsIdentityConversion();
5670 Result.Standard.setFromType(InitTy);
5671 Result.Standard.setAllToTypes(InitTy);
5672 for (unsigned i = 0; i < e; ++i) {
5673 Expr *Init = From->getInit(i);
5675 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5676 AllowObjCWritebackConversion);
5677
5678 // Keep the worse conversion seen so far.
5679 // FIXME: Sequences are not totally ordered, so 'worse' can be
5680 // ambiguous. CWG has been informed.
5682 Result) ==
5684 Result = ICS;
5685 // Bail as soon as we find something unconvertible.
5686 if (Result.isBad()) {
5687 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5688 return Result;
5689 }
5690 }
5691 }
5692
5693 // If we needed any implicit {} initialization, compare that now.
5694 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5695 // has been informed that this might not be the best thing.
5696 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5697 S, From->getEndLoc(), DfltElt, Result) ==
5699 Result = DfltElt;
5700 // Record the type being initialized so that we may compare sequences
5701 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5702 return Result;
5703 }
5704
5705 // C++14 [over.ics.list]p4:
5706 // C++11 [over.ics.list]p3:
5707 // Otherwise, if the parameter is a non-aggregate class X and overload
5708 // resolution chooses a single best constructor [...] the implicit
5709 // conversion sequence is a user-defined conversion sequence. If multiple
5710 // constructors are viable but none is better than the others, the
5711 // implicit conversion sequence is a user-defined conversion sequence.
5712 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5713 // This function can deal with initializer lists.
5714 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5715 AllowedExplicit::None,
5716 InOverloadResolution, /*CStyle=*/false,
5717 AllowObjCWritebackConversion,
5718 /*AllowObjCConversionOnExplicit=*/false);
5719 }
5720
5721 // C++14 [over.ics.list]p5:
5722 // C++11 [over.ics.list]p4:
5723 // Otherwise, if the parameter has an aggregate type which can be
5724 // initialized from the initializer list [...] the implicit conversion
5725 // sequence is a user-defined conversion sequence.
5726 if (ToType->isAggregateType()) {
5727 // Type is an aggregate, argument is an init list. At this point it comes
5728 // down to checking whether the initialization works.
5729 // FIXME: Find out whether this parameter is consumed or not.
5730 InitializedEntity Entity =
5732 /*Consumed=*/false);
5734 From)) {
5735 Result.setUserDefined();
5736 Result.UserDefined.Before.setAsIdentityConversion();
5737 // Initializer lists don't have a type.
5738 Result.UserDefined.Before.setFromType(QualType());
5739 Result.UserDefined.Before.setAllToTypes(QualType());
5740
5741 Result.UserDefined.After.setAsIdentityConversion();
5742 Result.UserDefined.After.setFromType(ToType);
5743 Result.UserDefined.After.setAllToTypes(ToType);
5744 Result.UserDefined.ConversionFunction = nullptr;
5745 }
5746 return Result;
5747 }
5748
5749 // C++14 [over.ics.list]p6:
5750 // C++11 [over.ics.list]p5:
5751 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5752 if (ToType->isReferenceType()) {
5753 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5754 // mention initializer lists in any way. So we go by what list-
5755 // initialization would do and try to extrapolate from that.
5756
5757 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5758
5759 // If the initializer list has a single element that is reference-related
5760 // to the parameter type, we initialize the reference from that.
5761 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5762 Expr *Init = From->getInit(0);
5763
5764 QualType T2 = Init->getType();
5765
5766 // If the initializer is the address of an overloaded function, try
5767 // to resolve the overloaded function. If all goes well, T2 is the
5768 // type of the resulting function.
5769 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5772 Init, ToType, false, Found))
5773 T2 = Fn->getType();
5774 }
5775
5776 // Compute some basic properties of the types and the initializer.
5777 Sema::ReferenceCompareResult RefRelationship =
5778 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5779
5780 if (RefRelationship >= Sema::Ref_Related) {
5781 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5782 SuppressUserConversions,
5783 /*AllowExplicit=*/false);
5784 }
5785 }
5786
5787 // Otherwise, we bind the reference to a temporary created from the
5788 // initializer list.
5789 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5790 InOverloadResolution,
5791 AllowObjCWritebackConversion);
5792 if (Result.isFailure())
5793 return Result;
5794 assert(!Result.isEllipsis() &&
5795 "Sub-initialization cannot result in ellipsis conversion.");
5796
5797 // Can we even bind to a temporary?
5798 if (ToType->isRValueReferenceType() ||
5799 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5800 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5801 Result.UserDefined.After;
5802 SCS.ReferenceBinding = true;
5804 SCS.BindsToRvalue = true;
5805 SCS.BindsToFunctionLvalue = false;
5808 SCS.FromBracedInitList = false;
5809
5810 } else
5812 From, ToType);
5813 return Result;
5814 }
5815
5816 // C++14 [over.ics.list]p7:
5817 // C++11 [over.ics.list]p6:
5818 // Otherwise, if the parameter type is not a class:
5819 if (!ToType->isRecordType()) {
5820 // - if the initializer list has one element that is not itself an
5821 // initializer list, the implicit conversion sequence is the one
5822 // required to convert the element to the parameter type.
5823 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5824 // single integer.
5825 unsigned NumInits = From->getNumInits();
5826 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5827 !isa<EmbedExpr>(From->getInit(0))) {
5828 Result = TryCopyInitialization(
5829 S, From->getInit(0), ToType, SuppressUserConversions,
5830 InOverloadResolution, AllowObjCWritebackConversion);
5831 if (Result.isStandard())
5832 Result.Standard.FromBracedInitList = true;
5833 }
5834 // - if the initializer list has no elements, the implicit conversion
5835 // sequence is the identity conversion.
5836 else if (NumInits == 0) {
5837 Result.setStandard();
5838 Result.Standard.setAsIdentityConversion();
5839 Result.Standard.setFromType(ToType);
5840 Result.Standard.setAllToTypes(ToType);
5841 }
5842 return Result;
5843 }
5844
5845 // C++14 [over.ics.list]p8:
5846 // C++11 [over.ics.list]p7:
5847 // In all cases other than those enumerated above, no conversion is possible
5848 return Result;
5849}
5850
5851/// TryCopyInitialization - Try to copy-initialize a value of type
5852/// ToType from the expression From. Return the implicit conversion
5853/// sequence required to pass this argument, which may be a bad
5854/// conversion sequence (meaning that the argument cannot be passed to
5855/// a parameter of this type). If @p SuppressUserConversions, then we
5856/// do not permit any user-defined conversion sequences.
5857static ImplicitConversionSequence
5859 bool SuppressUserConversions,
5860 bool InOverloadResolution,
5861 bool AllowObjCWritebackConversion,
5862 bool AllowExplicit) {
5863 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5864 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5865 InOverloadResolution,AllowObjCWritebackConversion);
5866
5867 if (ToType->isReferenceType())
5868 return TryReferenceInit(S, From, ToType,
5869 /*FIXME:*/ From->getBeginLoc(),
5870 SuppressUserConversions, AllowExplicit);
5871
5872 return TryImplicitConversion(S, From, ToType,
5873 SuppressUserConversions,
5874 AllowedExplicit::None,
5875 InOverloadResolution,
5876 /*CStyle=*/false,
5877 AllowObjCWritebackConversion,
5878 /*AllowObjCConversionOnExplicit=*/false);
5879}
5880
5881static bool TryCopyInitialization(const CanQualType FromQTy,
5882 const CanQualType ToQTy,
5883 Sema &S,
5884 SourceLocation Loc,
5885 ExprValueKind FromVK) {
5886 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5888 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5889
5890 return !ICS.isBad();
5891}
5892
5893/// TryObjectArgumentInitialization - Try to initialize the object
5894/// parameter of the given member function (@c Method) from the
5895/// expression @p From.
5897 Sema &S, SourceLocation Loc, QualType FromType,
5898 Expr::Classification FromClassification, CXXMethodDecl *Method,
5899 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5900 QualType ExplicitParameterType = QualType(),
5901 bool SuppressUserConversion = false) {
5902
5903 // We need to have an object of class type.
5904 if (const auto *PT = FromType->getAs<PointerType>()) {
5905 FromType = PT->getPointeeType();
5906
5907 // When we had a pointer, it's implicitly dereferenced, so we
5908 // better have an lvalue.
5909 assert(FromClassification.isLValue());
5910 }
5911
5912 auto ValueKindFromClassification = [](Expr::Classification C) {
5913 if (C.isPRValue())
5914 return clang::VK_PRValue;
5915 if (C.isXValue())
5916 return VK_XValue;
5917 return clang::VK_LValue;
5918 };
5919
5920 if (Method->isExplicitObjectMemberFunction()) {
5921 if (ExplicitParameterType.isNull())
5922 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5923 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5924 ValueKindFromClassification(FromClassification));
5926 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5927 /*InOverloadResolution=*/true, false);
5928 if (ICS.isBad())
5929 ICS.Bad.FromExpr = nullptr;
5930 return ICS;
5931 }
5932
5933 assert(FromType->isRecordType());
5934
5935 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5936 // C++98 [class.dtor]p2:
5937 // A destructor can be invoked for a const, volatile or const volatile
5938 // object.
5939 // C++98 [over.match.funcs]p4:
5940 // For static member functions, the implicit object parameter is considered
5941 // to match any object (since if the function is selected, the object is
5942 // discarded).
5943 Qualifiers Quals = Method->getMethodQualifiers();
5944 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5945 Quals.addConst();
5946 Quals.addVolatile();
5947 }
5948
5949 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5950
5951 // Set up the conversion sequence as a "bad" conversion, to allow us
5952 // to exit early.
5954
5955 // C++0x [over.match.funcs]p4:
5956 // For non-static member functions, the type of the implicit object
5957 // parameter is
5958 //
5959 // - "lvalue reference to cv X" for functions declared without a
5960 // ref-qualifier or with the & ref-qualifier
5961 // - "rvalue reference to cv X" for functions declared with the &&
5962 // ref-qualifier
5963 //
5964 // where X is the class of which the function is a member and cv is the
5965 // cv-qualification on the member function declaration.
5966 //
5967 // However, when finding an implicit conversion sequence for the argument, we
5968 // are not allowed to perform user-defined conversions
5969 // (C++ [over.match.funcs]p5). We perform a simplified version of
5970 // reference binding here, that allows class rvalues to bind to
5971 // non-constant references.
5972
5973 // First check the qualifiers.
5974 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5975 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5976 if (ImplicitParamType.getCVRQualifiers() !=
5977 FromTypeCanon.getLocalCVRQualifiers() &&
5978 !ImplicitParamType.isAtLeastAsQualifiedAs(
5979 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5981 FromType, ImplicitParamType);
5982 return ICS;
5983 }
5984
5985 if (FromTypeCanon.hasAddressSpace()) {
5986 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5987 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5988 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5989 S.getASTContext())) {
5991 FromType, ImplicitParamType);
5992 return ICS;
5993 }
5994 }
5995
5996 // Check that we have either the same type or a derived type. It
5997 // affects the conversion rank.
5998 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5999 ImplicitConversionKind SecondKind;
6000 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6001 SecondKind = ICK_Identity;
6002 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6003 SecondKind = ICK_Derived_To_Base;
6004 } else if (!Method->isExplicitObjectMemberFunction()) {
6006 FromType, ImplicitParamType);
6007 return ICS;
6008 }
6009
6010 // Check the ref-qualifier.
6011 switch (Method->getRefQualifier()) {
6012 case RQ_None:
6013 // Do nothing; we don't care about lvalueness or rvalueness.
6014 break;
6015
6016 case RQ_LValue:
6017 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6018 // non-const lvalue reference cannot bind to an rvalue
6020 ImplicitParamType);
6021 return ICS;
6022 }
6023 break;
6024
6025 case RQ_RValue:
6026 if (!FromClassification.isRValue()) {
6027 // rvalue reference cannot bind to an lvalue
6029 ImplicitParamType);
6030 return ICS;
6031 }
6032 break;
6033 }
6034
6035 // Success. Mark this as a reference binding.
6036 ICS.setStandard();
6038 ICS.Standard.Second = SecondKind;
6039 ICS.Standard.setFromType(FromType);
6040 ICS.Standard.setAllToTypes(ImplicitParamType);
6041 ICS.Standard.ReferenceBinding = true;
6042 ICS.Standard.DirectBinding = true;
6043 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6044 ICS.Standard.BindsToFunctionLvalue = false;
6045 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6046 ICS.Standard.FromBracedInitList = false;
6048 = (Method->getRefQualifier() == RQ_None);
6049 return ICS;
6050}
6051
6052/// PerformObjectArgumentInitialization - Perform initialization of
6053/// the implicit object parameter for the given Method with the given
6054/// expression.
6056 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6058 QualType FromRecordType, DestType;
6059 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6060
6061 Expr::Classification FromClassification;
6062 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6063 FromRecordType = PT->getPointeeType();
6064 DestType = Method->getThisType();
6065 FromClassification = Expr::Classification::makeSimpleLValue();
6066 } else {
6067 FromRecordType = From->getType();
6068 DestType = ImplicitParamRecordType;
6069 FromClassification = From->Classify(Context);
6070
6071 // CWG2813 [expr.call]p6:
6072 // If the function is an implicit object member function, the object
6073 // expression of the class member access shall be a glvalue [...]
6074 if (From->isPRValue()) {
6075 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6076 Method->getRefQualifier() !=
6078 }
6079 }
6080
6081 // Note that we always use the true parent context when performing
6082 // the actual argument initialization.
6084 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6085 Method->getParent());
6086 if (ICS.isBad()) {
6087 switch (ICS.Bad.Kind) {
6089 Qualifiers FromQs = FromRecordType.getQualifiers();
6090 Qualifiers ToQs = DestType.getQualifiers();
6091 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6092 if (CVR) {
6093 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6094 << Method->getDeclName() << FromRecordType << (CVR - 1)
6095 << From->getSourceRange();
6096 Diag(Method->getLocation(), diag::note_previous_decl)
6097 << Method->getDeclName();
6098 return ExprError();
6099 }
6100 break;
6101 }
6102
6105 bool IsRValueQualified =
6106 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6107 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6108 << Method->getDeclName() << FromClassification.isRValue()
6109 << IsRValueQualified;
6110 Diag(Method->getLocation(), diag::note_previous_decl)
6111 << Method->getDeclName();
6112 return ExprError();
6113 }
6114
6117 break;
6118
6121 llvm_unreachable("Lists are not objects");
6122 }
6123
6124 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6125 << ImplicitParamRecordType << FromRecordType
6126 << From->getSourceRange();
6127 }
6128
6129 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6130 ExprResult FromRes =
6131 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6132 if (FromRes.isInvalid())
6133 return ExprError();
6134 From = FromRes.get();
6135 }
6136
6137 if (!Context.hasSameType(From->getType(), DestType)) {
6138 CastKind CK;
6139 QualType PteeTy = DestType->getPointeeType();
6140 LangAS DestAS =
6141 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6142 if (FromRecordType.getAddressSpace() != DestAS)
6143 CK = CK_AddressSpaceConversion;
6144 else
6145 CK = CK_NoOp;
6146 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6147 }
6148 return From;
6149}
6150
6151/// TryContextuallyConvertToBool - Attempt to contextually convert the
6152/// expression From to bool (C++0x [conv]p3).
6155 // C++ [dcl.init]/17.8:
6156 // - Otherwise, if the initialization is direct-initialization, the source
6157 // type is std::nullptr_t, and the destination type is bool, the initial
6158 // value of the object being initialized is false.
6159 if (From->getType()->isNullPtrType())
6161 S.Context.BoolTy,
6162 From->isGLValue());
6163
6164 // All other direct-initialization of bool is equivalent to an implicit
6165 // conversion to bool in which explicit conversions are permitted.
6166 return TryImplicitConversion(S, From, S.Context.BoolTy,
6167 /*SuppressUserConversions=*/false,
6168 AllowedExplicit::Conversions,
6169 /*InOverloadResolution=*/false,
6170 /*CStyle=*/false,
6171 /*AllowObjCWritebackConversion=*/false,
6172 /*AllowObjCConversionOnExplicit=*/false);
6173}
6174
6176 if (checkPlaceholderForOverload(*this, From))
6177 return ExprError();
6178
6180 if (!ICS.isBad())
6181 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6183
6185 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6186 << From->getType() << From->getSourceRange();
6187 return ExprError();
6188}
6189
6190/// Check that the specified conversion is permitted in a converted constant
6191/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6192/// is acceptable.
6195 // Since we know that the target type is an integral or unscoped enumeration
6196 // type, most conversion kinds are impossible. All possible First and Third
6197 // conversions are fine.
6198 switch (SCS.Second) {
6199 case ICK_Identity:
6201 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6203 return true;
6204
6206 // Conversion from an integral or unscoped enumeration type to bool is
6207 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6208 // conversion, so we allow it in a converted constant expression.
6209 //
6210 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6211 // a lot of popular code. We should at least add a warning for this
6212 // (non-conforming) extension.
6214 SCS.getToType(2)->isBooleanType();
6215
6217 case ICK_Pointer_Member:
6218 // C++1z: null pointer conversions and null member pointer conversions are
6219 // only permitted if the source type is std::nullptr_t.
6220 return SCS.getFromType()->isNullPtrType();
6221
6233 case ICK_Vector_Splat:
6234 case ICK_Complex_Real:
6243 return false;
6244
6249 llvm_unreachable("found a first conversion kind in Second");
6250
6252 case ICK_Qualification:
6253 llvm_unreachable("found a third conversion kind in Second");
6254
6256 break;
6257 }
6258
6259 llvm_unreachable("unknown conversion kind");
6260}
6261
6262/// BuildConvertedConstantExpression - Check that the expression From is a
6263/// converted constant expression of type T, perform the conversion but
6264/// does not evaluate the expression
6266 QualType T, CCEKind CCE,
6267 NamedDecl *Dest,
6268 APValue &PreNarrowingValue) {
6269 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6271 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6272 "converted constant expression outside C++11 or TTP matching");
6273
6274 if (checkPlaceholderForOverload(S, From))
6275 return ExprError();
6276
6277 // C++1z [expr.const]p3:
6278 // A converted constant expression of type T is an expression,
6279 // implicitly converted to type T, where the converted
6280 // expression is a constant expression and the implicit conversion
6281 // sequence contains only [... list of conversions ...].
6283 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6285 : TryCopyInitialization(S, From, T,
6286 /*SuppressUserConversions=*/false,
6287 /*InOverloadResolution=*/false,
6288 /*AllowObjCWritebackConversion=*/false,
6289 /*AllowExplicit=*/false);
6290 StandardConversionSequence *SCS = nullptr;
6291 switch (ICS.getKind()) {
6293 SCS = &ICS.Standard;
6294 break;
6296 if (T->isRecordType())
6297 SCS = &ICS.UserDefined.Before;
6298 else
6299 SCS = &ICS.UserDefined.After;
6300 break;
6304 return S.Diag(From->getBeginLoc(),
6305 diag::err_typecheck_converted_constant_expression)
6306 << From->getType() << From->getSourceRange() << T;
6307 return ExprError();
6308
6311 llvm_unreachable("bad conversion in converted constant expression");
6312 }
6313
6314 // Check that we would only use permitted conversions.
6315 if (!CheckConvertedConstantConversions(S, *SCS)) {
6316 return S.Diag(From->getBeginLoc(),
6317 diag::err_typecheck_converted_constant_expression_disallowed)
6318 << From->getType() << From->getSourceRange() << T;
6319 }
6320 // [...] and where the reference binding (if any) binds directly.
6321 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6322 return S.Diag(From->getBeginLoc(),
6323 diag::err_typecheck_converted_constant_expression_indirect)
6324 << From->getType() << From->getSourceRange() << T;
6325 }
6326 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6327 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6328 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6329 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6330 // case explicitly.
6331 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6332 return S.Diag(From->getBeginLoc(),
6333 diag::err_reference_bind_to_bitfield_in_cce)
6334 << From->getSourceRange();
6335 }
6336
6337 // Usually we can simply apply the ImplicitConversionSequence we formed
6338 // earlier, but that's not guaranteed to work when initializing an object of
6339 // class type.
6340 ExprResult Result;
6341 bool IsTemplateArgument =
6343 if (T->isRecordType()) {
6344 assert(IsTemplateArgument &&
6345 "unexpected class type converted constant expr");
6346 Result = S.PerformCopyInitialization(
6349 SourceLocation(), From);
6350 } else {
6351 Result =
6353 }
6354 if (Result.isInvalid())
6355 return Result;
6356
6357 // C++2a [intro.execution]p5:
6358 // A full-expression is [...] a constant-expression [...]
6359 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6360 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6361 IsTemplateArgument);
6362 if (Result.isInvalid())
6363 return Result;
6364
6365 // Check for a narrowing implicit conversion.
6366 bool ReturnPreNarrowingValue = false;
6367 QualType PreNarrowingType;
6368 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6369 PreNarrowingType)) {
6371 // Implicit conversion to a narrower type, and the value is not a constant
6372 // expression. We'll diagnose this in a moment.
6373 case NK_Not_Narrowing:
6374 break;
6375
6377 if (CCE == CCEKind::ArrayBound &&
6378 PreNarrowingType->isIntegralOrEnumerationType() &&
6379 PreNarrowingValue.isInt()) {
6380 // Don't diagnose array bound narrowing here; we produce more precise
6381 // errors by allowing the un-narrowed value through.
6382 ReturnPreNarrowingValue = true;
6383 break;
6384 }
6385 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6386 << CCE << /*Constant*/ 1
6387 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6388 break;
6389
6391 // Implicit conversion to a narrower type, but the expression is
6392 // value-dependent so we can't tell whether it's actually narrowing.
6393 // For matching the parameters of a TTP, the conversion is ill-formed
6394 // if it may narrow.
6395 if (CCE != CCEKind::TempArgStrict)
6396 break;
6397 [[fallthrough]];
6398 case NK_Type_Narrowing:
6399 // FIXME: It would be better to diagnose that the expression is not a
6400 // constant expression.
6401 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6402 << CCE << /*Constant*/ 0 << From->getType() << T;
6403 break;
6404 }
6405 if (!ReturnPreNarrowingValue)
6406 PreNarrowingValue = {};
6407
6408 return Result;
6409}
6410
6411/// CheckConvertedConstantExpression - Check that the expression From is a
6412/// converted constant expression of type T, perform the conversion and produce
6413/// the converted expression, per C++11 [expr.const]p3.
6416 CCEKind CCE, bool RequireInt,
6417 NamedDecl *Dest) {
6418
6419 APValue PreNarrowingValue;
6420 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6421 PreNarrowingValue);
6422 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6423 Value = APValue();
6424 return Result;
6425 }
6426 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6427 RequireInt, PreNarrowingValue);
6428}
6429
6431 CCEKind CCE,
6432 NamedDecl *Dest) {
6433 APValue PreNarrowingValue;
6434 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6435 PreNarrowingValue);
6436}
6437
6439 APValue &Value, CCEKind CCE,
6440 NamedDecl *Dest) {
6441 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6442 Dest);
6443}
6444
6446 llvm::APSInt &Value,
6447 CCEKind CCE) {
6448 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6449
6450 APValue V;
6451 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6452 /*Dest=*/nullptr);
6453 if (!R.isInvalid() && !R.get()->isValueDependent())
6454 Value = V.getInt();
6455 return R;
6456}
6457
6460 CCEKind CCE, bool RequireInt,
6461 const APValue &PreNarrowingValue) {
6462
6463 ExprResult Result = E;
6464 // Check the expression is a constant expression.
6466 Expr::EvalResult Eval;
6467 Eval.Diag = &Notes;
6468
6469 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6470
6471 ConstantExprKind Kind;
6472 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6473 Kind = ConstantExprKind::ClassTemplateArgument;
6474 else if (CCE == CCEKind::TemplateArg)
6475 Kind = ConstantExprKind::NonClassTemplateArgument;
6476 else
6477 Kind = ConstantExprKind::Normal;
6478
6479 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6480 (RequireInt && !Eval.Val.isInt())) {
6481 // The expression can't be folded, so we can't keep it at this position in
6482 // the AST.
6483 Result = ExprError();
6484 } else {
6485 Value = Eval.Val;
6486
6487 if (Notes.empty()) {
6488 // It's a constant expression.
6489 Expr *E = Result.get();
6490 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6491 // We expect a ConstantExpr to have a value associated with it
6492 // by this point.
6493 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6494 "ConstantExpr has no value associated with it");
6495 (void)CE;
6496 } else {
6498 }
6499 if (!PreNarrowingValue.isAbsent())
6500 Value = std::move(PreNarrowingValue);
6501 return E;
6502 }
6503 }
6504
6505 // It's not a constant expression. Produce an appropriate diagnostic.
6506 if (Notes.size() == 1 &&
6507 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6508 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6509 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6510 diag::note_constexpr_invalid_template_arg) {
6511 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6512 for (unsigned I = 0; I < Notes.size(); ++I)
6513 Diag(Notes[I].first, Notes[I].second);
6514 } else {
6515 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6516 << CCE << E->getSourceRange();
6517 for (unsigned I = 0; I < Notes.size(); ++I)
6518 Diag(Notes[I].first, Notes[I].second);
6519 }
6520 return ExprError();
6521}
6522
6523/// dropPointerConversions - If the given standard conversion sequence
6524/// involves any pointer conversions, remove them. This may change
6525/// the result type of the conversion sequence.
6527 if (SCS.Second == ICK_Pointer_Conversion) {
6528 SCS.Second = ICK_Identity;
6529 SCS.Dimension = ICK_Identity;
6530 SCS.Third = ICK_Identity;
6531 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6532 }
6533}
6534
6535/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6536/// convert the expression From to an Objective-C pointer type.
6537static ImplicitConversionSequence
6539 // Do an implicit conversion to 'id'.
6542 = TryImplicitConversion(S, From, Ty,
6543 // FIXME: Are these flags correct?
6544 /*SuppressUserConversions=*/false,
6545 AllowedExplicit::Conversions,
6546 /*InOverloadResolution=*/false,
6547 /*CStyle=*/false,
6548 /*AllowObjCWritebackConversion=*/false,
6549 /*AllowObjCConversionOnExplicit=*/true);
6550
6551 // Strip off any final conversions to 'id'.
6552 switch (ICS.getKind()) {
6557 break;
6558
6561 break;
6562
6565 break;
6566 }
6567
6568 return ICS;
6569}
6570
6572 if (checkPlaceholderForOverload(*this, From))
6573 return ExprError();
6574
6575 QualType Ty = Context.getObjCIdType();
6578 if (!ICS.isBad())
6579 return PerformImplicitConversion(From, Ty, ICS,
6581 return ExprResult();
6582}
6583
6584static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6585 const Expr *Base = nullptr;
6586 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6587 "expected a member expression");
6588
6589 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6590 M && !M->isImplicitAccess())
6591 Base = M->getBase();
6592 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6593 M && !M->isImplicitAccess())
6594 Base = M->getBase();
6595
6596 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6597
6598 if (T->isPointerType())
6599 T = T->getPointeeType();
6600
6601 return T;
6602}
6603
6605 const FunctionDecl *Fun) {
6606 QualType ObjType = Obj->getType();
6607 if (ObjType->isPointerType()) {
6608 ObjType = ObjType->getPointeeType();
6609 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6611 /*CanOverflow=*/false, FPOptionsOverride());
6612 }
6613 return Obj;
6614}
6615
6623
6625 Expr *Object, MultiExprArg &Args,
6626 SmallVectorImpl<Expr *> &NewArgs) {
6627 assert(Method->isExplicitObjectMemberFunction() &&
6628 "Method is not an explicit member function");
6629 assert(NewArgs.empty() && "NewArgs should be empty");
6630
6631 NewArgs.reserve(Args.size() + 1);
6632 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6633 NewArgs.push_back(This);
6634 NewArgs.append(Args.begin(), Args.end());
6635 Args = NewArgs;
6637 Method, Object->getBeginLoc());
6638}
6639
6640/// Determine whether the provided type is an integral type, or an enumeration
6641/// type of a permitted flavor.
6643 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6644 : T->isIntegralOrUnscopedEnumerationType();
6645}
6646
6647static ExprResult
6650 QualType T, UnresolvedSetImpl &ViableConversions) {
6651
6652 if (Converter.Suppress)
6653 return ExprError();
6654
6655 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6656 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6657 CXXConversionDecl *Conv =
6658 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6660 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6661 }
6662 return From;
6663}
6664
6665static bool
6668 QualType T, bool HadMultipleCandidates,
6669 UnresolvedSetImpl &ExplicitConversions) {
6670 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6671 DeclAccessPair Found = ExplicitConversions[0];
6672 CXXConversionDecl *Conversion =
6673 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6674
6675 // The user probably meant to invoke the given explicit
6676 // conversion; use it.
6677 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6678 std::string TypeStr;
6679 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6680
6681 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6683 "static_cast<" + TypeStr + ">(")
6685 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6686 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6687
6688 // If we aren't in a SFINAE context, build a call to the
6689 // explicit conversion function.
6690 if (SemaRef.isSFINAEContext())
6691 return true;
6692
6693 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6694 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6695 HadMultipleCandidates);
6696 if (Result.isInvalid())
6697 return true;
6698
6699 // Replace the conversion with a RecoveryExpr, so we don't try to
6700 // instantiate it later, but can further diagnose here.
6701 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6702 From, Result.get()->getType());
6703 if (Result.isInvalid())
6704 return true;
6705 From = Result.get();
6706 }
6707 return false;
6708}
6709
6710static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6712 QualType T, bool HadMultipleCandidates,
6714 CXXConversionDecl *Conversion =
6715 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6716 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6717
6718 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6719 if (!Converter.SuppressConversion) {
6720 if (SemaRef.isSFINAEContext())
6721 return true;
6722
6723 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6724 << From->getSourceRange();
6725 }
6726
6727 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6728 HadMultipleCandidates);
6729 if (Result.isInvalid())
6730 return true;
6731 // Record usage of conversion in an implicit cast.
6732 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6733 CK_UserDefinedConversion, Result.get(),
6734 nullptr, Result.get()->getValueKind(),
6735 SemaRef.CurFPFeatureOverrides());
6736 return false;
6737}
6738
6740 Sema &SemaRef, SourceLocation Loc, Expr *From,
6742 if (!Converter.match(From->getType()) && !Converter.Suppress)
6743 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6744 << From->getSourceRange();
6745
6746 return SemaRef.DefaultLvalueConversion(From);
6747}
6748
6749static void
6751 UnresolvedSetImpl &ViableConversions,
6752 OverloadCandidateSet &CandidateSet) {
6753 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6754 NamedDecl *D = FoundDecl.getDecl();
6755 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6756 if (isa<UsingShadowDecl>(D))
6757 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6758
6759 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6761 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6762 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6763 continue;
6764 }
6766 SemaRef.AddConversionCandidate(
6767 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6768 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6769 }
6770}
6771
6772/// Attempt to convert the given expression to a type which is accepted
6773/// by the given converter.
6774///
6775/// This routine will attempt to convert an expression of class type to a
6776/// type accepted by the specified converter. In C++11 and before, the class
6777/// must have a single non-explicit conversion function converting to a matching
6778/// type. In C++1y, there can be multiple such conversion functions, but only
6779/// one target type.
6780///
6781/// \param Loc The source location of the construct that requires the
6782/// conversion.
6783///
6784/// \param From The expression we're converting from.
6785///
6786/// \param Converter Used to control and diagnose the conversion process.
6787///
6788/// \returns The expression, converted to an integral or enumeration type if
6789/// successful.
6791 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6792 // We can't perform any more checking for type-dependent expressions.
6793 if (From->isTypeDependent())
6794 return From;
6795
6796 // Process placeholders immediately.
6797 if (From->hasPlaceholderType()) {
6798 ExprResult result = CheckPlaceholderExpr(From);
6799 if (result.isInvalid())
6800 return result;
6801 From = result.get();
6802 }
6803
6804 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6805 ExprResult Converted = DefaultLvalueConversion(From);
6806 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6807 // If the expression already has a matching type, we're golden.
6808 if (Converter.match(T))
6809 return Converted;
6810
6811 // FIXME: Check for missing '()' if T is a function type?
6812
6813 // We can only perform contextual implicit conversions on objects of class
6814 // type.
6815 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6816 if (!RecordTy || !getLangOpts().CPlusPlus) {
6817 if (!Converter.Suppress)
6818 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6819 return From;
6820 }
6821
6822 // We must have a complete class type.
6823 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6824 ContextualImplicitConverter &Converter;
6825 Expr *From;
6826
6827 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6828 : Converter(Converter), From(From) {}
6829
6830 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6831 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6832 }
6833 } IncompleteDiagnoser(Converter, From);
6834
6835 if (Converter.Suppress ? !isCompleteType(Loc, T)
6836 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6837 return From;
6838
6839 // Look for a conversion to an integral or enumeration type.
6841 ViableConversions; // These are *potentially* viable in C++1y.
6842 UnresolvedSet<4> ExplicitConversions;
6843 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6844 ->getDefinitionOrSelf()
6845 ->getVisibleConversionFunctions();
6846
6847 bool HadMultipleCandidates =
6848 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6849
6850 // To check that there is only one target type, in C++1y:
6851 QualType ToType;
6852 bool HasUniqueTargetType = true;
6853
6854 // Collect explicit or viable (potentially in C++1y) conversions.
6855 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6856 NamedDecl *D = (*I)->getUnderlyingDecl();
6857 CXXConversionDecl *Conversion;
6858 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6859 if (ConvTemplate) {
6861 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6862 else
6863 continue; // C++11 does not consider conversion operator templates(?).
6864 } else
6865 Conversion = cast<CXXConversionDecl>(D);
6866
6867 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6868 "Conversion operator templates are considered potentially "
6869 "viable in C++1y");
6870
6871 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6872 if (Converter.match(CurToType) || ConvTemplate) {
6873
6874 if (Conversion->isExplicit()) {
6875 // FIXME: For C++1y, do we need this restriction?
6876 // cf. diagnoseNoViableConversion()
6877 if (!ConvTemplate)
6878 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6879 } else {
6880 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6881 if (ToType.isNull())
6882 ToType = CurToType.getUnqualifiedType();
6883 else if (HasUniqueTargetType &&
6884 (CurToType.getUnqualifiedType() != ToType))
6885 HasUniqueTargetType = false;
6886 }
6887 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6888 }
6889 }
6890 }
6891
6892 if (getLangOpts().CPlusPlus14) {
6893 // C++1y [conv]p6:
6894 // ... An expression e of class type E appearing in such a context
6895 // is said to be contextually implicitly converted to a specified
6896 // type T and is well-formed if and only if e can be implicitly
6897 // converted to a type T that is determined as follows: E is searched
6898 // for conversion functions whose return type is cv T or reference to
6899 // cv T such that T is allowed by the context. There shall be
6900 // exactly one such T.
6901
6902 // If no unique T is found:
6903 if (ToType.isNull()) {
6904 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6905 HadMultipleCandidates,
6906 ExplicitConversions))
6907 return ExprError();
6908 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6909 }
6910
6911 // If more than one unique Ts are found:
6912 if (!HasUniqueTargetType)
6913 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6914 ViableConversions);
6915
6916 // If one unique T is found:
6917 // First, build a candidate set from the previously recorded
6918 // potentially viable conversions.
6920 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6921 CandidateSet);
6922
6923 // Then, perform overload resolution over the candidate set.
6925 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6926 case OR_Success: {
6927 // Apply this conversion.
6929 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6930 if (recordConversion(*this, Loc, From, Converter, T,
6931 HadMultipleCandidates, Found))
6932 return ExprError();
6933 break;
6934 }
6935 case OR_Ambiguous:
6936 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6937 ViableConversions);
6939 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6940 HadMultipleCandidates,
6941 ExplicitConversions))
6942 return ExprError();
6943 [[fallthrough]];
6944 case OR_Deleted:
6945 // We'll complain below about a non-integral condition type.
6946 break;
6947 }
6948 } else {
6949 switch (ViableConversions.size()) {
6950 case 0: {
6951 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6952 HadMultipleCandidates,
6953 ExplicitConversions))
6954 return ExprError();
6955
6956 // We'll complain below about a non-integral condition type.
6957 break;
6958 }
6959 case 1: {
6960 // Apply this conversion.
6961 DeclAccessPair Found = ViableConversions[0];
6962 if (recordConversion(*this, Loc, From, Converter, T,
6963 HadMultipleCandidates, Found))
6964 return ExprError();
6965 break;
6966 }
6967 default:
6968 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6969 ViableConversions);
6970 }
6971 }
6972
6973 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6974}
6975
6976/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6977/// an acceptable non-member overloaded operator for a call whose
6978/// arguments have types T1 (and, if non-empty, T2). This routine
6979/// implements the check in C++ [over.match.oper]p3b2 concerning
6980/// enumeration types.
6982 FunctionDecl *Fn,
6983 ArrayRef<Expr *> Args) {
6984 QualType T1 = Args[0]->getType();
6985 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6986
6987 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6988 return true;
6989
6990 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6991 return true;
6992
6993 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6994 if (Proto->getNumParams() < 1)
6995 return false;
6996
6997 if (T1->isEnumeralType()) {
6998 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6999 if (Context.hasSameUnqualifiedType(T1, ArgType))
7000 return true;
7001 }
7002
7003 if (Proto->getNumParams() < 2)
7004 return false;
7005
7006 if (!T2.isNull() && T2->isEnumeralType()) {
7007 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7008 if (Context.hasSameUnqualifiedType(T2, ArgType))
7009 return true;
7010 }
7011
7012 return false;
7013}
7014
7017 return false;
7018
7019 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7020 return FD->isTargetMultiVersion();
7021
7022 if (!FD->isMultiVersion())
7023 return false;
7024
7025 // Among multiple target versions consider either the default,
7026 // or the first non-default in the absence of default version.
7027 unsigned SeenAt = 0;
7028 unsigned I = 0;
7029 bool HasDefault = false;
7031 FD, [&](const FunctionDecl *CurFD) {
7032 if (FD == CurFD)
7033 SeenAt = I;
7034 else if (CurFD->isTargetMultiVersionDefault())
7035 HasDefault = true;
7036 ++I;
7037 });
7038 return HasDefault || SeenAt != 0;
7039}
7040
7043 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7044 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7045 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7046 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7047 bool StrictPackMatch) {
7048 const FunctionProtoType *Proto
7049 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7050 assert(Proto && "Functions without a prototype cannot be overloaded");
7051 assert(!Function->getDescribedFunctionTemplate() &&
7052 "Use AddTemplateOverloadCandidate for function templates");
7053
7054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7056 // If we get here, it's because we're calling a member function
7057 // that is named without a member access expression (e.g.,
7058 // "this->f") that was either written explicitly or created
7059 // implicitly. This can happen with a qualified call to a member
7060 // function, e.g., X::f(). We use an empty type for the implied
7061 // object argument (C++ [over.call.func]p3), and the acting context
7062 // is irrelevant.
7063 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7065 CandidateSet, SuppressUserConversions,
7066 PartialOverloading, EarlyConversions, PO,
7067 StrictPackMatch);
7068 return;
7069 }
7070 // We treat a constructor like a non-member function, since its object
7071 // argument doesn't participate in overload resolution.
7072 }
7073
7074 if (!CandidateSet.isNewCandidate(Function, PO))
7075 return;
7076
7077 // C++11 [class.copy]p11: [DR1402]
7078 // A defaulted move constructor that is defined as deleted is ignored by
7079 // overload resolution.
7080 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7081 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7082 Constructor->isMoveConstructor())
7083 return;
7084
7085 // Overload resolution is always an unevaluated context.
7088
7089 // C++ [over.match.oper]p3:
7090 // if no operand has a class type, only those non-member functions in the
7091 // lookup set that have a first parameter of type T1 or "reference to
7092 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7093 // is a right operand) a second parameter of type T2 or "reference to
7094 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7095 // candidate functions.
7096 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7098 return;
7099
7100 // Add this candidate
7101 OverloadCandidate &Candidate =
7102 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7103 Candidate.FoundDecl = FoundDecl;
7104 Candidate.Function = Function;
7105 Candidate.Viable = true;
7106 Candidate.RewriteKind =
7107 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7108 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7109 Candidate.ExplicitCallArguments = Args.size();
7110 Candidate.StrictPackMatch = StrictPackMatch;
7111
7112 // Explicit functions are not actually candidates at all if we're not
7113 // allowing them in this context, but keep them around so we can point
7114 // to them in diagnostics.
7115 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7116 Candidate.Viable = false;
7117 Candidate.FailureKind = ovl_fail_explicit;
7118 return;
7119 }
7120
7121 // Functions with internal linkage are only viable in the same module unit.
7122 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7123 /// FIXME: Currently, the semantics of linkage in clang is slightly
7124 /// different from the semantics in C++ spec. In C++ spec, only names
7125 /// have linkage. So that all entities of the same should share one
7126 /// linkage. But in clang, different entities of the same could have
7127 /// different linkage.
7128 const NamedDecl *ND = Function;
7129 bool IsImplicitlyInstantiated = false;
7130 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7131 ND = SpecInfo->getTemplate();
7132 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7134 }
7135
7136 /// Don't remove inline functions with internal linkage from the overload
7137 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7138 /// However:
7139 /// - Inline functions with internal linkage are a common pattern in
7140 /// headers to avoid ODR issues.
7141 /// - The global module is meant to be a transition mechanism for C and C++
7142 /// headers, and the current rules as written work against that goal.
7143 const bool IsInlineFunctionInGMF =
7144 Function->isFromGlobalModule() &&
7145 (IsImplicitlyInstantiated || Function->isInlined());
7146
7147 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7148 Candidate.Viable = false;
7150 return;
7151 }
7152 }
7153
7155 Candidate.Viable = false;
7157 return;
7158 }
7159
7160 if (Constructor) {
7161 // C++ [class.copy]p3:
7162 // A member function template is never instantiated to perform the copy
7163 // of a class object to an object of its class type.
7164 CanQualType ClassType =
7165 Context.getCanonicalTagType(Constructor->getParent());
7166 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7167 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7168 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7169 ClassType))) {
7170 Candidate.Viable = false;
7172 return;
7173 }
7174
7175 // C++ [over.match.funcs]p8: (proposed DR resolution)
7176 // A constructor inherited from class type C that has a first parameter
7177 // of type "reference to P" (including such a constructor instantiated
7178 // from a template) is excluded from the set of candidate functions when
7179 // constructing an object of type cv D if the argument list has exactly
7180 // one argument and D is reference-related to P and P is reference-related
7181 // to C.
7182 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7183 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7184 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7185 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7186 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7187 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7188 SourceLocation Loc = Args.front()->getExprLoc();
7189 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7190 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7191 Candidate.Viable = false;
7193 return;
7194 }
7195 }
7196
7197 // Check that the constructor is capable of constructing an object in the
7198 // destination address space.
7200 Constructor->getMethodQualifiers().getAddressSpace(),
7201 CandidateSet.getDestAS(), getASTContext())) {
7202 Candidate.Viable = false;
7204 }
7205 }
7206
7207 unsigned NumParams = Proto->getNumParams();
7208
7209 // (C++ 13.3.2p2): A candidate function having fewer than m
7210 // parameters is viable only if it has an ellipsis in its parameter
7211 // list (8.3.5).
7212 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7213 !Proto->isVariadic() &&
7214 shouldEnforceArgLimit(PartialOverloading, Function)) {
7215 Candidate.Viable = false;
7217 return;
7218 }
7219
7220 // (C++ 13.3.2p2): A candidate function having more than m parameters
7221 // is viable only if the (m+1)st parameter has a default argument
7222 // (8.3.6). For the purposes of overload resolution, the
7223 // parameter list is truncated on the right, so that there are
7224 // exactly m parameters.
7225 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7226 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7227 !PartialOverloading) {
7228 // Not enough arguments.
7229 Candidate.Viable = false;
7231 return;
7232 }
7233
7234 // (CUDA B.1): Check for invalid calls between targets.
7235 if (getLangOpts().CUDA) {
7236 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7237 // Skip the check for callers that are implicit members, because in this
7238 // case we may not yet know what the member's target is; the target is
7239 // inferred for the member automatically, based on the bases and fields of
7240 // the class.
7241 if (!(Caller && Caller->isImplicit()) &&
7242 !CUDA().IsAllowedCall(Caller, Function)) {
7243 Candidate.Viable = false;
7244 Candidate.FailureKind = ovl_fail_bad_target;
7245 return;
7246 }
7247 }
7248
7249 if (Function->getTrailingRequiresClause()) {
7250 ConstraintSatisfaction Satisfaction;
7251 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7252 /*ForOverloadResolution*/ true) ||
7253 !Satisfaction.IsSatisfied) {
7254 Candidate.Viable = false;
7256 return;
7257 }
7258 }
7259
7260 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7261 // Determine the implicit conversion sequences for each of the
7262 // arguments.
7263 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7264 unsigned ConvIdx =
7265 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7266 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7267 // We already formed a conversion sequence for this parameter during
7268 // template argument deduction.
7269 } else if (ArgIdx < NumParams) {
7270 // (C++ 13.3.2p3): for F to be a viable function, there shall
7271 // exist for each argument an implicit conversion sequence
7272 // (13.3.3.1) that converts that argument to the corresponding
7273 // parameter of F.
7274 QualType ParamType = Proto->getParamType(ArgIdx);
7275 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7276 if (ParamABI == ParameterABI::HLSLOut ||
7277 ParamABI == ParameterABI::HLSLInOut)
7278 ParamType = ParamType.getNonReferenceType();
7279 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7280 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7281 /*InOverloadResolution=*/true,
7282 /*AllowObjCWritebackConversion=*/
7283 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7284 if (Candidate.Conversions[ConvIdx].isBad()) {
7285 Candidate.Viable = false;
7287 return;
7288 }
7289 } else {
7290 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7291 // argument for which there is no corresponding parameter is
7292 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7293 Candidate.Conversions[ConvIdx].setEllipsis();
7294 }
7295 }
7296
7297 if (EnableIfAttr *FailedAttr =
7298 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7299 Candidate.Viable = false;
7300 Candidate.FailureKind = ovl_fail_enable_if;
7301 Candidate.DeductionFailure.Data = FailedAttr;
7302 return;
7303 }
7304}
7305
7309 if (Methods.size() <= 1)
7310 return nullptr;
7311
7312 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7313 bool Match = true;
7314 ObjCMethodDecl *Method = Methods[b];
7315 unsigned NumNamedArgs = Sel.getNumArgs();
7316 // Method might have more arguments than selector indicates. This is due
7317 // to addition of c-style arguments in method.
7318 if (Method->param_size() > NumNamedArgs)
7319 NumNamedArgs = Method->param_size();
7320 if (Args.size() < NumNamedArgs)
7321 continue;
7322
7323 for (unsigned i = 0; i < NumNamedArgs; i++) {
7324 // We can't do any type-checking on a type-dependent argument.
7325 if (Args[i]->isTypeDependent()) {
7326 Match = false;
7327 break;
7328 }
7329
7330 ParmVarDecl *param = Method->parameters()[i];
7331 Expr *argExpr = Args[i];
7332 assert(argExpr && "SelectBestMethod(): missing expression");
7333
7334 // Strip the unbridged-cast placeholder expression off unless it's
7335 // a consumed argument.
7336 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7337 !param->hasAttr<CFConsumedAttr>())
7338 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7339
7340 // If the parameter is __unknown_anytype, move on to the next method.
7341 if (param->getType() == Context.UnknownAnyTy) {
7342 Match = false;
7343 break;
7344 }
7345
7346 ImplicitConversionSequence ConversionState
7347 = TryCopyInitialization(*this, argExpr, param->getType(),
7348 /*SuppressUserConversions*/false,
7349 /*InOverloadResolution=*/true,
7350 /*AllowObjCWritebackConversion=*/
7351 getLangOpts().ObjCAutoRefCount,
7352 /*AllowExplicit*/false);
7353 // This function looks for a reasonably-exact match, so we consider
7354 // incompatible pointer conversions to be a failure here.
7355 if (ConversionState.isBad() ||
7356 (ConversionState.isStandard() &&
7357 ConversionState.Standard.Second ==
7359 Match = false;
7360 break;
7361 }
7362 }
7363 // Promote additional arguments to variadic methods.
7364 if (Match && Method->isVariadic()) {
7365 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7366 if (Args[i]->isTypeDependent()) {
7367 Match = false;
7368 break;
7369 }
7371 Args[i], VariadicCallType::Method, nullptr);
7372 if (Arg.isInvalid()) {
7373 Match = false;
7374 break;
7375 }
7376 }
7377 } else {
7378 // Check for extra arguments to non-variadic methods.
7379 if (Args.size() != NumNamedArgs)
7380 Match = false;
7381 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7382 // Special case when selectors have no argument. In this case, select
7383 // one with the most general result type of 'id'.
7384 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7385 QualType ReturnT = Methods[b]->getReturnType();
7386 if (ReturnT->isObjCIdType())
7387 return Methods[b];
7388 }
7389 }
7390 }
7391
7392 if (Match)
7393 return Method;
7394 }
7395 return nullptr;
7396}
7397
7399 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7400 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7401 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7402 if (ThisArg) {
7403 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7404 assert(!isa<CXXConstructorDecl>(Method) &&
7405 "Shouldn't have `this` for ctors!");
7406 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7408 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7409 if (R.isInvalid())
7410 return false;
7411 ConvertedThis = R.get();
7412 } else {
7413 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7414 (void)MD;
7415 assert((MissingImplicitThis || MD->isStatic() ||
7417 "Expected `this` for non-ctor instance methods");
7418 }
7419 ConvertedThis = nullptr;
7420 }
7421
7422 // Ignore any variadic arguments. Converting them is pointless, since the
7423 // user can't refer to them in the function condition.
7424 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7425
7426 // Convert the arguments.
7427 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7428 ExprResult R;
7430 S.Context, Function->getParamDecl(I)),
7431 SourceLocation(), Args[I]);
7432
7433 if (R.isInvalid())
7434 return false;
7435
7436 ConvertedArgs.push_back(R.get());
7437 }
7438
7439 if (Trap.hasErrorOccurred())
7440 return false;
7441
7442 // Push default arguments if needed.
7443 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7444 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7445 ParmVarDecl *P = Function->getParamDecl(i);
7446 if (!P->hasDefaultArg())
7447 return false;
7448 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7449 if (R.isInvalid())
7450 return false;
7451 ConvertedArgs.push_back(R.get());
7452 }
7453
7454 if (Trap.hasErrorOccurred())
7455 return false;
7456 }
7457 return true;
7458}
7459
7461 SourceLocation CallLoc,
7462 ArrayRef<Expr *> Args,
7463 bool MissingImplicitThis) {
7464 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7465 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7466 return nullptr;
7467
7468 SFINAETrap Trap(*this);
7469 SmallVector<Expr *, 16> ConvertedArgs;
7470 // FIXME: We should look into making enable_if late-parsed.
7471 Expr *DiscardedThis;
7473 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7474 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7475 return *EnableIfAttrs.begin();
7476
7477 for (auto *EIA : EnableIfAttrs) {
7479 // FIXME: This doesn't consider value-dependent cases, because doing so is
7480 // very difficult. Ideally, we should handle them more gracefully.
7481 if (EIA->getCond()->isValueDependent() ||
7482 !EIA->getCond()->EvaluateWithSubstitution(
7483 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7484 return EIA;
7485
7486 if (!Result.isInt() || !Result.getInt().getBoolValue())
7487 return EIA;
7488 }
7489 return nullptr;
7490}
7491
7492template <typename CheckFn>
7494 bool ArgDependent, SourceLocation Loc,
7495 CheckFn &&IsSuccessful) {
7497 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7498 if (ArgDependent == DIA->getArgDependent())
7499 Attrs.push_back(DIA);
7500 }
7501
7502 // Common case: No diagnose_if attributes, so we can quit early.
7503 if (Attrs.empty())
7504 return false;
7505
7506 auto WarningBegin = std::stable_partition(
7507 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7508 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7509 DIA->getWarningGroup().empty();
7510 });
7511
7512 // Note that diagnose_if attributes are late-parsed, so they appear in the
7513 // correct order (unlike enable_if attributes).
7514 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7515 IsSuccessful);
7516 if (ErrAttr != WarningBegin) {
7517 const DiagnoseIfAttr *DIA = *ErrAttr;
7518 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7519 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7520 << DIA->getParent() << DIA->getCond()->getSourceRange();
7521 return true;
7522 }
7523
7524 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7525 switch (Sev) {
7526 case DiagnoseIfAttr::DS_warning:
7528 case DiagnoseIfAttr::DS_error:
7529 return diag::Severity::Error;
7530 }
7531 llvm_unreachable("Fully covered switch above!");
7532 };
7533
7534 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7535 if (IsSuccessful(DIA)) {
7536 if (DIA->getWarningGroup().empty() &&
7537 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7538 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7539 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7540 << DIA->getParent() << DIA->getCond()->getSourceRange();
7541 } else {
7542 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7543 DIA->getWarningGroup());
7544 assert(DiagGroup);
7545 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7546 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7547 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7548 S.Diag(Loc, DiagID) << DIA->getMessage();
7549 }
7550 }
7551
7552 return false;
7553}
7554
7556 const Expr *ThisArg,
7558 SourceLocation Loc) {
7560 *this, Function, /*ArgDependent=*/true, Loc,
7561 [&](const DiagnoseIfAttr *DIA) {
7563 // It's sane to use the same Args for any redecl of this function, since
7564 // EvaluateWithSubstitution only cares about the position of each
7565 // argument in the arg list, not the ParmVarDecl* it maps to.
7566 if (!DIA->getCond()->EvaluateWithSubstitution(
7567 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7568 return false;
7569 return Result.isInt() && Result.getInt().getBoolValue();
7570 });
7571}
7572
7574 SourceLocation Loc) {
7576 *this, ND, /*ArgDependent=*/false, Loc,
7577 [&](const DiagnoseIfAttr *DIA) {
7578 bool Result;
7579 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7580 Result;
7581 });
7582}
7583
7585 ArrayRef<Expr *> Args,
7586 OverloadCandidateSet &CandidateSet,
7587 TemplateArgumentListInfo *ExplicitTemplateArgs,
7588 bool SuppressUserConversions,
7589 bool PartialOverloading,
7590 bool FirstArgumentIsBase) {
7591 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7592 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7593 ArrayRef<Expr *> FunctionArgs = Args;
7594
7595 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7596 FunctionDecl *FD =
7597 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7598
7599 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7600 QualType ObjectType;
7601 Expr::Classification ObjectClassification;
7602 if (Args.size() > 0) {
7603 if (Expr *E = Args[0]) {
7604 // Use the explicit base to restrict the lookup:
7605 ObjectType = E->getType();
7606 // Pointers in the object arguments are implicitly dereferenced, so we
7607 // always classify them as l-values.
7608 if (!ObjectType.isNull() && ObjectType->isPointerType())
7609 ObjectClassification = Expr::Classification::makeSimpleLValue();
7610 else
7611 ObjectClassification = E->Classify(Context);
7612 } // .. else there is an implicit base.
7613 FunctionArgs = Args.slice(1);
7614 }
7615 if (FunTmpl) {
7617 FunTmpl, F.getPair(),
7619 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7620 FunctionArgs, CandidateSet, SuppressUserConversions,
7621 PartialOverloading);
7622 } else {
7623 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7624 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7625 ObjectClassification, FunctionArgs, CandidateSet,
7626 SuppressUserConversions, PartialOverloading);
7627 }
7628 } else {
7629 // This branch handles both standalone functions and static methods.
7630
7631 // Slice the first argument (which is the base) when we access
7632 // static method as non-static.
7633 if (Args.size() > 0 &&
7634 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7635 !isa<CXXConstructorDecl>(FD)))) {
7636 assert(cast<CXXMethodDecl>(FD)->isStatic());
7637 FunctionArgs = Args.slice(1);
7638 }
7639 if (FunTmpl) {
7640 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7641 ExplicitTemplateArgs, FunctionArgs,
7642 CandidateSet, SuppressUserConversions,
7643 PartialOverloading);
7644 } else {
7645 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7646 SuppressUserConversions, PartialOverloading);
7647 }
7648 }
7649 }
7650}
7651
7653 Expr::Classification ObjectClassification,
7654 ArrayRef<Expr *> Args,
7655 OverloadCandidateSet &CandidateSet,
7656 bool SuppressUserConversions,
7658 NamedDecl *Decl = FoundDecl.getDecl();
7660
7662 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7663
7664 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7665 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7666 "Expected a member function template");
7667 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7668 /*ExplicitArgs*/ nullptr, ObjectType,
7669 ObjectClassification, Args, CandidateSet,
7670 SuppressUserConversions, false, PO);
7671 } else {
7672 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7673 ObjectType, ObjectClassification, Args, CandidateSet,
7674 SuppressUserConversions, false, {}, PO);
7675 }
7676}
7677
7680 CXXRecordDecl *ActingContext, QualType ObjectType,
7681 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7682 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7683 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7684 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7685 const FunctionProtoType *Proto
7686 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7687 assert(Proto && "Methods without a prototype cannot be overloaded");
7689 "Use AddOverloadCandidate for constructors");
7690
7691 if (!CandidateSet.isNewCandidate(Method, PO))
7692 return;
7693
7694 // C++11 [class.copy]p23: [DR1402]
7695 // A defaulted move assignment operator that is defined as deleted is
7696 // ignored by overload resolution.
7697 if (Method->isDefaulted() && Method->isDeleted() &&
7698 Method->isMoveAssignmentOperator())
7699 return;
7700
7701 // Overload resolution is always an unevaluated context.
7704
7705 bool IgnoreExplicitObject =
7706 (Method->isExplicitObjectMemberFunction() &&
7707 CandidateSet.getKind() ==
7709 bool ImplicitObjectMethodTreatedAsStatic =
7710 CandidateSet.getKind() ==
7712 Method->isImplicitObjectMemberFunction();
7713
7714 unsigned ExplicitOffset =
7715 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7716
7717 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7718 int(ImplicitObjectMethodTreatedAsStatic);
7719
7720 unsigned ExtraArgs =
7722 ? 0
7723 : 1;
7724
7725 // Add this candidate
7726 OverloadCandidate &Candidate =
7727 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7728 Candidate.FoundDecl = FoundDecl;
7729 Candidate.Function = Method;
7730 Candidate.RewriteKind =
7731 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7732 Candidate.TookAddressOfOverload =
7734 Candidate.ExplicitCallArguments = Args.size();
7735 Candidate.StrictPackMatch = StrictPackMatch;
7736
7737 // (C++ 13.3.2p2): A candidate function having fewer than m
7738 // parameters is viable only if it has an ellipsis in its parameter
7739 // list (8.3.5).
7740 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7741 !Proto->isVariadic() &&
7742 shouldEnforceArgLimit(PartialOverloading, Method)) {
7743 Candidate.Viable = false;
7745 return;
7746 }
7747
7748 // (C++ 13.3.2p2): A candidate function having more than m parameters
7749 // is viable only if the (m+1)st parameter has a default argument
7750 // (8.3.6). For the purposes of overload resolution, the
7751 // parameter list is truncated on the right, so that there are
7752 // exactly m parameters.
7753 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7754 ExplicitOffset +
7755 int(ImplicitObjectMethodTreatedAsStatic);
7756
7757 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7758 // Not enough arguments.
7759 Candidate.Viable = false;
7761 return;
7762 }
7763
7764 Candidate.Viable = true;
7765
7766 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7767 if (!IgnoreExplicitObject) {
7768 if (ObjectType.isNull())
7769 Candidate.IgnoreObjectArgument = true;
7770 else if (Method->isStatic()) {
7771 // [over.best.ics.general]p8
7772 // When the parameter is the implicit object parameter of a static member
7773 // function, the implicit conversion sequence is a standard conversion
7774 // sequence that is neither better nor worse than any other standard
7775 // conversion sequence.
7776 //
7777 // This is a rule that was introduced in C++23 to support static lambdas.
7778 // We apply it retroactively because we want to support static lambdas as
7779 // an extension and it doesn't hurt previous code.
7780 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7781 } else {
7782 // Determine the implicit conversion sequence for the object
7783 // parameter.
7784 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7785 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7786 Method, ActingContext, /*InOverloadResolution=*/true);
7787 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7788 Candidate.Viable = false;
7790 return;
7791 }
7792 }
7793 }
7794
7795 // (CUDA B.1): Check for invalid calls between targets.
7796 if (getLangOpts().CUDA)
7797 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7798 Method)) {
7799 Candidate.Viable = false;
7800 Candidate.FailureKind = ovl_fail_bad_target;
7801 return;
7802 }
7803
7804 if (Method->getTrailingRequiresClause()) {
7805 ConstraintSatisfaction Satisfaction;
7806 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7807 /*ForOverloadResolution*/ true) ||
7808 !Satisfaction.IsSatisfied) {
7809 Candidate.Viable = false;
7811 return;
7812 }
7813 }
7814
7815 // Determine the implicit conversion sequences for each of the
7816 // arguments.
7817 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7818 unsigned ConvIdx =
7819 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7820 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7821 // We already formed a conversion sequence for this parameter during
7822 // template argument deduction.
7823 } else if (ArgIdx < NumParams) {
7824 // (C++ 13.3.2p3): for F to be a viable function, there shall
7825 // exist for each argument an implicit conversion sequence
7826 // (13.3.3.1) that converts that argument to the corresponding
7827 // parameter of F.
7828 QualType ParamType;
7829 if (ImplicitObjectMethodTreatedAsStatic) {
7830 ParamType = ArgIdx == 0
7831 ? Method->getFunctionObjectParameterReferenceType()
7832 : Proto->getParamType(ArgIdx - 1);
7833 } else {
7834 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7835 }
7836 Candidate.Conversions[ConvIdx]
7837 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7838 SuppressUserConversions,
7839 /*InOverloadResolution=*/true,
7840 /*AllowObjCWritebackConversion=*/
7841 getLangOpts().ObjCAutoRefCount);
7842 if (Candidate.Conversions[ConvIdx].isBad()) {
7843 Candidate.Viable = false;
7845 return;
7846 }
7847 } else {
7848 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7849 // argument for which there is no corresponding parameter is
7850 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7851 Candidate.Conversions[ConvIdx].setEllipsis();
7852 }
7853 }
7854
7855 if (EnableIfAttr *FailedAttr =
7856 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7857 Candidate.Viable = false;
7858 Candidate.FailureKind = ovl_fail_enable_if;
7859 Candidate.DeductionFailure.Data = FailedAttr;
7860 return;
7861 }
7862
7864 Candidate.Viable = false;
7866 }
7867}
7868
7870 Sema &S, OverloadCandidateSet &CandidateSet,
7871 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7872 CXXRecordDecl *ActingContext,
7873 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7874 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7875 bool SuppressUserConversions, bool PartialOverloading,
7877
7878 // C++ [over.match.funcs]p7:
7879 // In each case where a candidate is a function template, candidate
7880 // function template specializations are generated using template argument
7881 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7882 // candidate functions in the usual way.113) A given name can refer to one
7883 // or more function templates and also to a set of overloaded non-template
7884 // functions. In such a case, the candidate functions generated from each
7885 // function template are combined with the set of non-template candidate
7886 // functions.
7887 TemplateDeductionInfo Info(CandidateSet.getLocation());
7888 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7889 FunctionDecl *Specialization = nullptr;
7890 ConversionSequenceList Conversions;
7892 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7893 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7894 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7895 CandidateSet.getKind() ==
7897 [&](ArrayRef<QualType> ParamTypes,
7898 bool OnlyInitializeNonUserDefinedConversions) {
7899 return S.CheckNonDependentConversions(
7900 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7901 Sema::CheckNonDependentConversionsFlag(
7902 SuppressUserConversions,
7903 OnlyInitializeNonUserDefinedConversions),
7904 ActingContext, ObjectType, ObjectClassification, PO);
7905 });
7907 OverloadCandidate &Candidate =
7908 CandidateSet.addCandidate(Conversions.size(), Conversions);
7909 Candidate.FoundDecl = FoundDecl;
7910 Candidate.Function = Method;
7911 Candidate.Viable = false;
7912 Candidate.RewriteKind =
7913 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7914 Candidate.IsSurrogate = false;
7915 Candidate.TookAddressOfOverload =
7916 CandidateSet.getKind() ==
7918
7919 Candidate.IgnoreObjectArgument =
7920 Method->isStatic() ||
7921 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7922 Candidate.ExplicitCallArguments = Args.size();
7925 else {
7927 Candidate.DeductionFailure =
7928 MakeDeductionFailureInfo(S.Context, Result, Info);
7929 }
7930 return;
7931 }
7932
7933 // Add the function template specialization produced by template argument
7934 // deduction as a candidate.
7935 assert(Specialization && "Missing member function template specialization?");
7937 "Specialization is not a member function?");
7939 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7940 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7941 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7942}
7943
7945 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7946 CXXRecordDecl *ActingContext,
7947 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7948 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7949 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7950 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7951 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7952 return;
7953
7954 if (ExplicitTemplateArgs ||
7957 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7958 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7959 SuppressUserConversions, PartialOverloading, PO);
7960 return;
7961 }
7962
7964 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7965 Args, SuppressUserConversions, PartialOverloading, PO);
7966}
7967
7968/// Determine whether a given function template has a simple explicit specifier
7969/// or a non-value-dependent explicit-specification that evaluates to true.
7973
7978
7980 Sema &S, OverloadCandidateSet &CandidateSet,
7982 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7983 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7985 bool AggregateCandidateDeduction) {
7986
7987 // If the function template has a non-dependent explicit specification,
7988 // exclude it now if appropriate; we are not permitted to perform deduction
7989 // and substitution in this case.
7990 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7991 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7992 Candidate.FoundDecl = FoundDecl;
7993 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7994 Candidate.Viable = false;
7995 Candidate.FailureKind = ovl_fail_explicit;
7996 return;
7997 }
7998
7999 // C++ [over.match.funcs]p7:
8000 // In each case where a candidate is a function template, candidate
8001 // function template specializations are generated using template argument
8002 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8003 // candidate functions in the usual way.113) A given name can refer to one
8004 // or more function templates and also to a set of overloaded non-template
8005 // functions. In such a case, the candidate functions generated from each
8006 // function template are combined with the set of non-template candidate
8007 // functions.
8008 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8009 FunctionTemplate->getTemplateDepth());
8010 FunctionDecl *Specialization = nullptr;
8011 ConversionSequenceList Conversions;
8013 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8014 PartialOverloading, AggregateCandidateDeduction,
8015 /*PartialOrdering=*/false,
8016 /*ObjectType=*/QualType(),
8017 /*ObjectClassification=*/Expr::Classification(),
8018 CandidateSet.getKind() ==
8020 [&](ArrayRef<QualType> ParamTypes,
8021 bool OnlyInitializeNonUserDefinedConversions) {
8022 return S.CheckNonDependentConversions(
8023 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8024 Sema::CheckNonDependentConversionsFlag(
8025 SuppressUserConversions,
8026 OnlyInitializeNonUserDefinedConversions),
8027 nullptr, QualType(), {}, PO);
8028 });
8030 OverloadCandidate &Candidate =
8031 CandidateSet.addCandidate(Conversions.size(), Conversions);
8032 Candidate.FoundDecl = FoundDecl;
8033 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8034 Candidate.Viable = false;
8035 Candidate.RewriteKind =
8036 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8037 Candidate.IsSurrogate = false;
8038 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8039 // Ignore the object argument if there is one, since we don't have an object
8040 // type.
8041 Candidate.TookAddressOfOverload =
8042 CandidateSet.getKind() ==
8044
8045 Candidate.IgnoreObjectArgument =
8046 isa<CXXMethodDecl>(Candidate.Function) &&
8047 !cast<CXXMethodDecl>(Candidate.Function)
8048 ->isExplicitObjectMemberFunction() &&
8050
8051 Candidate.ExplicitCallArguments = Args.size();
8054 else {
8056 Candidate.DeductionFailure =
8058 }
8059 return;
8060 }
8061
8062 // Add the function template specialization produced by template argument
8063 // deduction as a candidate.
8064 assert(Specialization && "Missing function template specialization?");
8066 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8067 PartialOverloading, AllowExplicit,
8068 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8069 Info.AggregateDeductionCandidateHasMismatchedArity,
8070 Info.hasStrictPackMatch());
8071}
8072
8075 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8076 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8077 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8078 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8079 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8080 return;
8081
8082 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8083
8084 if (ExplicitTemplateArgs ||
8086 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8087 DependentExplicitSpecifier)) {
8088
8090 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8091 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8092 IsADLCandidate, PO, AggregateCandidateDeduction);
8093
8094 if (DependentExplicitSpecifier)
8096 return;
8097 }
8098
8099 CandidateSet.AddDeferredTemplateCandidate(
8100 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8101 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8102 AggregateCandidateDeduction);
8103}
8104
8107 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8109 CheckNonDependentConversionsFlag UserConversionFlag,
8110 CXXRecordDecl *ActingContext, QualType ObjectType,
8111 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8112 // FIXME: The cases in which we allow explicit conversions for constructor
8113 // arguments never consider calling a constructor template. It's not clear
8114 // that is correct.
8115 const bool AllowExplicit = false;
8116
8117 bool ForOverloadSetAddressResolution =
8119 auto *FD = FunctionTemplate->getTemplatedDecl();
8120 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8121 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8123 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8124
8125 if (Conversions.empty())
8126 Conversions =
8127 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8128
8129 // Overload resolution is always an unevaluated context.
8132
8133 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8134 // require that, but this check should never result in a hard error, and
8135 // overload resolution is permitted to sidestep instantiations.
8136 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8137 !ObjectType.isNull()) {
8138 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8139 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8140 !ParamTypes[0]->isDependentType()) {
8142 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8143 Method, ActingContext, /*InOverloadResolution=*/true,
8144 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8145 : QualType());
8146 if (Conversions[ConvIdx].isBad())
8147 return true;
8148 }
8149 }
8150
8151 // A speculative workaround for self-dependent constraint bugs that manifest
8152 // after CWG2369.
8153 // FIXME: Add references to the standard once P3606 is adopted.
8154 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8155 QualType ArgType) {
8156 ParamType = ParamType.getNonReferenceType();
8157 ArgType = ArgType.getNonReferenceType();
8158 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8159 if (PointerConv) {
8160 ParamType = ParamType->getPointeeType();
8161 ArgType = ArgType->getPointeeType();
8162 }
8163
8164 if (auto *RD = ParamType->getAsCXXRecordDecl();
8165 RD && RD->hasDefinition() &&
8166 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8167 auto Info = getConstructorInfo(ND);
8168 if (!Info)
8169 return false;
8170 CXXConstructorDecl *Ctor = Info.Constructor;
8171 /// isConvertingConstructor takes copy/move constructors into
8172 /// account!
8173 return !Ctor->isCopyOrMoveConstructor() &&
8175 /*AllowExplicit=*/true);
8176 }))
8177 return true;
8178 if (auto *RD = ArgType->getAsCXXRecordDecl();
8179 RD && RD->hasDefinition() &&
8180 !RD->getVisibleConversionFunctions().empty())
8181 return true;
8182
8183 return false;
8184 };
8185
8186 unsigned Offset =
8187 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8188 : 0;
8189
8190 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8191 I != N; ++I) {
8192 QualType ParamType = ParamTypes[I + Offset];
8193 if (!ParamType->isDependentType()) {
8194 unsigned ConvIdx;
8196 ConvIdx = Args.size() - 1 - I;
8197 assert(Args.size() + ThisConversions == 2 &&
8198 "number of args (including 'this') must be exactly 2 for "
8199 "reversed order");
8200 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8201 // would also be 0. 'this' got ConvIdx = 1 previously.
8202 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8203 } else {
8204 // For members, 'this' got ConvIdx = 0 previously.
8205 ConvIdx = ThisConversions + I;
8206 }
8207 if (Conversions[ConvIdx].isInitialized())
8208 continue;
8209 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8210 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8211 continue;
8213 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8214 /*InOverloadResolution=*/true,
8215 /*AllowObjCWritebackConversion=*/
8216 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8217 if (Conversions[ConvIdx].isBad())
8218 return true;
8219 }
8220 }
8221
8222 return false;
8223}
8224
8225/// Determine whether this is an allowable conversion from the result
8226/// of an explicit conversion operator to the expected type, per C++
8227/// [over.match.conv]p1 and [over.match.ref]p1.
8228///
8229/// \param ConvType The return type of the conversion function.
8230///
8231/// \param ToType The type we are converting to.
8232///
8233/// \param AllowObjCPointerConversion Allow a conversion from one
8234/// Objective-C pointer to another.
8235///
8236/// \returns true if the conversion is allowable, false otherwise.
8238 QualType ConvType, QualType ToType,
8239 bool AllowObjCPointerConversion) {
8240 QualType ToNonRefType = ToType.getNonReferenceType();
8241
8242 // Easy case: the types are the same.
8243 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8244 return true;
8245
8246 // Allow qualification conversions.
8247 bool ObjCLifetimeConversion;
8248 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8249 ObjCLifetimeConversion))
8250 return true;
8251
8252 // If we're not allowed to consider Objective-C pointer conversions,
8253 // we're done.
8254 if (!AllowObjCPointerConversion)
8255 return false;
8256
8257 // Is this an Objective-C pointer conversion?
8258 bool IncompatibleObjC = false;
8259 QualType ConvertedType;
8260 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8261 IncompatibleObjC);
8262}
8263
8265 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8266 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8267 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8268 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8269 assert(!Conversion->getDescribedFunctionTemplate() &&
8270 "Conversion function templates use AddTemplateConversionCandidate");
8271 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8272 if (!CandidateSet.isNewCandidate(Conversion))
8273 return;
8274
8275 // If the conversion function has an undeduced return type, trigger its
8276 // deduction now.
8277 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8278 if (DeduceReturnType(Conversion, From->getExprLoc()))
8279 return;
8280 ConvType = Conversion->getConversionType().getNonReferenceType();
8281 }
8282
8283 // If we don't allow any conversion of the result type, ignore conversion
8284 // functions that don't convert to exactly (possibly cv-qualified) T.
8285 if (!AllowResultConversion &&
8286 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8287 return;
8288
8289 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8290 // operator is only a candidate if its return type is the target type or
8291 // can be converted to the target type with a qualification conversion.
8292 //
8293 // FIXME: Include such functions in the candidate list and explain why we
8294 // can't select them.
8295 if (Conversion->isExplicit() &&
8296 !isAllowableExplicitConversion(*this, ConvType, ToType,
8297 AllowObjCConversionOnExplicit))
8298 return;
8299
8300 // Overload resolution is always an unevaluated context.
8303
8304 // Add this candidate
8305 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8306 Candidate.FoundDecl = FoundDecl;
8307 Candidate.Function = Conversion;
8309 Candidate.FinalConversion.setFromType(ConvType);
8310 Candidate.FinalConversion.setAllToTypes(ToType);
8311 Candidate.HasFinalConversion = true;
8312 Candidate.Viable = true;
8313 Candidate.ExplicitCallArguments = 1;
8314 Candidate.StrictPackMatch = StrictPackMatch;
8315
8316 // Explicit functions are not actually candidates at all if we're not
8317 // allowing them in this context, but keep them around so we can point
8318 // to them in diagnostics.
8319 if (!AllowExplicit && Conversion->isExplicit()) {
8320 Candidate.Viable = false;
8321 Candidate.FailureKind = ovl_fail_explicit;
8322 return;
8323 }
8324
8325 // C++ [over.match.funcs]p4:
8326 // For conversion functions, the function is considered to be a member of
8327 // the class of the implicit implied object argument for the purpose of
8328 // defining the type of the implicit object parameter.
8329 //
8330 // Determine the implicit conversion sequence for the implicit
8331 // object parameter.
8332 QualType ObjectType = From->getType();
8333 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8334 ObjectType = FromPtrType->getPointeeType();
8335 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8336 // C++23 [over.best.ics.general]
8337 // However, if the target is [...]
8338 // - the object parameter of a user-defined conversion function
8339 // [...] user-defined conversion sequences are not considered.
8341 *this, CandidateSet.getLocation(), From->getType(),
8342 From->Classify(Context), Conversion, ConversionContext,
8343 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8344 /*SuppressUserConversion*/ true);
8345
8346 if (Candidate.Conversions[0].isBad()) {
8347 Candidate.Viable = false;
8349 return;
8350 }
8351
8352 if (Conversion->getTrailingRequiresClause()) {
8353 ConstraintSatisfaction Satisfaction;
8354 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8355 !Satisfaction.IsSatisfied) {
8356 Candidate.Viable = false;
8358 return;
8359 }
8360 }
8361
8362 // We won't go through a user-defined type conversion function to convert a
8363 // derived to base as such conversions are given Conversion Rank. They only
8364 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8365 QualType FromCanon
8366 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8367 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8368 if (FromCanon == ToCanon ||
8369 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8370 Candidate.Viable = false;
8372 return;
8373 }
8374
8375 // To determine what the conversion from the result of calling the
8376 // conversion function to the type we're eventually trying to
8377 // convert to (ToType), we need to synthesize a call to the
8378 // conversion function and attempt copy initialization from it. This
8379 // makes sure that we get the right semantics with respect to
8380 // lvalues/rvalues and the type. Fortunately, we can allocate this
8381 // call on the stack and we don't need its arguments to be
8382 // well-formed.
8383 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8384 VK_LValue, From->getBeginLoc());
8386 Context.getPointerType(Conversion->getType()),
8387 CK_FunctionToPointerDecay, &ConversionRef,
8389
8390 QualType ConversionType = Conversion->getConversionType();
8391 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8392 Candidate.Viable = false;
8394 return;
8395 }
8396
8397 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8398
8399 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8400
8401 // Introduce a temporary expression with the right type and value category
8402 // that we can use for deduction purposes.
8403 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8404
8406 TryCopyInitialization(*this, &FakeCall, ToType,
8407 /*SuppressUserConversions=*/true,
8408 /*InOverloadResolution=*/false,
8409 /*AllowObjCWritebackConversion=*/false);
8410
8411 switch (ICS.getKind()) {
8413 Candidate.FinalConversion = ICS.Standard;
8414 Candidate.HasFinalConversion = true;
8415
8416 // C++ [over.ics.user]p3:
8417 // If the user-defined conversion is specified by a specialization of a
8418 // conversion function template, the second standard conversion sequence
8419 // shall have exact match rank.
8420 if (Conversion->getPrimaryTemplate() &&
8422 Candidate.Viable = false;
8424 return;
8425 }
8426
8427 // C++0x [dcl.init.ref]p5:
8428 // In the second case, if the reference is an rvalue reference and
8429 // the second standard conversion sequence of the user-defined
8430 // conversion sequence includes an lvalue-to-rvalue conversion, the
8431 // program is ill-formed.
8432 if (ToType->isRValueReferenceType() &&
8434 Candidate.Viable = false;
8436 return;
8437 }
8438 break;
8439
8441 Candidate.Viable = false;
8443 return;
8444
8445 default:
8446 llvm_unreachable(
8447 "Can only end up with a standard conversion sequence or failure");
8448 }
8449
8450 if (EnableIfAttr *FailedAttr =
8451 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8452 Candidate.Viable = false;
8453 Candidate.FailureKind = ovl_fail_enable_if;
8454 Candidate.DeductionFailure.Data = FailedAttr;
8455 return;
8456 }
8457
8458 if (isNonViableMultiVersionOverload(Conversion)) {
8459 Candidate.Viable = false;
8461 }
8462}
8463
8465 Sema &S, OverloadCandidateSet &CandidateSet,
8467 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8468 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8469 bool AllowResultConversion) {
8470
8471 // If the function template has a non-dependent explicit specification,
8472 // exclude it now if appropriate; we are not permitted to perform deduction
8473 // and substitution in this case.
8474 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8475 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8476 Candidate.FoundDecl = FoundDecl;
8477 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8478 Candidate.Viable = false;
8479 Candidate.FailureKind = ovl_fail_explicit;
8480 return;
8481 }
8482
8483 QualType ObjectType = From->getType();
8484 Expr::Classification ObjectClassification = From->Classify(S.Context);
8485
8486 TemplateDeductionInfo Info(CandidateSet.getLocation());
8489 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8490 Specialization, Info);
8492 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8493 Candidate.FoundDecl = FoundDecl;
8494 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8495 Candidate.Viable = false;
8497 Candidate.ExplicitCallArguments = 1;
8498 Candidate.DeductionFailure =
8499 MakeDeductionFailureInfo(S.Context, Result, Info);
8500 return;
8501 }
8502
8503 // Add the conversion function template specialization produced by
8504 // template argument deduction as a candidate.
8505 assert(Specialization && "Missing function template specialization?");
8506 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8507 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8508 AllowExplicit, AllowResultConversion,
8509 Info.hasStrictPackMatch());
8510}
8511
8514 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8515 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8516 bool AllowExplicit, bool AllowResultConversion) {
8517 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8518 "Only conversion function templates permitted here");
8519
8520 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8521 return;
8522
8524 CandidateSet.getKind() ==
8528 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8529 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8530 AllowResultConversion);
8531
8533 return;
8534 }
8535
8537 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8538 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8539}
8540
8542 DeclAccessPair FoundDecl,
8543 CXXRecordDecl *ActingContext,
8544 const FunctionProtoType *Proto,
8545 Expr *Object,
8546 ArrayRef<Expr *> Args,
8547 OverloadCandidateSet& CandidateSet) {
8548 if (!CandidateSet.isNewCandidate(Conversion))
8549 return;
8550
8551 // Overload resolution is always an unevaluated context.
8554
8555 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8556 Candidate.FoundDecl = FoundDecl;
8557 Candidate.Function = nullptr;
8558 Candidate.Surrogate = Conversion;
8559 Candidate.IsSurrogate = true;
8560 Candidate.Viable = true;
8561 Candidate.ExplicitCallArguments = Args.size();
8562
8563 // Determine the implicit conversion sequence for the implicit
8564 // object parameter.
8565 ImplicitConversionSequence ObjectInit;
8566 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8567 ObjectInit = TryCopyInitialization(*this, Object,
8568 Conversion->getParamDecl(0)->getType(),
8569 /*SuppressUserConversions=*/false,
8570 /*InOverloadResolution=*/true, false);
8571 } else {
8573 *this, CandidateSet.getLocation(), Object->getType(),
8574 Object->Classify(Context), Conversion, ActingContext);
8575 }
8576
8577 if (ObjectInit.isBad()) {
8578 Candidate.Viable = false;
8580 Candidate.Conversions[0] = ObjectInit;
8581 return;
8582 }
8583
8584 // The first conversion is actually a user-defined conversion whose
8585 // first conversion is ObjectInit's standard conversion (which is
8586 // effectively a reference binding). Record it as such.
8587 Candidate.Conversions[0].setUserDefined();
8588 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8589 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8590 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8591 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8592 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8593 Candidate.Conversions[0].UserDefined.After
8594 = Candidate.Conversions[0].UserDefined.Before;
8595 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8596
8597 // Find the
8598 unsigned NumParams = Proto->getNumParams();
8599
8600 // (C++ 13.3.2p2): A candidate function having fewer than m
8601 // parameters is viable only if it has an ellipsis in its parameter
8602 // list (8.3.5).
8603 if (Args.size() > NumParams && !Proto->isVariadic()) {
8604 Candidate.Viable = false;
8606 return;
8607 }
8608
8609 // Function types don't have any default arguments, so just check if
8610 // we have enough arguments.
8611 if (Args.size() < NumParams) {
8612 // Not enough arguments.
8613 Candidate.Viable = false;
8615 return;
8616 }
8617
8618 // Determine the implicit conversion sequences for each of the
8619 // arguments.
8620 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8621 if (ArgIdx < NumParams) {
8622 // (C++ 13.3.2p3): for F to be a viable function, there shall
8623 // exist for each argument an implicit conversion sequence
8624 // (13.3.3.1) that converts that argument to the corresponding
8625 // parameter of F.
8626 QualType ParamType = Proto->getParamType(ArgIdx);
8627 Candidate.Conversions[ArgIdx + 1]
8628 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8629 /*SuppressUserConversions=*/false,
8630 /*InOverloadResolution=*/false,
8631 /*AllowObjCWritebackConversion=*/
8632 getLangOpts().ObjCAutoRefCount);
8633 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8634 Candidate.Viable = false;
8636 return;
8637 }
8638 } else {
8639 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8640 // argument for which there is no corresponding parameter is
8641 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8642 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8643 }
8644 }
8645
8646 if (Conversion->getTrailingRequiresClause()) {
8647 ConstraintSatisfaction Satisfaction;
8648 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8649 /*ForOverloadResolution*/ true) ||
8650 !Satisfaction.IsSatisfied) {
8651 Candidate.Viable = false;
8653 return;
8654 }
8655 }
8656
8657 if (EnableIfAttr *FailedAttr =
8658 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8659 Candidate.Viable = false;
8660 Candidate.FailureKind = ovl_fail_enable_if;
8661 Candidate.DeductionFailure.Data = FailedAttr;
8662 return;
8663 }
8664}
8665
8667 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8668 OverloadCandidateSet &CandidateSet,
8669 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8670 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8671 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8672 ArrayRef<Expr *> FunctionArgs = Args;
8673
8674 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8675 FunctionDecl *FD =
8676 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8677
8678 // Don't consider rewritten functions if we're not rewriting.
8679 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8680 continue;
8681
8682 assert(!isa<CXXMethodDecl>(FD) &&
8683 "unqualified operator lookup found a member function");
8684
8685 if (FunTmpl) {
8686 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8687 FunctionArgs, CandidateSet);
8688 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8689
8690 // As template candidates are not deduced immediately,
8691 // persist the array in the overload set.
8693 FunctionArgs[1], FunctionArgs[0]);
8694 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8695 Reversed, CandidateSet, false, false, true,
8696 ADLCallKind::NotADL,
8698 }
8699 } else {
8700 if (ExplicitTemplateArgs)
8701 continue;
8702 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8703 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8704 AddOverloadCandidate(FD, F.getPair(),
8705 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8706 false, false, true, false, ADLCallKind::NotADL, {},
8708 }
8709 }
8710}
8711
8713 SourceLocation OpLoc,
8714 ArrayRef<Expr *> Args,
8715 OverloadCandidateSet &CandidateSet,
8717 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8718
8719 // C++ [over.match.oper]p3:
8720 // For a unary operator @ with an operand of a type whose
8721 // cv-unqualified version is T1, and for a binary operator @ with
8722 // a left operand of a type whose cv-unqualified version is T1 and
8723 // a right operand of a type whose cv-unqualified version is T2,
8724 // three sets of candidate functions, designated member
8725 // candidates, non-member candidates and built-in candidates, are
8726 // constructed as follows:
8727 QualType T1 = Args[0]->getType();
8728
8729 // -- If T1 is a complete class type or a class currently being
8730 // defined, the set of member candidates is the result of the
8731 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8732 // the set of member candidates is empty.
8733 if (T1->isRecordType()) {
8734 bool IsComplete = isCompleteType(OpLoc, T1);
8735 auto *T1RD = T1->getAsCXXRecordDecl();
8736 // Complete the type if it can be completed.
8737 // If the type is neither complete nor being defined, bail out now.
8738 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8739 return;
8740
8741 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8742 LookupQualifiedName(Operators, T1RD);
8743 Operators.suppressAccessDiagnostics();
8744
8745 for (LookupResult::iterator Oper = Operators.begin(),
8746 OperEnd = Operators.end();
8747 Oper != OperEnd; ++Oper) {
8748 if (Oper->getAsFunction() &&
8750 !CandidateSet.getRewriteInfo().shouldAddReversed(
8751 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8752 continue;
8753 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8754 Args[0]->Classify(Context), Args.slice(1),
8755 CandidateSet, /*SuppressUserConversion=*/false, PO);
8756 }
8757 }
8758}
8759
8761 OverloadCandidateSet& CandidateSet,
8762 bool IsAssignmentOperator,
8763 unsigned NumContextualBoolArguments) {
8764 // Overload resolution is always an unevaluated context.
8767
8768 // Add this candidate
8769 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8770 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8771 Candidate.Function = nullptr;
8772 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8773
8774 // Determine the implicit conversion sequences for each of the
8775 // arguments.
8776 Candidate.Viable = true;
8777 Candidate.ExplicitCallArguments = Args.size();
8778 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8779 // C++ [over.match.oper]p4:
8780 // For the built-in assignment operators, conversions of the
8781 // left operand are restricted as follows:
8782 // -- no temporaries are introduced to hold the left operand, and
8783 // -- no user-defined conversions are applied to the left
8784 // operand to achieve a type match with the left-most
8785 // parameter of a built-in candidate.
8786 //
8787 // We block these conversions by turning off user-defined
8788 // conversions, since that is the only way that initialization of
8789 // a reference to a non-class type can occur from something that
8790 // is not of the same type.
8791 if (ArgIdx < NumContextualBoolArguments) {
8792 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8793 "Contextual conversion to bool requires bool type");
8794 Candidate.Conversions[ArgIdx]
8795 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8796 } else {
8797 Candidate.Conversions[ArgIdx]
8798 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8799 ArgIdx == 0 && IsAssignmentOperator,
8800 /*InOverloadResolution=*/false,
8801 /*AllowObjCWritebackConversion=*/
8802 getLangOpts().ObjCAutoRefCount);
8803 }
8804 if (Candidate.Conversions[ArgIdx].isBad()) {
8805 Candidate.Viable = false;
8807 break;
8808 }
8809 }
8810}
8811
8812namespace {
8813
8814/// BuiltinCandidateTypeSet - A set of types that will be used for the
8815/// candidate operator functions for built-in operators (C++
8816/// [over.built]). The types are separated into pointer types and
8817/// enumeration types.
8818class BuiltinCandidateTypeSet {
8819 /// TypeSet - A set of types.
8820 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8821
8822 /// PointerTypes - The set of pointer types that will be used in the
8823 /// built-in candidates.
8824 TypeSet PointerTypes;
8825
8826 /// MemberPointerTypes - The set of member pointer types that will be
8827 /// used in the built-in candidates.
8828 TypeSet MemberPointerTypes;
8829
8830 /// EnumerationTypes - The set of enumeration types that will be
8831 /// used in the built-in candidates.
8832 TypeSet EnumerationTypes;
8833
8834 /// The set of vector types that will be used in the built-in
8835 /// candidates.
8836 TypeSet VectorTypes;
8837
8838 /// The set of matrix types that will be used in the built-in
8839 /// candidates.
8840 TypeSet MatrixTypes;
8841
8842 /// The set of _BitInt types that will be used in the built-in candidates.
8843 TypeSet BitIntTypes;
8844
8845 /// A flag indicating non-record types are viable candidates
8846 bool HasNonRecordTypes;
8847
8848 /// A flag indicating whether either arithmetic or enumeration types
8849 /// were present in the candidate set.
8850 bool HasArithmeticOrEnumeralTypes;
8851
8852 /// A flag indicating whether the nullptr type was present in the
8853 /// candidate set.
8854 bool HasNullPtrType;
8855
8856 /// Sema - The semantic analysis instance where we are building the
8857 /// candidate type set.
8858 Sema &SemaRef;
8859
8860 /// Context - The AST context in which we will build the type sets.
8861 ASTContext &Context;
8862
8863 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8864 const Qualifiers &VisibleQuals);
8865 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8866
8867public:
8868 /// iterator - Iterates through the types that are part of the set.
8869 typedef TypeSet::iterator iterator;
8870
8871 BuiltinCandidateTypeSet(Sema &SemaRef)
8872 : HasNonRecordTypes(false),
8873 HasArithmeticOrEnumeralTypes(false),
8874 HasNullPtrType(false),
8875 SemaRef(SemaRef),
8876 Context(SemaRef.Context) { }
8877
8878 void AddTypesConvertedFrom(QualType Ty,
8879 SourceLocation Loc,
8880 bool AllowUserConversions,
8881 bool AllowExplicitConversions,
8882 const Qualifiers &VisibleTypeConversionsQuals);
8883
8884 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8885 llvm::iterator_range<iterator> member_pointer_types() {
8886 return MemberPointerTypes;
8887 }
8888 llvm::iterator_range<iterator> enumeration_types() {
8889 return EnumerationTypes;
8890 }
8891 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8892 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8893 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8894
8895 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8896 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8897 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8898 bool hasNullPtrType() const { return HasNullPtrType; }
8899};
8900
8901} // end anonymous namespace
8902
8903/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8904/// the set of pointer types along with any more-qualified variants of
8905/// that type. For example, if @p Ty is "int const *", this routine
8906/// will add "int const *", "int const volatile *", "int const
8907/// restrict *", and "int const volatile restrict *" to the set of
8908/// pointer types. Returns true if the add of @p Ty itself succeeded,
8909/// false otherwise.
8910///
8911/// FIXME: what to do about extended qualifiers?
8912bool
8913BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8914 const Qualifiers &VisibleQuals) {
8915
8916 // Insert this type.
8917 if (!PointerTypes.insert(Ty))
8918 return false;
8919
8920 QualType PointeeTy;
8921 const PointerType *PointerTy = Ty->getAs<PointerType>();
8922 bool buildObjCPtr = false;
8923 if (!PointerTy) {
8924 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8925 PointeeTy = PTy->getPointeeType();
8926 buildObjCPtr = true;
8927 } else {
8928 PointeeTy = PointerTy->getPointeeType();
8929 }
8930
8931 // Don't add qualified variants of arrays. For one, they're not allowed
8932 // (the qualifier would sink to the element type), and for another, the
8933 // only overload situation where it matters is subscript or pointer +- int,
8934 // and those shouldn't have qualifier variants anyway.
8935 if (PointeeTy->isArrayType())
8936 return true;
8937
8938 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8939 bool hasVolatile = VisibleQuals.hasVolatile();
8940 bool hasRestrict = VisibleQuals.hasRestrict();
8941
8942 // Iterate through all strict supersets of BaseCVR.
8943 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8944 if ((CVR | BaseCVR) != CVR) continue;
8945 // Skip over volatile if no volatile found anywhere in the types.
8946 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8947
8948 // Skip over restrict if no restrict found anywhere in the types, or if
8949 // the type cannot be restrict-qualified.
8950 if ((CVR & Qualifiers::Restrict) &&
8951 (!hasRestrict ||
8952 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8953 continue;
8954
8955 // Build qualified pointee type.
8956 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8957
8958 // Build qualified pointer type.
8959 QualType QPointerTy;
8960 if (!buildObjCPtr)
8961 QPointerTy = Context.getPointerType(QPointeeTy);
8962 else
8963 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8964
8965 // Insert qualified pointer type.
8966 PointerTypes.insert(QPointerTy);
8967 }
8968
8969 return true;
8970}
8971
8972/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8973/// to the set of pointer types along with any more-qualified variants of
8974/// that type. For example, if @p Ty is "int const *", this routine
8975/// will add "int const *", "int const volatile *", "int const
8976/// restrict *", and "int const volatile restrict *" to the set of
8977/// pointer types. Returns true if the add of @p Ty itself succeeded,
8978/// false otherwise.
8979///
8980/// FIXME: what to do about extended qualifiers?
8981bool
8982BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8983 QualType Ty) {
8984 // Insert this type.
8985 if (!MemberPointerTypes.insert(Ty))
8986 return false;
8987
8988 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8989 assert(PointerTy && "type was not a member pointer type!");
8990
8991 QualType PointeeTy = PointerTy->getPointeeType();
8992 // Don't add qualified variants of arrays. For one, they're not allowed
8993 // (the qualifier would sink to the element type), and for another, the
8994 // only overload situation where it matters is subscript or pointer +- int,
8995 // and those shouldn't have qualifier variants anyway.
8996 if (PointeeTy->isArrayType())
8997 return true;
8998 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
8999
9000 // Iterate through all strict supersets of the pointee type's CVR
9001 // qualifiers.
9002 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9003 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9004 if ((CVR | BaseCVR) != CVR) continue;
9005
9006 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9007 MemberPointerTypes.insert(Context.getMemberPointerType(
9008 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9009 }
9010
9011 return true;
9012}
9013
9014/// AddTypesConvertedFrom - Add each of the types to which the type @p
9015/// Ty can be implicit converted to the given set of @p Types. We're
9016/// primarily interested in pointer types and enumeration types. We also
9017/// take member pointer types, for the conditional operator.
9018/// AllowUserConversions is true if we should look at the conversion
9019/// functions of a class type, and AllowExplicitConversions if we
9020/// should also include the explicit conversion functions of a class
9021/// type.
9022void
9023BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9024 SourceLocation Loc,
9025 bool AllowUserConversions,
9026 bool AllowExplicitConversions,
9027 const Qualifiers &VisibleQuals) {
9028 // Only deal with canonical types.
9029 Ty = Context.getCanonicalType(Ty);
9030
9031 // Look through reference types; they aren't part of the type of an
9032 // expression for the purposes of conversions.
9033 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9034 Ty = RefTy->getPointeeType();
9035
9036 // If we're dealing with an array type, decay to the pointer.
9037 if (Ty->isArrayType())
9038 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9039
9040 // Otherwise, we don't care about qualifiers on the type.
9041 Ty = Ty.getLocalUnqualifiedType();
9042
9043 // Flag if we ever add a non-record type.
9044 bool TyIsRec = Ty->isRecordType();
9045 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9046
9047 // Flag if we encounter an arithmetic type.
9048 HasArithmeticOrEnumeralTypes =
9049 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9050
9051 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9052 PointerTypes.insert(Ty);
9053 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9054 // Insert our type, and its more-qualified variants, into the set
9055 // of types.
9056 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9057 return;
9058 } else if (Ty->isMemberPointerType()) {
9059 // Member pointers are far easier, since the pointee can't be converted.
9060 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9061 return;
9062 } else if (Ty->isEnumeralType()) {
9063 HasArithmeticOrEnumeralTypes = true;
9064 EnumerationTypes.insert(Ty);
9065 } else if (Ty->isBitIntType()) {
9066 HasArithmeticOrEnumeralTypes = true;
9067 BitIntTypes.insert(Ty);
9068 } else if (Ty->isVectorType()) {
9069 // We treat vector types as arithmetic types in many contexts as an
9070 // extension.
9071 HasArithmeticOrEnumeralTypes = true;
9072 VectorTypes.insert(Ty);
9073 } else if (Ty->isMatrixType()) {
9074 // Similar to vector types, we treat vector types as arithmetic types in
9075 // many contexts as an extension.
9076 HasArithmeticOrEnumeralTypes = true;
9077 MatrixTypes.insert(Ty);
9078 } else if (Ty->isNullPtrType()) {
9079 HasNullPtrType = true;
9080 } else if (AllowUserConversions && TyIsRec) {
9081 // No conversion functions in incomplete types.
9082 if (!SemaRef.isCompleteType(Loc, Ty))
9083 return;
9084
9085 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9086 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9087 if (isa<UsingShadowDecl>(D))
9088 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9089
9090 // Skip conversion function templates; they don't tell us anything
9091 // about which builtin types we can convert to.
9093 continue;
9094
9095 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9096 if (AllowExplicitConversions || !Conv->isExplicit()) {
9097 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9098 VisibleQuals);
9099 }
9100 }
9101 }
9102}
9103/// Helper function for adjusting address spaces for the pointer or reference
9104/// operands of builtin operators depending on the argument.
9109
9110/// Helper function for AddBuiltinOperatorCandidates() that adds
9111/// the volatile- and non-volatile-qualified assignment operators for the
9112/// given type to the candidate set.
9114 QualType T,
9115 ArrayRef<Expr *> Args,
9116 OverloadCandidateSet &CandidateSet) {
9117 QualType ParamTypes[2];
9118
9119 // T& operator=(T&, T)
9120 ParamTypes[0] = S.Context.getLValueReferenceType(
9122 ParamTypes[1] = T;
9123 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9124 /*IsAssignmentOperator=*/true);
9125
9127 // volatile T& operator=(volatile T&, T)
9128 ParamTypes[0] = S.Context.getLValueReferenceType(
9130 Args[0]));
9131 ParamTypes[1] = T;
9132 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9133 /*IsAssignmentOperator=*/true);
9134 }
9135}
9136
9137/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9138/// if any, found in visible type conversion functions found in ArgExpr's type.
9139static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9140 Qualifiers VRQuals;
9141 CXXRecordDecl *ClassDecl;
9142 if (const MemberPointerType *RHSMPType =
9143 ArgExpr->getType()->getAs<MemberPointerType>())
9144 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9145 else
9146 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9147 if (!ClassDecl) {
9148 // Just to be safe, assume the worst case.
9149 VRQuals.addVolatile();
9150 VRQuals.addRestrict();
9151 return VRQuals;
9152 }
9153 if (!ClassDecl->hasDefinition())
9154 return VRQuals;
9155
9156 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9157 if (isa<UsingShadowDecl>(D))
9158 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9159 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9160 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9161 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9162 CanTy = ResTypeRef->getPointeeType();
9163 // Need to go down the pointer/mempointer chain and add qualifiers
9164 // as see them.
9165 bool done = false;
9166 while (!done) {
9167 if (CanTy.isRestrictQualified())
9168 VRQuals.addRestrict();
9169 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9170 CanTy = ResTypePtr->getPointeeType();
9171 else if (const MemberPointerType *ResTypeMPtr =
9172 CanTy->getAs<MemberPointerType>())
9173 CanTy = ResTypeMPtr->getPointeeType();
9174 else
9175 done = true;
9176 if (CanTy.isVolatileQualified())
9177 VRQuals.addVolatile();
9178 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9179 return VRQuals;
9180 }
9181 }
9182 }
9183 return VRQuals;
9184}
9185
9186// Note: We're currently only handling qualifiers that are meaningful for the
9187// LHS of compound assignment overloading.
9189 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9190 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9191 // _Atomic
9192 if (Available.hasAtomic()) {
9193 Available.removeAtomic();
9194 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9195 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9196 return;
9197 }
9198
9199 // volatile
9200 if (Available.hasVolatile()) {
9201 Available.removeVolatile();
9202 assert(!Applied.hasVolatile());
9203 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9204 Callback);
9205 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9206 return;
9207 }
9208
9209 Callback(Applied);
9210}
9211
9213 QualifiersAndAtomic Quals,
9214 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9216 Callback);
9217}
9218
9220 QualifiersAndAtomic Quals,
9221 Sema &S) {
9222 if (Quals.hasAtomic())
9224 if (Quals.hasVolatile())
9227}
9228
9229namespace {
9230
9231/// Helper class to manage the addition of builtin operator overload
9232/// candidates. It provides shared state and utility methods used throughout
9233/// the process, as well as a helper method to add each group of builtin
9234/// operator overloads from the standard to a candidate set.
9235class BuiltinOperatorOverloadBuilder {
9236 // Common instance state available to all overload candidate addition methods.
9237 Sema &S;
9238 ArrayRef<Expr *> Args;
9239 QualifiersAndAtomic VisibleTypeConversionsQuals;
9240 bool HasArithmeticOrEnumeralCandidateType;
9241 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9242 OverloadCandidateSet &CandidateSet;
9243
9244 static constexpr int ArithmeticTypesCap = 26;
9245 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9246
9247 // Define some indices used to iterate over the arithmetic types in
9248 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9249 // types are that preserved by promotion (C++ [over.built]p2).
9250 unsigned FirstIntegralType,
9251 LastIntegralType;
9252 unsigned FirstPromotedIntegralType,
9253 LastPromotedIntegralType;
9254 unsigned FirstPromotedArithmeticType,
9255 LastPromotedArithmeticType;
9256 unsigned NumArithmeticTypes;
9257
9258 void InitArithmeticTypes() {
9259 // Start of promoted types.
9260 FirstPromotedArithmeticType = 0;
9261 ArithmeticTypes.push_back(S.Context.FloatTy);
9262 ArithmeticTypes.push_back(S.Context.DoubleTy);
9263 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9265 ArithmeticTypes.push_back(S.Context.Float128Ty);
9267 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9268
9269 // Start of integral types.
9270 FirstIntegralType = ArithmeticTypes.size();
9271 FirstPromotedIntegralType = ArithmeticTypes.size();
9272 ArithmeticTypes.push_back(S.Context.IntTy);
9273 ArithmeticTypes.push_back(S.Context.LongTy);
9274 ArithmeticTypes.push_back(S.Context.LongLongTy);
9278 ArithmeticTypes.push_back(S.Context.Int128Ty);
9279 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9280 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9281 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9285 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9286
9287 /// We add candidates for the unique, unqualified _BitInt types present in
9288 /// the candidate type set. The candidate set already handled ensuring the
9289 /// type is unqualified and canonical, but because we're adding from N
9290 /// different sets, we need to do some extra work to unique things. Insert
9291 /// the candidates into a unique set, then move from that set into the list
9292 /// of arithmetic types.
9293 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9294 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9295 for (QualType BitTy : Candidate.bitint_types())
9296 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9297 }
9298 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9299 LastPromotedIntegralType = ArithmeticTypes.size();
9300 LastPromotedArithmeticType = ArithmeticTypes.size();
9301 // End of promoted types.
9302
9303 ArithmeticTypes.push_back(S.Context.BoolTy);
9304 ArithmeticTypes.push_back(S.Context.CharTy);
9305 ArithmeticTypes.push_back(S.Context.WCharTy);
9306 if (S.Context.getLangOpts().Char8)
9307 ArithmeticTypes.push_back(S.Context.Char8Ty);
9308 ArithmeticTypes.push_back(S.Context.Char16Ty);
9309 ArithmeticTypes.push_back(S.Context.Char32Ty);
9310 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9311 ArithmeticTypes.push_back(S.Context.ShortTy);
9312 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9313 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9314 LastIntegralType = ArithmeticTypes.size();
9315 NumArithmeticTypes = ArithmeticTypes.size();
9316 // End of integral types.
9317 // FIXME: What about complex? What about half?
9318
9319 // We don't know for sure how many bit-precise candidates were involved, so
9320 // we subtract those from the total when testing whether we're under the
9321 // cap or not.
9322 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9323 ArithmeticTypesCap &&
9324 "Enough inline storage for all arithmetic types.");
9325 }
9326
9327 /// Helper method to factor out the common pattern of adding overloads
9328 /// for '++' and '--' builtin operators.
9329 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9330 bool HasVolatile,
9331 bool HasRestrict) {
9332 QualType ParamTypes[2] = {
9333 S.Context.getLValueReferenceType(CandidateTy),
9334 S.Context.IntTy
9335 };
9336
9337 // Non-volatile version.
9338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9339
9340 // Use a heuristic to reduce number of builtin candidates in the set:
9341 // add volatile version only if there are conversions to a volatile type.
9342 if (HasVolatile) {
9343 ParamTypes[0] =
9345 S.Context.getVolatileType(CandidateTy));
9346 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9347 }
9348
9349 // Add restrict version only if there are conversions to a restrict type
9350 // and our candidate type is a non-restrict-qualified pointer.
9351 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9352 !CandidateTy.isRestrictQualified()) {
9353 ParamTypes[0]
9356 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9357
9358 if (HasVolatile) {
9359 ParamTypes[0]
9361 S.Context.getCVRQualifiedType(CandidateTy,
9364 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9365 }
9366 }
9367
9368 }
9369
9370 /// Helper to add an overload candidate for a binary builtin with types \p L
9371 /// and \p R.
9372 void AddCandidate(QualType L, QualType R) {
9373 QualType LandR[2] = {L, R};
9374 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9375 }
9376
9377public:
9378 BuiltinOperatorOverloadBuilder(
9379 Sema &S, ArrayRef<Expr *> Args,
9380 QualifiersAndAtomic VisibleTypeConversionsQuals,
9381 bool HasArithmeticOrEnumeralCandidateType,
9382 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9383 OverloadCandidateSet &CandidateSet)
9384 : S(S), Args(Args),
9385 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9386 HasArithmeticOrEnumeralCandidateType(
9387 HasArithmeticOrEnumeralCandidateType),
9388 CandidateTypes(CandidateTypes),
9389 CandidateSet(CandidateSet) {
9390
9391 InitArithmeticTypes();
9392 }
9393
9394 // Increment is deprecated for bool since C++17.
9395 //
9396 // C++ [over.built]p3:
9397 //
9398 // For every pair (T, VQ), where T is an arithmetic type other
9399 // than bool, and VQ is either volatile or empty, there exist
9400 // candidate operator functions of the form
9401 //
9402 // VQ T& operator++(VQ T&);
9403 // T operator++(VQ T&, int);
9404 //
9405 // C++ [over.built]p4:
9406 //
9407 // For every pair (T, VQ), where T is an arithmetic type other
9408 // than bool, and VQ is either volatile or empty, there exist
9409 // candidate operator functions of the form
9410 //
9411 // VQ T& operator--(VQ T&);
9412 // T operator--(VQ T&, int);
9413 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9414 if (!HasArithmeticOrEnumeralCandidateType)
9415 return;
9416
9417 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9418 const auto TypeOfT = ArithmeticTypes[Arith];
9419 if (TypeOfT == S.Context.BoolTy) {
9420 if (Op == OO_MinusMinus)
9421 continue;
9422 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9423 continue;
9424 }
9425 addPlusPlusMinusMinusStyleOverloads(
9426 TypeOfT,
9427 VisibleTypeConversionsQuals.hasVolatile(),
9428 VisibleTypeConversionsQuals.hasRestrict());
9429 }
9430 }
9431
9432 // C++ [over.built]p5:
9433 //
9434 // For every pair (T, VQ), where T is a cv-qualified or
9435 // cv-unqualified object type, and VQ is either volatile or
9436 // empty, there exist candidate operator functions of the form
9437 //
9438 // T*VQ& operator++(T*VQ&);
9439 // T*VQ& operator--(T*VQ&);
9440 // T* operator++(T*VQ&, int);
9441 // T* operator--(T*VQ&, int);
9442 void addPlusPlusMinusMinusPointerOverloads() {
9443 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9444 // Skip pointer types that aren't pointers to object types.
9445 if (!PtrTy->getPointeeType()->isObjectType())
9446 continue;
9447
9448 addPlusPlusMinusMinusStyleOverloads(
9449 PtrTy,
9450 (!PtrTy.isVolatileQualified() &&
9451 VisibleTypeConversionsQuals.hasVolatile()),
9452 (!PtrTy.isRestrictQualified() &&
9453 VisibleTypeConversionsQuals.hasRestrict()));
9454 }
9455 }
9456
9457 // C++ [over.built]p6:
9458 // For every cv-qualified or cv-unqualified object type T, there
9459 // exist candidate operator functions of the form
9460 //
9461 // T& operator*(T*);
9462 //
9463 // C++ [over.built]p7:
9464 // For every function type T that does not have cv-qualifiers or a
9465 // ref-qualifier, there exist candidate operator functions of the form
9466 // T& operator*(T*);
9467 void addUnaryStarPointerOverloads() {
9468 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9469 QualType PointeeTy = ParamTy->getPointeeType();
9470 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9471 continue;
9472
9473 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9474 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9475 continue;
9476
9477 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9478 }
9479 }
9480
9481 // C++ [over.built]p9:
9482 // For every promoted arithmetic type T, there exist candidate
9483 // operator functions of the form
9484 //
9485 // T operator+(T);
9486 // T operator-(T);
9487 void addUnaryPlusOrMinusArithmeticOverloads() {
9488 if (!HasArithmeticOrEnumeralCandidateType)
9489 return;
9490
9491 for (unsigned Arith = FirstPromotedArithmeticType;
9492 Arith < LastPromotedArithmeticType; ++Arith) {
9493 QualType ArithTy = ArithmeticTypes[Arith];
9494 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9495 }
9496
9497 // Extension: We also add these operators for vector types.
9498 for (QualType VecTy : CandidateTypes[0].vector_types())
9499 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9500 }
9501
9502 // C++ [over.built]p8:
9503 // For every type T, there exist candidate operator functions of
9504 // the form
9505 //
9506 // T* operator+(T*);
9507 void addUnaryPlusPointerOverloads() {
9508 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9509 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9510 }
9511
9512 // C++ [over.built]p10:
9513 // For every promoted integral type T, there exist candidate
9514 // operator functions of the form
9515 //
9516 // T operator~(T);
9517 void addUnaryTildePromotedIntegralOverloads() {
9518 if (!HasArithmeticOrEnumeralCandidateType)
9519 return;
9520
9521 for (unsigned Int = FirstPromotedIntegralType;
9522 Int < LastPromotedIntegralType; ++Int) {
9523 QualType IntTy = ArithmeticTypes[Int];
9524 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9525 }
9526
9527 // Extension: We also add this operator for vector types.
9528 for (QualType VecTy : CandidateTypes[0].vector_types())
9529 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9530 }
9531
9532 // C++ [over.match.oper]p16:
9533 // For every pointer to member type T or type std::nullptr_t, there
9534 // exist candidate operator functions of the form
9535 //
9536 // bool operator==(T,T);
9537 // bool operator!=(T,T);
9538 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9539 /// Set of (canonical) types that we've already handled.
9540 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9541
9542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9543 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9544 // Don't add the same builtin candidate twice.
9545 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9546 continue;
9547
9548 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9550 }
9551
9552 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9554 if (AddedTypes.insert(NullPtrTy).second) {
9555 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9556 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9557 }
9558 }
9559 }
9560 }
9561
9562 // C++ [over.built]p15:
9563 //
9564 // For every T, where T is an enumeration type or a pointer type,
9565 // there exist candidate operator functions of the form
9566 //
9567 // bool operator<(T, T);
9568 // bool operator>(T, T);
9569 // bool operator<=(T, T);
9570 // bool operator>=(T, T);
9571 // bool operator==(T, T);
9572 // bool operator!=(T, T);
9573 // R operator<=>(T, T)
9574 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9575 // C++ [over.match.oper]p3:
9576 // [...]the built-in candidates include all of the candidate operator
9577 // functions defined in 13.6 that, compared to the given operator, [...]
9578 // do not have the same parameter-type-list as any non-template non-member
9579 // candidate.
9580 //
9581 // Note that in practice, this only affects enumeration types because there
9582 // aren't any built-in candidates of record type, and a user-defined operator
9583 // must have an operand of record or enumeration type. Also, the only other
9584 // overloaded operator with enumeration arguments, operator=,
9585 // cannot be overloaded for enumeration types, so this is the only place
9586 // where we must suppress candidates like this.
9587 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9588 UserDefinedBinaryOperators;
9589
9590 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9591 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9592 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9593 CEnd = CandidateSet.end();
9594 C != CEnd; ++C) {
9595 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9596 continue;
9597
9598 if (C->Function->isFunctionTemplateSpecialization())
9599 continue;
9600
9601 // We interpret "same parameter-type-list" as applying to the
9602 // "synthesized candidate, with the order of the two parameters
9603 // reversed", not to the original function.
9604 bool Reversed = C->isReversed();
9605 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9606 ->getType()
9607 .getUnqualifiedType();
9608 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9609 ->getType()
9610 .getUnqualifiedType();
9611
9612 // Skip if either parameter isn't of enumeral type.
9613 if (!FirstParamType->isEnumeralType() ||
9614 !SecondParamType->isEnumeralType())
9615 continue;
9616
9617 // Add this operator to the set of known user-defined operators.
9618 UserDefinedBinaryOperators.insert(
9619 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9620 S.Context.getCanonicalType(SecondParamType)));
9621 }
9622 }
9623 }
9624
9625 /// Set of (canonical) types that we've already handled.
9626 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9627
9628 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9629 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9630 // Don't add the same builtin candidate twice.
9631 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9632 continue;
9633 if (IsSpaceship && PtrTy->isFunctionPointerType())
9634 continue;
9635
9636 QualType ParamTypes[2] = {PtrTy, PtrTy};
9637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9638 }
9639 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9640 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9641
9642 // Don't add the same builtin candidate twice, or if a user defined
9643 // candidate exists.
9644 if (!AddedTypes.insert(CanonType).second ||
9645 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9646 CanonType)))
9647 continue;
9648 QualType ParamTypes[2] = {EnumTy, EnumTy};
9649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9650 }
9651 }
9652 }
9653
9654 // C++ [over.built]p13:
9655 //
9656 // For every cv-qualified or cv-unqualified object type T
9657 // there exist candidate operator functions of the form
9658 //
9659 // T* operator+(T*, ptrdiff_t);
9660 // T& operator[](T*, ptrdiff_t); [BELOW]
9661 // T* operator-(T*, ptrdiff_t);
9662 // T* operator+(ptrdiff_t, T*);
9663 // T& operator[](ptrdiff_t, T*); [BELOW]
9664 //
9665 // C++ [over.built]p14:
9666 //
9667 // For every T, where T is a pointer to object type, there
9668 // exist candidate operator functions of the form
9669 //
9670 // ptrdiff_t operator-(T, T);
9671 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9672 /// Set of (canonical) types that we've already handled.
9673 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9674
9675 for (int Arg = 0; Arg < 2; ++Arg) {
9676 QualType AsymmetricParamTypes[2] = {
9679 };
9680 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9681 QualType PointeeTy = PtrTy->getPointeeType();
9682 if (!PointeeTy->isObjectType())
9683 continue;
9684
9685 AsymmetricParamTypes[Arg] = PtrTy;
9686 if (Arg == 0 || Op == OO_Plus) {
9687 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9688 // T* operator+(ptrdiff_t, T*);
9689 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9690 }
9691 if (Op == OO_Minus) {
9692 // ptrdiff_t operator-(T, T);
9693 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9694 continue;
9695
9696 QualType ParamTypes[2] = {PtrTy, PtrTy};
9697 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9698 }
9699 }
9700 }
9701 }
9702
9703 // C++ [over.built]p12:
9704 //
9705 // For every pair of promoted arithmetic types L and R, there
9706 // exist candidate operator functions of the form
9707 //
9708 // LR operator*(L, R);
9709 // LR operator/(L, R);
9710 // LR operator+(L, R);
9711 // LR operator-(L, R);
9712 // bool operator<(L, R);
9713 // bool operator>(L, R);
9714 // bool operator<=(L, R);
9715 // bool operator>=(L, R);
9716 // bool operator==(L, R);
9717 // bool operator!=(L, R);
9718 //
9719 // where LR is the result of the usual arithmetic conversions
9720 // between types L and R.
9721 //
9722 // C++ [over.built]p24:
9723 //
9724 // For every pair of promoted arithmetic types L and R, there exist
9725 // candidate operator functions of the form
9726 //
9727 // LR operator?(bool, L, R);
9728 //
9729 // where LR is the result of the usual arithmetic conversions
9730 // between types L and R.
9731 // Our candidates ignore the first parameter.
9732 void addGenericBinaryArithmeticOverloads() {
9733 if (!HasArithmeticOrEnumeralCandidateType)
9734 return;
9735
9736 for (unsigned Left = FirstPromotedArithmeticType;
9737 Left < LastPromotedArithmeticType; ++Left) {
9738 for (unsigned Right = FirstPromotedArithmeticType;
9739 Right < LastPromotedArithmeticType; ++Right) {
9740 QualType LandR[2] = { ArithmeticTypes[Left],
9741 ArithmeticTypes[Right] };
9742 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9743 }
9744 }
9745
9746 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9747 // conditional operator for vector types.
9748 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9749 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9750 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9751 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9752 }
9753 }
9754
9755 /// Add binary operator overloads for each candidate matrix type M1, M2:
9756 /// * (M1, M1) -> M1
9757 /// * (M1, M1.getElementType()) -> M1
9758 /// * (M2.getElementType(), M2) -> M2
9759 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9760 void addMatrixBinaryArithmeticOverloads() {
9761 if (!HasArithmeticOrEnumeralCandidateType)
9762 return;
9763
9764 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9765 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9766 AddCandidate(M1, M1);
9767 }
9768
9769 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9770 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9771 if (!CandidateTypes[0].containsMatrixType(M2))
9772 AddCandidate(M2, M2);
9773 }
9774 }
9775
9776 // C++2a [over.built]p14:
9777 //
9778 // For every integral type T there exists a candidate operator function
9779 // of the form
9780 //
9781 // std::strong_ordering operator<=>(T, T)
9782 //
9783 // C++2a [over.built]p15:
9784 //
9785 // For every pair of floating-point types L and R, there exists a candidate
9786 // operator function of the form
9787 //
9788 // std::partial_ordering operator<=>(L, R);
9789 //
9790 // FIXME: The current specification for integral types doesn't play nice with
9791 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9792 // comparisons. Under the current spec this can lead to ambiguity during
9793 // overload resolution. For example:
9794 //
9795 // enum A : int {a};
9796 // auto x = (a <=> (long)42);
9797 //
9798 // error: call is ambiguous for arguments 'A' and 'long'.
9799 // note: candidate operator<=>(int, int)
9800 // note: candidate operator<=>(long, long)
9801 //
9802 // To avoid this error, this function deviates from the specification and adds
9803 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9804 // arithmetic types (the same as the generic relational overloads).
9805 //
9806 // For now this function acts as a placeholder.
9807 void addThreeWayArithmeticOverloads() {
9808 addGenericBinaryArithmeticOverloads();
9809 }
9810
9811 // C++ [over.built]p17:
9812 //
9813 // For every pair of promoted integral types L and R, there
9814 // exist candidate operator functions of the form
9815 //
9816 // LR operator%(L, R);
9817 // LR operator&(L, R);
9818 // LR operator^(L, R);
9819 // LR operator|(L, R);
9820 // L operator<<(L, R);
9821 // L operator>>(L, R);
9822 //
9823 // where LR is the result of the usual arithmetic conversions
9824 // between types L and R.
9825 void addBinaryBitwiseArithmeticOverloads() {
9826 if (!HasArithmeticOrEnumeralCandidateType)
9827 return;
9828
9829 for (unsigned Left = FirstPromotedIntegralType;
9830 Left < LastPromotedIntegralType; ++Left) {
9831 for (unsigned Right = FirstPromotedIntegralType;
9832 Right < LastPromotedIntegralType; ++Right) {
9833 QualType LandR[2] = { ArithmeticTypes[Left],
9834 ArithmeticTypes[Right] };
9835 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9836 }
9837 }
9838 }
9839
9840 // C++ [over.built]p20:
9841 //
9842 // For every pair (T, VQ), where T is an enumeration or
9843 // pointer to member type and VQ is either volatile or
9844 // empty, there exist candidate operator functions of the form
9845 //
9846 // VQ T& operator=(VQ T&, T);
9847 void addAssignmentMemberPointerOrEnumeralOverloads() {
9848 /// Set of (canonical) types that we've already handled.
9849 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9850
9851 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9852 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9853 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9854 continue;
9855
9856 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9857 }
9858
9859 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9860 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9861 continue;
9862
9863 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9864 }
9865 }
9866 }
9867
9868 // C++ [over.built]p19:
9869 //
9870 // For every pair (T, VQ), where T is any type and VQ is either
9871 // volatile or empty, there exist candidate operator functions
9872 // of the form
9873 //
9874 // T*VQ& operator=(T*VQ&, T*);
9875 //
9876 // C++ [over.built]p21:
9877 //
9878 // For every pair (T, VQ), where T is a cv-qualified or
9879 // cv-unqualified object type and VQ is either volatile or
9880 // empty, there exist candidate operator functions of the form
9881 //
9882 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9883 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9884 void addAssignmentPointerOverloads(bool isEqualOp) {
9885 /// Set of (canonical) types that we've already handled.
9886 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9887
9888 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9889 // If this is operator=, keep track of the builtin candidates we added.
9890 if (isEqualOp)
9891 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9892 else if (!PtrTy->getPointeeType()->isObjectType())
9893 continue;
9894
9895 // non-volatile version
9896 QualType ParamTypes[2] = {
9898 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9899 };
9900 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9901 /*IsAssignmentOperator=*/ isEqualOp);
9902
9903 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9904 VisibleTypeConversionsQuals.hasVolatile();
9905 if (NeedVolatile) {
9906 // volatile version
9907 ParamTypes[0] =
9909 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9910 /*IsAssignmentOperator=*/isEqualOp);
9911 }
9912
9913 if (!PtrTy.isRestrictQualified() &&
9914 VisibleTypeConversionsQuals.hasRestrict()) {
9915 // restrict version
9916 ParamTypes[0] =
9918 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9919 /*IsAssignmentOperator=*/isEqualOp);
9920
9921 if (NeedVolatile) {
9922 // volatile restrict version
9923 ParamTypes[0] =
9926 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9927 /*IsAssignmentOperator=*/isEqualOp);
9928 }
9929 }
9930 }
9931
9932 if (isEqualOp) {
9933 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9934 // Make sure we don't add the same candidate twice.
9935 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9936 continue;
9937
9938 QualType ParamTypes[2] = {
9940 PtrTy,
9941 };
9942
9943 // non-volatile version
9944 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9945 /*IsAssignmentOperator=*/true);
9946
9947 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9948 VisibleTypeConversionsQuals.hasVolatile();
9949 if (NeedVolatile) {
9950 // volatile version
9951 ParamTypes[0] = S.Context.getLValueReferenceType(
9952 S.Context.getVolatileType(PtrTy));
9953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9954 /*IsAssignmentOperator=*/true);
9955 }
9956
9957 if (!PtrTy.isRestrictQualified() &&
9958 VisibleTypeConversionsQuals.hasRestrict()) {
9959 // restrict version
9960 ParamTypes[0] = S.Context.getLValueReferenceType(
9961 S.Context.getRestrictType(PtrTy));
9962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9963 /*IsAssignmentOperator=*/true);
9964
9965 if (NeedVolatile) {
9966 // volatile restrict version
9967 ParamTypes[0] =
9970 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9971 /*IsAssignmentOperator=*/true);
9972 }
9973 }
9974 }
9975 }
9976 }
9977
9978 // C++ [over.built]p18:
9979 //
9980 // For every triple (L, VQ, R), where L is an arithmetic type,
9981 // VQ is either volatile or empty, and R is a promoted
9982 // arithmetic type, there exist candidate operator functions of
9983 // the form
9984 //
9985 // VQ L& operator=(VQ L&, R);
9986 // VQ L& operator*=(VQ L&, R);
9987 // VQ L& operator/=(VQ L&, R);
9988 // VQ L& operator+=(VQ L&, R);
9989 // VQ L& operator-=(VQ L&, R);
9990 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9991 if (!HasArithmeticOrEnumeralCandidateType)
9992 return;
9993
9994 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9995 for (unsigned Right = FirstPromotedArithmeticType;
9996 Right < LastPromotedArithmeticType; ++Right) {
9997 QualType ParamTypes[2];
9998 ParamTypes[1] = ArithmeticTypes[Right];
10000 S, ArithmeticTypes[Left], Args[0]);
10001
10003 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10004 ParamTypes[0] =
10005 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10007 /*IsAssignmentOperator=*/isEqualOp);
10008 });
10009 }
10010 }
10011
10012 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10013 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10014 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10015 QualType ParamTypes[2];
10016 ParamTypes[1] = Vec2Ty;
10017 // Add this built-in operator as a candidate (VQ is empty).
10018 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10020 /*IsAssignmentOperator=*/isEqualOp);
10021
10022 // Add this built-in operator as a candidate (VQ is 'volatile').
10023 if (VisibleTypeConversionsQuals.hasVolatile()) {
10024 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10025 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10026 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10027 /*IsAssignmentOperator=*/isEqualOp);
10028 }
10029 }
10030 }
10031
10032 // C++ [over.built]p22:
10033 //
10034 // For every triple (L, VQ, R), where L is an integral type, VQ
10035 // is either volatile or empty, and R is a promoted integral
10036 // type, there exist candidate operator functions of the form
10037 //
10038 // VQ L& operator%=(VQ L&, R);
10039 // VQ L& operator<<=(VQ L&, R);
10040 // VQ L& operator>>=(VQ L&, R);
10041 // VQ L& operator&=(VQ L&, R);
10042 // VQ L& operator^=(VQ L&, R);
10043 // VQ L& operator|=(VQ L&, R);
10044 void addAssignmentIntegralOverloads() {
10045 if (!HasArithmeticOrEnumeralCandidateType)
10046 return;
10047
10048 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10049 for (unsigned Right = FirstPromotedIntegralType;
10050 Right < LastPromotedIntegralType; ++Right) {
10051 QualType ParamTypes[2];
10052 ParamTypes[1] = ArithmeticTypes[Right];
10054 S, ArithmeticTypes[Left], Args[0]);
10055
10057 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10058 ParamTypes[0] =
10059 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10061 });
10062 }
10063 }
10064 }
10065
10066 // C++ [over.operator]p23:
10067 //
10068 // There also exist candidate operator functions of the form
10069 //
10070 // bool operator!(bool);
10071 // bool operator&&(bool, bool);
10072 // bool operator||(bool, bool);
10073 void addExclaimOverload() {
10074 QualType ParamTy = S.Context.BoolTy;
10075 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10076 /*IsAssignmentOperator=*/false,
10077 /*NumContextualBoolArguments=*/1);
10078 }
10079 void addAmpAmpOrPipePipeOverload() {
10080 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10082 /*IsAssignmentOperator=*/false,
10083 /*NumContextualBoolArguments=*/2);
10084 }
10085
10086 // C++ [over.built]p13:
10087 //
10088 // For every cv-qualified or cv-unqualified object type T there
10089 // exist candidate operator functions of the form
10090 //
10091 // T* operator+(T*, ptrdiff_t); [ABOVE]
10092 // T& operator[](T*, ptrdiff_t);
10093 // T* operator-(T*, ptrdiff_t); [ABOVE]
10094 // T* operator+(ptrdiff_t, T*); [ABOVE]
10095 // T& operator[](ptrdiff_t, T*);
10096 void addSubscriptOverloads() {
10097 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10098 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10099 QualType PointeeType = PtrTy->getPointeeType();
10100 if (!PointeeType->isObjectType())
10101 continue;
10102
10103 // T& operator[](T*, ptrdiff_t)
10104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10105 }
10106
10107 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10108 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10109 QualType PointeeType = PtrTy->getPointeeType();
10110 if (!PointeeType->isObjectType())
10111 continue;
10112
10113 // T& operator[](ptrdiff_t, T*)
10114 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10115 }
10116 }
10117
10118 // C++ [over.built]p11:
10119 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10120 // C1 is the same type as C2 or is a derived class of C2, T is an object
10121 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10122 // there exist candidate operator functions of the form
10123 //
10124 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10125 //
10126 // where CV12 is the union of CV1 and CV2.
10127 void addArrowStarOverloads() {
10128 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10129 QualType C1Ty = PtrTy;
10130 QualType C1;
10131 QualifierCollector Q1;
10132 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10133 if (!isa<RecordType>(C1))
10134 continue;
10135 // heuristic to reduce number of builtin candidates in the set.
10136 // Add volatile/restrict version only if there are conversions to a
10137 // volatile/restrict type.
10138 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10139 continue;
10140 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10141 continue;
10142 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10143 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10144 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10145 *D2 = mptr->getMostRecentCXXRecordDecl();
10146 if (!declaresSameEntity(D1, D2) &&
10147 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10148 break;
10149 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10150 // build CV12 T&
10151 QualType T = mptr->getPointeeType();
10152 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10153 T.isVolatileQualified())
10154 continue;
10155 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10156 T.isRestrictQualified())
10157 continue;
10158 T = Q1.apply(S.Context, T);
10159 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10160 }
10161 }
10162 }
10163
10164 // Note that we don't consider the first argument, since it has been
10165 // contextually converted to bool long ago. The candidates below are
10166 // therefore added as binary.
10167 //
10168 // C++ [over.built]p25:
10169 // For every type T, where T is a pointer, pointer-to-member, or scoped
10170 // enumeration type, there exist candidate operator functions of the form
10171 //
10172 // T operator?(bool, T, T);
10173 //
10174 void addConditionalOperatorOverloads() {
10175 /// Set of (canonical) types that we've already handled.
10176 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10177
10178 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10179 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10180 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10181 continue;
10182
10183 QualType ParamTypes[2] = {PtrTy, PtrTy};
10184 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10185 }
10186
10187 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10188 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10189 continue;
10190
10191 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10192 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10193 }
10194
10195 if (S.getLangOpts().CPlusPlus11) {
10196 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10197 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10198 continue;
10199
10200 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10201 continue;
10202
10203 QualType ParamTypes[2] = {EnumTy, EnumTy};
10204 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10205 }
10206 }
10207 }
10208 }
10209};
10210
10211} // end anonymous namespace
10212
10214 SourceLocation OpLoc,
10215 ArrayRef<Expr *> Args,
10216 OverloadCandidateSet &CandidateSet) {
10217 // Find all of the types that the arguments can convert to, but only
10218 // if the operator we're looking at has built-in operator candidates
10219 // that make use of these types. Also record whether we encounter non-record
10220 // candidate types or either arithmetic or enumeral candidate types.
10221 QualifiersAndAtomic VisibleTypeConversionsQuals;
10222 VisibleTypeConversionsQuals.addConst();
10223 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10224 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10225 if (Args[ArgIdx]->getType()->isAtomicType())
10226 VisibleTypeConversionsQuals.addAtomic();
10227 }
10228
10229 bool HasNonRecordCandidateType = false;
10230 bool HasArithmeticOrEnumeralCandidateType = false;
10232 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10233 CandidateTypes.emplace_back(*this);
10234 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10235 OpLoc,
10236 true,
10237 (Op == OO_Exclaim ||
10238 Op == OO_AmpAmp ||
10239 Op == OO_PipePipe),
10240 VisibleTypeConversionsQuals);
10241 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10242 CandidateTypes[ArgIdx].hasNonRecordTypes();
10243 HasArithmeticOrEnumeralCandidateType =
10244 HasArithmeticOrEnumeralCandidateType ||
10245 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10246 }
10247
10248 // Exit early when no non-record types have been added to the candidate set
10249 // for any of the arguments to the operator.
10250 //
10251 // We can't exit early for !, ||, or &&, since there we have always have
10252 // 'bool' overloads.
10253 if (!HasNonRecordCandidateType &&
10254 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10255 return;
10256
10257 // Setup an object to manage the common state for building overloads.
10258 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10259 VisibleTypeConversionsQuals,
10260 HasArithmeticOrEnumeralCandidateType,
10261 CandidateTypes, CandidateSet);
10262
10263 // Dispatch over the operation to add in only those overloads which apply.
10264 switch (Op) {
10265 case OO_None:
10267 llvm_unreachable("Expected an overloaded operator");
10268
10269 case OO_New:
10270 case OO_Delete:
10271 case OO_Array_New:
10272 case OO_Array_Delete:
10273 case OO_Call:
10274 llvm_unreachable(
10275 "Special operators don't use AddBuiltinOperatorCandidates");
10276
10277 case OO_Comma:
10278 case OO_Arrow:
10279 case OO_Coawait:
10280 // C++ [over.match.oper]p3:
10281 // -- For the operator ',', the unary operator '&', the
10282 // operator '->', or the operator 'co_await', the
10283 // built-in candidates set is empty.
10284 break;
10285
10286 case OO_Plus: // '+' is either unary or binary
10287 if (Args.size() == 1)
10288 OpBuilder.addUnaryPlusPointerOverloads();
10289 [[fallthrough]];
10290
10291 case OO_Minus: // '-' is either unary or binary
10292 if (Args.size() == 1) {
10293 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10294 } else {
10295 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10296 OpBuilder.addGenericBinaryArithmeticOverloads();
10297 OpBuilder.addMatrixBinaryArithmeticOverloads();
10298 }
10299 break;
10300
10301 case OO_Star: // '*' is either unary or binary
10302 if (Args.size() == 1)
10303 OpBuilder.addUnaryStarPointerOverloads();
10304 else {
10305 OpBuilder.addGenericBinaryArithmeticOverloads();
10306 OpBuilder.addMatrixBinaryArithmeticOverloads();
10307 }
10308 break;
10309
10310 case OO_Slash:
10311 OpBuilder.addGenericBinaryArithmeticOverloads();
10312 break;
10313
10314 case OO_PlusPlus:
10315 case OO_MinusMinus:
10316 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10317 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10318 break;
10319
10320 case OO_EqualEqual:
10321 case OO_ExclaimEqual:
10322 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10323 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10324 OpBuilder.addGenericBinaryArithmeticOverloads();
10325 break;
10326
10327 case OO_Less:
10328 case OO_Greater:
10329 case OO_LessEqual:
10330 case OO_GreaterEqual:
10331 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10332 OpBuilder.addGenericBinaryArithmeticOverloads();
10333 break;
10334
10335 case OO_Spaceship:
10336 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10337 OpBuilder.addThreeWayArithmeticOverloads();
10338 break;
10339
10340 case OO_Percent:
10341 case OO_Caret:
10342 case OO_Pipe:
10343 case OO_LessLess:
10344 case OO_GreaterGreater:
10345 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10346 break;
10347
10348 case OO_Amp: // '&' is either unary or binary
10349 if (Args.size() == 1)
10350 // C++ [over.match.oper]p3:
10351 // -- For the operator ',', the unary operator '&', or the
10352 // operator '->', the built-in candidates set is empty.
10353 break;
10354
10355 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10356 break;
10357
10358 case OO_Tilde:
10359 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10360 break;
10361
10362 case OO_Equal:
10363 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10364 [[fallthrough]];
10365
10366 case OO_PlusEqual:
10367 case OO_MinusEqual:
10368 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10369 [[fallthrough]];
10370
10371 case OO_StarEqual:
10372 case OO_SlashEqual:
10373 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10374 break;
10375
10376 case OO_PercentEqual:
10377 case OO_LessLessEqual:
10378 case OO_GreaterGreaterEqual:
10379 case OO_AmpEqual:
10380 case OO_CaretEqual:
10381 case OO_PipeEqual:
10382 OpBuilder.addAssignmentIntegralOverloads();
10383 break;
10384
10385 case OO_Exclaim:
10386 OpBuilder.addExclaimOverload();
10387 break;
10388
10389 case OO_AmpAmp:
10390 case OO_PipePipe:
10391 OpBuilder.addAmpAmpOrPipePipeOverload();
10392 break;
10393
10394 case OO_Subscript:
10395 if (Args.size() == 2)
10396 OpBuilder.addSubscriptOverloads();
10397 break;
10398
10399 case OO_ArrowStar:
10400 OpBuilder.addArrowStarOverloads();
10401 break;
10402
10403 case OO_Conditional:
10404 OpBuilder.addConditionalOperatorOverloads();
10405 OpBuilder.addGenericBinaryArithmeticOverloads();
10406 break;
10407 }
10408}
10409
10410void
10412 SourceLocation Loc,
10413 ArrayRef<Expr *> Args,
10414 TemplateArgumentListInfo *ExplicitTemplateArgs,
10415 OverloadCandidateSet& CandidateSet,
10416 bool PartialOverloading) {
10417 ADLResult Fns;
10418
10419 // FIXME: This approach for uniquing ADL results (and removing
10420 // redundant candidates from the set) relies on pointer-equality,
10421 // which means we need to key off the canonical decl. However,
10422 // always going back to the canonical decl might not get us the
10423 // right set of default arguments. What default arguments are
10424 // we supposed to consider on ADL candidates, anyway?
10425
10426 // FIXME: Pass in the explicit template arguments?
10427 ArgumentDependentLookup(Name, Loc, Args, Fns);
10428
10429 ArrayRef<Expr *> ReversedArgs;
10430
10431 // Erase all of the candidates we already knew about.
10432 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10433 CandEnd = CandidateSet.end();
10434 Cand != CandEnd; ++Cand)
10435 if (Cand->Function) {
10436 FunctionDecl *Fn = Cand->Function;
10437 Fns.erase(Fn);
10438 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10439 Fns.erase(FunTmpl);
10440 }
10441
10442 // For each of the ADL candidates we found, add it to the overload
10443 // set.
10444 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10446
10447 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10448 if (ExplicitTemplateArgs)
10449 continue;
10450
10452 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10453 PartialOverloading, /*AllowExplicit=*/true,
10454 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10455 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10457 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10458 /*SuppressUserConversions=*/false, PartialOverloading,
10459 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10460 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10461 }
10462 } else {
10463 auto *FTD = cast<FunctionTemplateDecl>(*I);
10465 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10466 /*SuppressUserConversions=*/false, PartialOverloading,
10467 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10468 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10469 *this, Args, FTD->getTemplatedDecl())) {
10470
10471 // As template candidates are not deduced immediately,
10472 // persist the array in the overload set.
10473 if (ReversedArgs.empty())
10474 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10475
10477 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10478 /*SuppressUserConversions=*/false, PartialOverloading,
10479 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10481 }
10482 }
10483 }
10484}
10485
10486namespace {
10487enum class Comparison { Equal, Better, Worse };
10488}
10489
10490/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10491/// overload resolution.
10492///
10493/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10494/// Cand1's first N enable_if attributes have precisely the same conditions as
10495/// Cand2's first N enable_if attributes (where N = the number of enable_if
10496/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10497///
10498/// Note that you can have a pair of candidates such that Cand1's enable_if
10499/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10500/// worse than Cand1's.
10501static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10502 const FunctionDecl *Cand2) {
10503 // Common case: One (or both) decls don't have enable_if attrs.
10504 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10505 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10506 if (!Cand1Attr || !Cand2Attr) {
10507 if (Cand1Attr == Cand2Attr)
10508 return Comparison::Equal;
10509 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10510 }
10511
10512 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10513 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10514
10515 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10516 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10517 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10518 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10519
10520 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10521 // has fewer enable_if attributes than Cand2, and vice versa.
10522 if (!Cand1A)
10523 return Comparison::Worse;
10524 if (!Cand2A)
10525 return Comparison::Better;
10526
10527 Cand1ID.clear();
10528 Cand2ID.clear();
10529
10530 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10531 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10532 if (Cand1ID != Cand2ID)
10533 return Comparison::Worse;
10534 }
10535
10536 return Comparison::Equal;
10537}
10538
10539static Comparison
10541 const OverloadCandidate &Cand2) {
10542 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10543 !Cand2.Function->isMultiVersion())
10544 return Comparison::Equal;
10545
10546 // If both are invalid, they are equal. If one of them is invalid, the other
10547 // is better.
10548 if (Cand1.Function->isInvalidDecl()) {
10549 if (Cand2.Function->isInvalidDecl())
10550 return Comparison::Equal;
10551 return Comparison::Worse;
10552 }
10553 if (Cand2.Function->isInvalidDecl())
10554 return Comparison::Better;
10555
10556 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10557 // cpu_dispatch, else arbitrarily based on the identifiers.
10558 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10559 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10560 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10561 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10562
10563 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10564 return Comparison::Equal;
10565
10566 if (Cand1CPUDisp && !Cand2CPUDisp)
10567 return Comparison::Better;
10568 if (Cand2CPUDisp && !Cand1CPUDisp)
10569 return Comparison::Worse;
10570
10571 if (Cand1CPUSpec && Cand2CPUSpec) {
10572 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10573 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10574 ? Comparison::Better
10575 : Comparison::Worse;
10576
10577 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10578 FirstDiff = std::mismatch(
10579 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10580 Cand2CPUSpec->cpus_begin(),
10581 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10582 return LHS->getName() == RHS->getName();
10583 });
10584
10585 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10586 "Two different cpu-specific versions should not have the same "
10587 "identifier list, otherwise they'd be the same decl!");
10588 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10589 ? Comparison::Better
10590 : Comparison::Worse;
10591 }
10592 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10593}
10594
10595/// Compute the type of the implicit object parameter for the given function,
10596/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10597/// null QualType if there is a 'matches anything' implicit object parameter.
10598static std::optional<QualType>
10601 return std::nullopt;
10602
10603 auto *M = cast<CXXMethodDecl>(F);
10604 // Static member functions' object parameters match all types.
10605 if (M->isStatic())
10606 return QualType();
10607 return M->getFunctionObjectParameterReferenceType();
10608}
10609
10610// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10611// represent the same entity.
10612static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10613 const FunctionDecl *F2) {
10614 if (declaresSameEntity(F1, F2))
10615 return true;
10616 auto PT1 = F1->getPrimaryTemplate();
10617 auto PT2 = F2->getPrimaryTemplate();
10618 if (PT1 && PT2) {
10619 if (declaresSameEntity(PT1, PT2) ||
10620 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10621 PT2->getInstantiatedFromMemberTemplate()))
10622 return true;
10623 }
10624 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10625 // different functions with same params). Consider removing this (as no test
10626 // fail w/o it).
10627 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10628 if (First) {
10629 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10630 return *T;
10631 }
10632 assert(I < F->getNumParams());
10633 return F->getParamDecl(I++)->getType();
10634 };
10635
10636 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10637 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10638
10639 if (F1NumParams != F2NumParams)
10640 return false;
10641
10642 unsigned I1 = 0, I2 = 0;
10643 for (unsigned I = 0; I != F1NumParams; ++I) {
10644 QualType T1 = NextParam(F1, I1, I == 0);
10645 QualType T2 = NextParam(F2, I2, I == 0);
10646 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10647 if (!Context.hasSameUnqualifiedType(T1, T2))
10648 return false;
10649 }
10650 return true;
10651}
10652
10653/// We're allowed to use constraints partial ordering only if the candidates
10654/// have the same parameter types:
10655/// [over.match.best.general]p2.6
10656/// F1 and F2 are non-template functions with the same
10657/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10659 FunctionDecl *Fn2,
10660 bool IsFn1Reversed,
10661 bool IsFn2Reversed) {
10662 assert(Fn1 && Fn2);
10663 if (Fn1->isVariadic() != Fn2->isVariadic())
10664 return false;
10665
10666 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10667 IsFn1Reversed ^ IsFn2Reversed))
10668 return false;
10669
10670 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10671 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10672 if (Mem1 && Mem2) {
10673 // if they are member functions, both are direct members of the same class,
10674 // and
10675 if (Mem1->getParent() != Mem2->getParent())
10676 return false;
10677 // if both are non-static member functions, they have the same types for
10678 // their object parameters
10679 if (Mem1->isInstance() && Mem2->isInstance() &&
10681 Mem1->getFunctionObjectParameterReferenceType(),
10682 Mem1->getFunctionObjectParameterReferenceType()))
10683 return false;
10684 }
10685 return true;
10686}
10687
10688static FunctionDecl *
10690 bool IsFn1Reversed, bool IsFn2Reversed) {
10691 if (!Fn1 || !Fn2)
10692 return nullptr;
10693
10694 // C++ [temp.constr.order]:
10695 // A non-template function F1 is more partial-ordering-constrained than a
10696 // non-template function F2 if:
10697 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10698 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10699
10700 if (Cand1IsSpecialization || Cand2IsSpecialization)
10701 return nullptr;
10702
10703 // - they have the same non-object-parameter-type-lists, and [...]
10704 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10705 IsFn2Reversed))
10706 return nullptr;
10707
10708 // - the declaration of F1 is more constrained than the declaration of F2.
10709 return S.getMoreConstrainedFunction(Fn1, Fn2);
10710}
10711
10712/// isBetterOverloadCandidate - Determines whether the first overload
10713/// candidate is a better candidate than the second (C++ 13.3.3p1).
10715 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10717 bool PartialOverloading) {
10718 // Define viable functions to be better candidates than non-viable
10719 // functions.
10720 if (!Cand2.Viable)
10721 return Cand1.Viable;
10722 else if (!Cand1.Viable)
10723 return false;
10724
10725 // [CUDA] A function with 'never' preference is marked not viable, therefore
10726 // is never shown up here. The worst preference shown up here is 'wrong side',
10727 // e.g. an H function called by a HD function in device compilation. This is
10728 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10729 // function which is called only by an H function. A deferred diagnostic will
10730 // be triggered if it is emitted. However a wrong-sided function is still
10731 // a viable candidate here.
10732 //
10733 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10734 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10735 // can be emitted, Cand1 is not better than Cand2. This rule should have
10736 // precedence over other rules.
10737 //
10738 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10739 // other rules should be used to determine which is better. This is because
10740 // host/device based overloading resolution is mostly for determining
10741 // viability of a function. If two functions are both viable, other factors
10742 // should take precedence in preference, e.g. the standard-defined preferences
10743 // like argument conversion ranks or enable_if partial-ordering. The
10744 // preference for pass-object-size parameters is probably most similar to a
10745 // type-based-overloading decision and so should take priority.
10746 //
10747 // If other rules cannot determine which is better, CUDA preference will be
10748 // used again to determine which is better.
10749 //
10750 // TODO: Currently IdentifyPreference does not return correct values
10751 // for functions called in global variable initializers due to missing
10752 // correct context about device/host. Therefore we can only enforce this
10753 // rule when there is a caller. We should enforce this rule for functions
10754 // in global variable initializers once proper context is added.
10755 //
10756 // TODO: We can only enable the hostness based overloading resolution when
10757 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10758 // overloading resolution diagnostics.
10759 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10760 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10761 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10762 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10763 bool IsCand1ImplicitHD =
10765 bool IsCand2ImplicitHD =
10767 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10768 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10769 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10770 // The implicit HD function may be a function in a system header which
10771 // is forced by pragma. In device compilation, if we prefer HD candidates
10772 // over wrong-sided candidates, overloading resolution may change, which
10773 // may result in non-deferrable diagnostics. As a workaround, we let
10774 // implicit HD candidates take equal preference as wrong-sided candidates.
10775 // This will preserve the overloading resolution.
10776 // TODO: We still need special handling of implicit HD functions since
10777 // they may incur other diagnostics to be deferred. We should make all
10778 // host/device related diagnostics deferrable and remove special handling
10779 // of implicit HD functions.
10780 auto EmitThreshold =
10781 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10782 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10785 auto Cand1Emittable = P1 > EmitThreshold;
10786 auto Cand2Emittable = P2 > EmitThreshold;
10787 if (Cand1Emittable && !Cand2Emittable)
10788 return true;
10789 if (!Cand1Emittable && Cand2Emittable)
10790 return false;
10791 }
10792 }
10793
10794 // C++ [over.match.best]p1: (Changed in C++23)
10795 //
10796 // -- if F is a static member function, ICS1(F) is defined such
10797 // that ICS1(F) is neither better nor worse than ICS1(G) for
10798 // any function G, and, symmetrically, ICS1(G) is neither
10799 // better nor worse than ICS1(F).
10800 unsigned StartArg = 0;
10801 if (!Cand1.TookAddressOfOverload &&
10803 StartArg = 1;
10804
10805 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10806 // We don't allow incompatible pointer conversions in C++.
10807 if (!S.getLangOpts().CPlusPlus)
10808 return ICS.isStandard() &&
10809 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10810
10811 // The only ill-formed conversion we allow in C++ is the string literal to
10812 // char* conversion, which is only considered ill-formed after C++11.
10813 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10815 };
10816
10817 // Define functions that don't require ill-formed conversions for a given
10818 // argument to be better candidates than functions that do.
10819 unsigned NumArgs = Cand1.Conversions.size();
10820 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10821 bool HasBetterConversion = false;
10822 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10823 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10824 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10825 if (Cand1Bad != Cand2Bad) {
10826 if (Cand1Bad)
10827 return false;
10828 HasBetterConversion = true;
10829 }
10830 }
10831
10832 if (HasBetterConversion)
10833 return true;
10834
10835 // C++ [over.match.best]p1:
10836 // A viable function F1 is defined to be a better function than another
10837 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10838 // conversion sequence than ICSi(F2), and then...
10839 bool HasWorseConversion = false;
10840 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10842 Cand1.Conversions[ArgIdx],
10843 Cand2.Conversions[ArgIdx])) {
10845 // Cand1 has a better conversion sequence.
10846 HasBetterConversion = true;
10847 break;
10848
10850 if (Cand1.Function && Cand2.Function &&
10851 Cand1.isReversed() != Cand2.isReversed() &&
10852 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10853 // Work around large-scale breakage caused by considering reversed
10854 // forms of operator== in C++20:
10855 //
10856 // When comparing a function against a reversed function, if we have a
10857 // better conversion for one argument and a worse conversion for the
10858 // other, the implicit conversion sequences are treated as being equally
10859 // good.
10860 //
10861 // This prevents a comparison function from being considered ambiguous
10862 // with a reversed form that is written in the same way.
10863 //
10864 // We diagnose this as an extension from CreateOverloadedBinOp.
10865 HasWorseConversion = true;
10866 break;
10867 }
10868
10869 // Cand1 can't be better than Cand2.
10870 return false;
10871
10873 // Do nothing.
10874 break;
10875 }
10876 }
10877
10878 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10879 // ICSj(F2), or, if not that,
10880 if (HasBetterConversion && !HasWorseConversion)
10881 return true;
10882
10883 // -- the context is an initialization by user-defined conversion
10884 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10885 // from the return type of F1 to the destination type (i.e.,
10886 // the type of the entity being initialized) is a better
10887 // conversion sequence than the standard conversion sequence
10888 // from the return type of F2 to the destination type.
10890 Cand1.Function && Cand2.Function &&
10893
10894 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10895 // First check whether we prefer one of the conversion functions over the
10896 // other. This only distinguishes the results in non-standard, extension
10897 // cases such as the conversion from a lambda closure type to a function
10898 // pointer or block.
10903 Cand1.FinalConversion,
10904 Cand2.FinalConversion);
10905
10908
10909 // FIXME: Compare kind of reference binding if conversion functions
10910 // convert to a reference type used in direct reference binding, per
10911 // C++14 [over.match.best]p1 section 2 bullet 3.
10912 }
10913
10914 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10915 // as combined with the resolution to CWG issue 243.
10916 //
10917 // When the context is initialization by constructor ([over.match.ctor] or
10918 // either phase of [over.match.list]), a constructor is preferred over
10919 // a conversion function.
10920 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10921 Cand1.Function && Cand2.Function &&
10924 return isa<CXXConstructorDecl>(Cand1.Function);
10925
10926 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10927 return Cand2.StrictPackMatch;
10928
10929 // -- F1 is a non-template function and F2 is a function template
10930 // specialization, or, if not that,
10931 bool Cand1IsSpecialization = Cand1.Function &&
10933 bool Cand2IsSpecialization = Cand2.Function &&
10935 if (Cand1IsSpecialization != Cand2IsSpecialization)
10936 return Cand2IsSpecialization;
10937
10938 // -- F1 and F2 are function template specializations, and the function
10939 // template for F1 is more specialized than the template for F2
10940 // according to the partial ordering rules described in 14.5.5.2, or,
10941 // if not that,
10942 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10943 const auto *Obj1Context =
10944 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10945 const auto *Obj2Context =
10946 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10947 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10949 Cand2.Function->getPrimaryTemplate(), Loc,
10951 : TPOC_Call,
10953 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10954 : QualType{},
10955 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10956 : QualType{},
10957 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10958 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10959 }
10960 }
10961
10962 // -— F1 and F2 are non-template functions and F1 is more
10963 // partial-ordering-constrained than F2 [...],
10965 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10966 Cand2.isReversed());
10967 F && F == Cand1.Function)
10968 return true;
10969
10970 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10971 // class B of D, and for all arguments the corresponding parameters of
10972 // F1 and F2 have the same type.
10973 // FIXME: Implement the "all parameters have the same type" check.
10974 bool Cand1IsInherited =
10975 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10976 bool Cand2IsInherited =
10977 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10978 if (Cand1IsInherited != Cand2IsInherited)
10979 return Cand2IsInherited;
10980 else if (Cand1IsInherited) {
10981 assert(Cand2IsInherited);
10982 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10983 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10984 if (Cand1Class->isDerivedFrom(Cand2Class))
10985 return true;
10986 if (Cand2Class->isDerivedFrom(Cand1Class))
10987 return false;
10988 // Inherited from sibling base classes: still ambiguous.
10989 }
10990
10991 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10992 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10993 // with reversed order of parameters and F1 is not
10994 //
10995 // We rank reversed + different operator as worse than just reversed, but
10996 // that comparison can never happen, because we only consider reversing for
10997 // the maximally-rewritten operator (== or <=>).
10998 if (Cand1.RewriteKind != Cand2.RewriteKind)
10999 return Cand1.RewriteKind < Cand2.RewriteKind;
11000
11001 // Check C++17 tie-breakers for deduction guides.
11002 {
11003 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11004 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11005 if (Guide1 && Guide2) {
11006 // -- F1 is generated from a deduction-guide and F2 is not
11007 if (Guide1->isImplicit() != Guide2->isImplicit())
11008 return Guide2->isImplicit();
11009
11010 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11011 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11012 return true;
11013 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11014 return false;
11015
11016 // --F1 is generated from a non-template constructor and F2 is generated
11017 // from a constructor template
11018 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11019 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11020 if (Constructor1 && Constructor2) {
11021 bool isC1Templated = Constructor1->getTemplatedKind() !=
11023 bool isC2Templated = Constructor2->getTemplatedKind() !=
11025 if (isC1Templated != isC2Templated)
11026 return isC2Templated;
11027 }
11028 }
11029 }
11030
11031 // Check for enable_if value-based overload resolution.
11032 if (Cand1.Function && Cand2.Function) {
11033 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11034 if (Cmp != Comparison::Equal)
11035 return Cmp == Comparison::Better;
11036 }
11037
11038 bool HasPS1 = Cand1.Function != nullptr &&
11040 bool HasPS2 = Cand2.Function != nullptr &&
11042 if (HasPS1 != HasPS2 && HasPS1)
11043 return true;
11044
11045 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11046 if (MV == Comparison::Better)
11047 return true;
11048 if (MV == Comparison::Worse)
11049 return false;
11050
11051 // If other rules cannot determine which is better, CUDA preference is used
11052 // to determine which is better.
11053 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11054 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11055 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11056 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11057 }
11058
11059 // General member function overloading is handled above, so this only handles
11060 // constructors with address spaces.
11061 // This only handles address spaces since C++ has no other
11062 // qualifier that can be used with constructors.
11063 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11064 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11065 if (CD1 && CD2) {
11066 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11067 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11068 if (AS1 != AS2) {
11070 return true;
11072 return false;
11073 }
11074 }
11075
11076 return false;
11077}
11078
11079/// Determine whether two declarations are "equivalent" for the purposes of
11080/// name lookup and overload resolution. This applies when the same internal/no
11081/// linkage entity is defined by two modules (probably by textually including
11082/// the same header). In such a case, we don't consider the declarations to
11083/// declare the same entity, but we also don't want lookups with both
11084/// declarations visible to be ambiguous in some cases (this happens when using
11085/// a modularized libstdc++).
11087 const NamedDecl *B) {
11088 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11089 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11090 if (!VA || !VB)
11091 return false;
11092
11093 // The declarations must be declaring the same name as an internal linkage
11094 // entity in different modules.
11095 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11096 VB->getDeclContext()->getRedeclContext()) ||
11097 getOwningModule(VA) == getOwningModule(VB) ||
11098 VA->isExternallyVisible() || VB->isExternallyVisible())
11099 return false;
11100
11101 // Check that the declarations appear to be equivalent.
11102 //
11103 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11104 // For constants and functions, we should check the initializer or body is
11105 // the same. For non-constant variables, we shouldn't allow it at all.
11106 if (Context.hasSameType(VA->getType(), VB->getType()))
11107 return true;
11108
11109 // Enum constants within unnamed enumerations will have different types, but
11110 // may still be similar enough to be interchangeable for our purposes.
11111 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11112 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11113 // Only handle anonymous enums. If the enumerations were named and
11114 // equivalent, they would have been merged to the same type.
11115 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11116 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11117 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11118 !Context.hasSameType(EnumA->getIntegerType(),
11119 EnumB->getIntegerType()))
11120 return false;
11121 // Allow this only if the value is the same for both enumerators.
11122 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11123 }
11124 }
11125
11126 // Nothing else is sufficiently similar.
11127 return false;
11128}
11129
11132 assert(D && "Unknown declaration");
11133 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11134
11135 Module *M = getOwningModule(D);
11136 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11137 << !M << (M ? M->getFullModuleName() : "");
11138
11139 for (auto *E : Equiv) {
11140 Module *M = getOwningModule(E);
11141 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11142 << !M << (M ? M->getFullModuleName() : "");
11143 }
11144}
11145
11148 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11150 static_cast<CNSInfo *>(DeductionFailure.Data)
11151 ->Satisfaction.ContainsErrors;
11152}
11153
11156 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11157 bool PartialOverloading, bool AllowExplicit,
11159 bool AggregateCandidateDeduction) {
11160
11161 auto *C =
11162 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11163
11166 /*AllowObjCConversionOnExplicit=*/false,
11167 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11168 PartialOverloading, AggregateCandidateDeduction},
11170 FoundDecl,
11171 Args,
11172 IsADLCandidate,
11173 PO};
11174
11175 HasDeferredTemplateConstructors |=
11176 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11177}
11178
11180 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11181 CXXRecordDecl *ActingContext, QualType ObjectType,
11182 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11183 bool SuppressUserConversions, bool PartialOverloading,
11185
11186 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11187
11188 auto *C =
11189 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11190
11193 /*AllowObjCConversionOnExplicit=*/false,
11194 /*AllowResultConversion=*/false,
11195 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11196 /*AggregateCandidateDeduction=*/false},
11197 MethodTmpl,
11198 FoundDecl,
11199 Args,
11200 ActingContext,
11201 ObjectClassification,
11202 ObjectType,
11203 PO};
11204}
11205
11208 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11209 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11210 bool AllowResultConversion) {
11211
11212 auto *C =
11213 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11214
11217 AllowObjCConversionOnExplicit, AllowResultConversion,
11218 /*AllowExplicit=*/false,
11219 /*SuppressUserConversions=*/false,
11220 /*PartialOverloading*/ false,
11221 /*AggregateCandidateDeduction=*/false},
11223 FoundDecl,
11224 ActingContext,
11225 From,
11226 ToType};
11227}
11228
11229static void
11232
11234 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11235 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11236 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11237}
11238
11239static void
11243 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11244 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11245 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11246 C.AggregateCandidateDeduction);
11247}
11248
11249static void
11253 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11254 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11255 C.AllowResultConversion);
11256}
11257
11259 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11260 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11261 while (Cand) {
11262 switch (Cand->Kind) {
11265 S, *this,
11266 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11267 break;
11270 S, *this,
11271 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11272 break;
11275 S, *this,
11276 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11277 break;
11278 }
11279 Cand = Cand->Next;
11280 }
11281 FirstDeferredCandidate = nullptr;
11282 DeferredCandidatesCount = 0;
11283}
11284
11286OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11287 Best->Best = true;
11288 if (Best->Function && Best->Function->isDeleted())
11289 return OR_Deleted;
11290 return OR_Success;
11291}
11292
11293void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11295 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11296 // are accepted by both clang and NVCC. However, during a particular
11297 // compilation mode only one call variant is viable. We need to
11298 // exclude non-viable overload candidates from consideration based
11299 // only on their host/device attributes. Specifically, if one
11300 // candidate call is WrongSide and the other is SameSide, we ignore
11301 // the WrongSide candidate.
11302 // We only need to remove wrong-sided candidates here if
11303 // -fgpu-exclude-wrong-side-overloads is off. When
11304 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11305 // uniformly in isBetterOverloadCandidate.
11306 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11307 return;
11308 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11309
11310 bool ContainsSameSideCandidate =
11311 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11312 // Check viable function only.
11313 return Cand->Viable && Cand->Function &&
11314 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11316 });
11317
11318 if (!ContainsSameSideCandidate)
11319 return;
11320
11321 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11322 // Check viable function only to avoid unnecessary data copying/moving.
11323 return Cand->Viable && Cand->Function &&
11324 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11326 };
11327 llvm::erase_if(Candidates, IsWrongSideCandidate);
11328}
11329
11330/// Computes the best viable function (C++ 13.3.3)
11331/// within an overload candidate set.
11332///
11333/// \param Loc The location of the function name (or operator symbol) for
11334/// which overload resolution occurs.
11335///
11336/// \param Best If overload resolution was successful or found a deleted
11337/// function, \p Best points to the candidate function found.
11338///
11339/// \returns The result of overload resolution.
11341 SourceLocation Loc,
11342 iterator &Best) {
11343
11345 DeferredCandidatesCount == 0) &&
11346 "Unexpected deferred template candidates");
11347
11348 bool TwoPhaseResolution =
11349 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11350
11351 if (TwoPhaseResolution) {
11352 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11353 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11354 if (!(HasDeferredTemplateConstructors &&
11355 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11356 return Res;
11357 }
11358 }
11359
11361 return BestViableFunctionImpl(S, Loc, Best);
11362}
11363
11364OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11366
11368 Candidates.reserve(this->Candidates.size());
11369 std::transform(this->Candidates.begin(), this->Candidates.end(),
11370 std::back_inserter(Candidates),
11371 [](OverloadCandidate &Cand) { return &Cand; });
11372
11373 if (S.getLangOpts().CUDA)
11374 CudaExcludeWrongSideCandidates(S, Candidates);
11375
11376 Best = end();
11377 for (auto *Cand : Candidates) {
11378 Cand->Best = false;
11379 if (Cand->Viable) {
11380 if (Best == end() ||
11381 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11382 Best = Cand;
11383 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11384 // This candidate has constraint that we were unable to evaluate because
11385 // it referenced an expression that contained an error. Rather than fall
11386 // back onto a potentially unintended candidate (made worse by
11387 // subsuming constraints), treat this as 'no viable candidate'.
11388 Best = end();
11389 return OR_No_Viable_Function;
11390 }
11391 }
11392
11393 // If we didn't find any viable functions, abort.
11394 if (Best == end())
11395 return OR_No_Viable_Function;
11396
11397 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11398 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11399 PendingBest.push_back(&*Best);
11400 Best->Best = true;
11401
11402 // Make sure that this function is better than every other viable
11403 // function. If not, we have an ambiguity.
11404 while (!PendingBest.empty()) {
11405 auto *Curr = PendingBest.pop_back_val();
11406 for (auto *Cand : Candidates) {
11407 if (Cand->Viable && !Cand->Best &&
11408 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11409 PendingBest.push_back(Cand);
11410 Cand->Best = true;
11411
11413 Curr->Function))
11414 EquivalentCands.push_back(Cand->Function);
11415 else
11416 Best = end();
11417 }
11418 }
11419 }
11420
11421 if (Best == end())
11422 return OR_Ambiguous;
11423
11424 OverloadingResult R = ResultForBestCandidate(Best);
11425
11426 if (!EquivalentCands.empty())
11428 EquivalentCands);
11429 return R;
11430}
11431
11432namespace {
11433
11434enum OverloadCandidateKind {
11435 oc_function,
11436 oc_method,
11437 oc_reversed_binary_operator,
11438 oc_constructor,
11439 oc_implicit_default_constructor,
11440 oc_implicit_copy_constructor,
11441 oc_implicit_move_constructor,
11442 oc_implicit_copy_assignment,
11443 oc_implicit_move_assignment,
11444 oc_implicit_equality_comparison,
11445 oc_inherited_constructor
11446};
11447
11448enum OverloadCandidateSelect {
11449 ocs_non_template,
11450 ocs_template,
11451 ocs_described_template,
11452};
11453
11454static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11455ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11456 const FunctionDecl *Fn,
11458 std::string &Description) {
11459
11460 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11461 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11462 isTemplate = true;
11463 Description = S.getTemplateArgumentBindingsText(
11464 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11465 }
11466
11467 OverloadCandidateSelect Select = [&]() {
11468 if (!Description.empty())
11469 return ocs_described_template;
11470 return isTemplate ? ocs_template : ocs_non_template;
11471 }();
11472
11473 OverloadCandidateKind Kind = [&]() {
11474 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11475 return oc_implicit_equality_comparison;
11476
11477 if (CRK & CRK_Reversed)
11478 return oc_reversed_binary_operator;
11479
11480 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11481 if (!Ctor->isImplicit()) {
11483 return oc_inherited_constructor;
11484 else
11485 return oc_constructor;
11486 }
11487
11488 if (Ctor->isDefaultConstructor())
11489 return oc_implicit_default_constructor;
11490
11491 if (Ctor->isMoveConstructor())
11492 return oc_implicit_move_constructor;
11493
11494 assert(Ctor->isCopyConstructor() &&
11495 "unexpected sort of implicit constructor");
11496 return oc_implicit_copy_constructor;
11497 }
11498
11499 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11500 // This actually gets spelled 'candidate function' for now, but
11501 // it doesn't hurt to split it out.
11502 if (!Meth->isImplicit())
11503 return oc_method;
11504
11505 if (Meth->isMoveAssignmentOperator())
11506 return oc_implicit_move_assignment;
11507
11508 if (Meth->isCopyAssignmentOperator())
11509 return oc_implicit_copy_assignment;
11510
11511 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11512 return oc_method;
11513 }
11514
11515 return oc_function;
11516 }();
11517
11518 return std::make_pair(Kind, Select);
11519}
11520
11521void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11522 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11523 // set.
11524 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11525 S.Diag(FoundDecl->getLocation(),
11526 diag::note_ovl_candidate_inherited_constructor)
11527 << Shadow->getNominatedBaseClass();
11528}
11529
11530} // end anonymous namespace
11531
11533 const FunctionDecl *FD) {
11534 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11535 bool AlwaysTrue;
11536 if (EnableIf->getCond()->isValueDependent() ||
11537 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11538 return false;
11539 if (!AlwaysTrue)
11540 return false;
11541 }
11542 return true;
11543}
11544
11545/// Returns true if we can take the address of the function.
11546///
11547/// \param Complain - If true, we'll emit a diagnostic
11548/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11549/// we in overload resolution?
11550/// \param Loc - The location of the statement we're complaining about. Ignored
11551/// if we're not complaining, or if we're in overload resolution.
11553 bool Complain,
11554 bool InOverloadResolution,
11555 SourceLocation Loc) {
11556 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11557 if (Complain) {
11558 if (InOverloadResolution)
11559 S.Diag(FD->getBeginLoc(),
11560 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11561 else
11562 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11563 }
11564 return false;
11565 }
11566
11567 if (FD->getTrailingRequiresClause()) {
11568 ConstraintSatisfaction Satisfaction;
11569 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11570 return false;
11571 if (!Satisfaction.IsSatisfied) {
11572 if (Complain) {
11573 if (InOverloadResolution) {
11574 SmallString<128> TemplateArgString;
11575 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11576 TemplateArgString += " ";
11577 TemplateArgString += S.getTemplateArgumentBindingsText(
11578 FunTmpl->getTemplateParameters(),
11580 }
11581
11582 S.Diag(FD->getBeginLoc(),
11583 diag::note_ovl_candidate_unsatisfied_constraints)
11584 << TemplateArgString;
11585 } else
11586 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11587 << FD;
11588 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11589 }
11590 return false;
11591 }
11592 }
11593
11594 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11595 return P->hasAttr<PassObjectSizeAttr>();
11596 });
11597 if (I == FD->param_end())
11598 return true;
11599
11600 if (Complain) {
11601 // Add one to ParamNo because it's user-facing
11602 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11603 if (InOverloadResolution)
11604 S.Diag(FD->getLocation(),
11605 diag::note_ovl_candidate_has_pass_object_size_params)
11606 << ParamNo;
11607 else
11608 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11609 << FD << ParamNo;
11610 }
11611 return false;
11612}
11613
11615 const FunctionDecl *FD) {
11616 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11617 /*InOverloadResolution=*/true,
11618 /*Loc=*/SourceLocation());
11619}
11620
11622 bool Complain,
11623 SourceLocation Loc) {
11624 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11625 /*InOverloadResolution=*/false,
11626 Loc);
11627}
11628
11629// Don't print candidates other than the one that matches the calling
11630// convention of the call operator, since that is guaranteed to exist.
11632 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11633
11634 if (!ConvD)
11635 return false;
11636 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11637 if (!RD->isLambda())
11638 return false;
11639
11640 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11641 CallingConv CallOpCC =
11642 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11643 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11644 CallingConv ConvToCC =
11645 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11646
11647 return ConvToCC != CallOpCC;
11648}
11649
11650// Notes the location of an overload candidate.
11652 OverloadCandidateRewriteKind RewriteKind,
11653 QualType DestType, bool TakingAddress) {
11654 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11655 return;
11656 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11657 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11658 return;
11659 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11660 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11661 return;
11663 return;
11664
11665 std::string FnDesc;
11666 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11667 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11668 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11669 << (unsigned)KSPair.first << (unsigned)KSPair.second
11670 << Fn << FnDesc;
11671
11672 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11673 Diag(Fn->getLocation(), PD);
11674 MaybeEmitInheritedConstructorNote(*this, Found);
11675}
11676
11677static void
11679 // Perhaps the ambiguity was caused by two atomic constraints that are
11680 // 'identical' but not equivalent:
11681 //
11682 // void foo() requires (sizeof(T) > 4) { } // #1
11683 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11684 //
11685 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11686 // #2 to subsume #1, but these constraint are not considered equivalent
11687 // according to the subsumption rules because they are not the same
11688 // source-level construct. This behavior is quite confusing and we should try
11689 // to help the user figure out what happened.
11690
11691 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11692 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11693 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11694 if (!I->Function)
11695 continue;
11697 if (auto *Template = I->Function->getPrimaryTemplate())
11698 Template->getAssociatedConstraints(AC);
11699 else
11700 I->Function->getAssociatedConstraints(AC);
11701 if (AC.empty())
11702 continue;
11703 if (FirstCand == nullptr) {
11704 FirstCand = I->Function;
11705 FirstAC = AC;
11706 } else if (SecondCand == nullptr) {
11707 SecondCand = I->Function;
11708 SecondAC = AC;
11709 } else {
11710 // We have more than one pair of constrained functions - this check is
11711 // expensive and we'd rather not try to diagnose it.
11712 return;
11713 }
11714 }
11715 if (!SecondCand)
11716 return;
11717 // The diagnostic can only happen if there are associated constraints on
11718 // both sides (there needs to be some identical atomic constraint).
11719 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11720 SecondCand, SecondAC))
11721 // Just show the user one diagnostic, they'll probably figure it out
11722 // from here.
11723 return;
11724}
11725
11726// Notes the location of all overload candidates designated through
11727// OverloadedExpr
11728void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11729 bool TakingAddress) {
11730 assert(OverloadedExpr->getType() == Context.OverloadTy);
11731
11732 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11733 OverloadExpr *OvlExpr = Ovl.Expression;
11734
11735 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11736 IEnd = OvlExpr->decls_end();
11737 I != IEnd; ++I) {
11738 if (FunctionTemplateDecl *FunTmpl =
11739 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11740 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11741 TakingAddress);
11742 } else if (FunctionDecl *Fun
11743 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11744 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11745 }
11746 }
11747}
11748
11749/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11750/// "lead" diagnostic; it will be given two arguments, the source and
11751/// target types of the conversion.
11753 Sema &S,
11754 SourceLocation CaretLoc,
11755 const PartialDiagnostic &PDiag) const {
11756 S.Diag(CaretLoc, PDiag)
11757 << Ambiguous.getFromType() << Ambiguous.getToType();
11758 unsigned CandsShown = 0;
11760 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11761 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11762 break;
11763 ++CandsShown;
11764 S.NoteOverloadCandidate(I->first, I->second);
11765 }
11766 S.Diags.overloadCandidatesShown(CandsShown);
11767 if (I != E)
11768 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11769}
11770
11772 unsigned I, bool TakingCandidateAddress) {
11773 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11774 assert(Conv.isBad());
11775 assert(Cand->Function && "for now, candidate must be a function");
11776 FunctionDecl *Fn = Cand->Function;
11777
11778 // There's a conversion slot for the object argument if this is a
11779 // non-constructor method. Note that 'I' corresponds the
11780 // conversion-slot index.
11781 bool isObjectArgument = false;
11782 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11784 if (I == 0)
11785 isObjectArgument = true;
11786 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11787 I--;
11788 }
11789
11790 std::string FnDesc;
11791 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11792 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11793 FnDesc);
11794
11795 Expr *FromExpr = Conv.Bad.FromExpr;
11796 QualType FromTy = Conv.Bad.getFromType();
11797 QualType ToTy = Conv.Bad.getToType();
11798 SourceRange ToParamRange;
11799
11800 // FIXME: In presence of parameter packs we can't determine parameter range
11801 // reliably, as we don't have access to instantiation.
11802 bool HasParamPack =
11803 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11804 return Parm->isParameterPack();
11805 });
11806 if (!isObjectArgument && !HasParamPack)
11807 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11808
11809 if (FromTy == S.Context.OverloadTy) {
11810 assert(FromExpr && "overload set argument came from implicit argument?");
11811 Expr *E = FromExpr->IgnoreParens();
11812 if (isa<UnaryOperator>(E))
11813 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11814 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11815
11816 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11817 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11818 << ToParamRange << ToTy << Name << I + 1;
11819 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11820 return;
11821 }
11822
11823 // Do some hand-waving analysis to see if the non-viability is due
11824 // to a qualifier mismatch.
11825 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11826 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11827 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11828 CToTy = RT->getPointeeType();
11829 else {
11830 // TODO: detect and diagnose the full richness of const mismatches.
11831 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11832 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11833 CFromTy = FromPT->getPointeeType();
11834 CToTy = ToPT->getPointeeType();
11835 }
11836 }
11837
11838 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11839 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11840 Qualifiers FromQs = CFromTy.getQualifiers();
11841 Qualifiers ToQs = CToTy.getQualifiers();
11842
11843 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11844 if (isObjectArgument)
11845 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11846 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11847 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11848 else
11849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11850 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11851 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11852 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11853 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11854 return;
11855 }
11856
11857 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11858 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11859 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11860 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11861 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11862 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11863 return;
11864 }
11865
11866 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11867 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11868 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11869 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11870 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11871 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11872 return;
11873 }
11874
11875 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11876 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11877 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11878 << FromTy << !!FromQs.getPointerAuth()
11879 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11880 << ToQs.getPointerAuth().getAsString() << I + 1
11881 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11882 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11883 return;
11884 }
11885
11886 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11887 assert(CVR && "expected qualifiers mismatch");
11888
11889 if (isObjectArgument) {
11890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11891 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11892 << FromTy << (CVR - 1);
11893 } else {
11894 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11895 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11896 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11897 }
11898 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11899 return;
11900 }
11901
11904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11905 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11906 << (unsigned)isObjectArgument << I + 1
11908 << ToParamRange;
11909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11910 return;
11911 }
11912
11913 // Special diagnostic for failure to convert an initializer list, since
11914 // telling the user that it has type void is not useful.
11915 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11917 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11918 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11921 ? 2
11922 : 0);
11923 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11924 return;
11925 }
11926
11927 // Diagnose references or pointers to incomplete types differently,
11928 // since it's far from impossible that the incompleteness triggered
11929 // the failure.
11930 QualType TempFromTy = FromTy.getNonReferenceType();
11931 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11932 TempFromTy = PTy->getPointeeType();
11933 if (TempFromTy->isIncompleteType()) {
11934 // Emit the generic diagnostic and, optionally, add the hints to it.
11935 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11936 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11937 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11938 << (unsigned)(Cand->Fix.Kind);
11939
11940 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11941 return;
11942 }
11943
11944 // Diagnose base -> derived pointer conversions.
11945 unsigned BaseToDerivedConversion = 0;
11946 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11947 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11948 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11949 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11950 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11951 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11952 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11953 FromPtrTy->getPointeeType()))
11954 BaseToDerivedConversion = 1;
11955 }
11956 } else if (const ObjCObjectPointerType *FromPtrTy
11957 = FromTy->getAs<ObjCObjectPointerType>()) {
11958 if (const ObjCObjectPointerType *ToPtrTy
11959 = ToTy->getAs<ObjCObjectPointerType>())
11960 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11961 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11962 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11963 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11964 FromIface->isSuperClassOf(ToIface))
11965 BaseToDerivedConversion = 2;
11966 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11967 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11968 S.getASTContext()) &&
11969 !FromTy->isIncompleteType() &&
11970 !ToRefTy->getPointeeType()->isIncompleteType() &&
11971 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11972 BaseToDerivedConversion = 3;
11973 }
11974 }
11975
11976 if (BaseToDerivedConversion) {
11977 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11978 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11979 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11980 << I + 1;
11981 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11982 return;
11983 }
11984
11985 if (isa<ObjCObjectPointerType>(CFromTy) &&
11986 isa<PointerType>(CToTy)) {
11987 Qualifiers FromQs = CFromTy.getQualifiers();
11988 Qualifiers ToQs = CToTy.getQualifiers();
11989 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11990 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11991 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11992 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11993 << I + 1;
11994 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11995 return;
11996 }
11997 }
11998
11999 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12000 return;
12001
12002 // Emit the generic diagnostic and, optionally, add the hints to it.
12003 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12004 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12005 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12006 << (unsigned)(Cand->Fix.Kind);
12007
12008 // Check that location of Fn is not in system header.
12009 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12010 // If we can fix the conversion, suggest the FixIts.
12011 for (const FixItHint &HI : Cand->Fix.Hints)
12012 FDiag << HI;
12013 }
12014
12015 S.Diag(Fn->getLocation(), FDiag);
12016
12017 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12018}
12019
12020/// Additional arity mismatch diagnosis specific to a function overload
12021/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12022/// over a candidate in any candidate set.
12024 unsigned NumArgs, bool IsAddressOf = false) {
12025 assert(Cand->Function && "Candidate is required to be a function.");
12026 FunctionDecl *Fn = Cand->Function;
12027 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12028 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12029
12030 // With invalid overloaded operators, it's possible that we think we
12031 // have an arity mismatch when in fact it looks like we have the
12032 // right number of arguments, because only overloaded operators have
12033 // the weird behavior of overloading member and non-member functions.
12034 // Just don't report anything.
12035 if (Fn->isInvalidDecl() &&
12036 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12037 return true;
12038
12039 if (NumArgs < MinParams) {
12040 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12042 Cand->DeductionFailure.getResult() ==
12044 } else {
12045 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12047 Cand->DeductionFailure.getResult() ==
12049 }
12050
12051 return false;
12052}
12053
12054/// General arity mismatch diagnosis over a candidate in a candidate set.
12056 unsigned NumFormalArgs,
12057 bool IsAddressOf = false) {
12058 assert(isa<FunctionDecl>(D) &&
12059 "The templated declaration should at least be a function"
12060 " when diagnosing bad template argument deduction due to too many"
12061 " or too few arguments");
12062
12064
12065 // TODO: treat calls to a missing default constructor as a special case
12066 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12067 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12068 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12069
12070 // at least / at most / exactly
12071 bool HasExplicitObjectParam =
12072 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12073
12074 unsigned ParamCount =
12075 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12076 unsigned mode, modeCount;
12077
12078 if (NumFormalArgs < MinParams) {
12079 if (MinParams != ParamCount || FnTy->isVariadic() ||
12080 FnTy->isTemplateVariadic())
12081 mode = 0; // "at least"
12082 else
12083 mode = 2; // "exactly"
12084 modeCount = MinParams;
12085 } else {
12086 if (MinParams != ParamCount)
12087 mode = 1; // "at most"
12088 else
12089 mode = 2; // "exactly"
12090 modeCount = ParamCount;
12091 }
12092
12093 std::string Description;
12094 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12095 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12096
12097 if (modeCount == 1 && !IsAddressOf &&
12098 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12100 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12101 << Description << mode
12102 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12103 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12104 else
12105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12106 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12107 << Description << mode << modeCount << NumFormalArgs
12108 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12109
12110 MaybeEmitInheritedConstructorNote(S, Found);
12111}
12112
12113/// Arity mismatch diagnosis specific to a function overload candidate.
12115 unsigned NumFormalArgs) {
12116 assert(Cand->Function && "Candidate must be a function");
12117 FunctionDecl *Fn = Cand->Function;
12118 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12119 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12120 Cand->TookAddressOfOverload);
12121}
12122
12124 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12125 return TD;
12126 llvm_unreachable("Unsupported: Getting the described template declaration"
12127 " for bad deduction diagnosis");
12128}
12129
12130/// Diagnose a failed template-argument deduction.
12131static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12132 DeductionFailureInfo &DeductionFailure,
12133 unsigned NumArgs,
12134 bool TakingCandidateAddress) {
12135 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12136 NamedDecl *ParamD;
12137 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12138 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12139 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12140 switch (DeductionFailure.getResult()) {
12142 llvm_unreachable(
12143 "TemplateDeductionResult::Success while diagnosing bad deduction");
12145 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12146 "while diagnosing bad deduction");
12149 return;
12150
12152 assert(ParamD && "no parameter found for incomplete deduction result");
12153 S.Diag(Templated->getLocation(),
12154 diag::note_ovl_candidate_incomplete_deduction)
12155 << ParamD->getDeclName();
12156 MaybeEmitInheritedConstructorNote(S, Found);
12157 return;
12158 }
12159
12161 assert(ParamD && "no parameter found for incomplete deduction result");
12162 S.Diag(Templated->getLocation(),
12163 diag::note_ovl_candidate_incomplete_deduction_pack)
12164 << ParamD->getDeclName()
12165 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12166 << *DeductionFailure.getFirstArg();
12167 MaybeEmitInheritedConstructorNote(S, Found);
12168 return;
12169 }
12170
12172 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12174
12175 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12176
12177 // Param will have been canonicalized, but it should just be a
12178 // qualified version of ParamD, so move the qualifiers to that.
12180 Qs.strip(Param);
12181 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12182 assert(S.Context.hasSameType(Param, NonCanonParam));
12183
12184 // Arg has also been canonicalized, but there's nothing we can do
12185 // about that. It also doesn't matter as much, because it won't
12186 // have any template parameters in it (because deduction isn't
12187 // done on dependent types).
12188 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12189
12190 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12191 << ParamD->getDeclName() << Arg << NonCanonParam;
12192 MaybeEmitInheritedConstructorNote(S, Found);
12193 return;
12194 }
12195
12197 assert(ParamD && "no parameter found for inconsistent deduction result");
12198 int which = 0;
12199 if (isa<TemplateTypeParmDecl>(ParamD))
12200 which = 0;
12201 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12202 // Deduction might have failed because we deduced arguments of two
12203 // different types for a non-type template parameter.
12204 // FIXME: Use a different TDK value for this.
12205 QualType T1 =
12206 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12207 QualType T2 =
12208 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12209 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12210 S.Diag(Templated->getLocation(),
12211 diag::note_ovl_candidate_inconsistent_deduction_types)
12212 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12213 << *DeductionFailure.getSecondArg() << T2;
12214 MaybeEmitInheritedConstructorNote(S, Found);
12215 return;
12216 }
12217
12218 which = 1;
12219 } else {
12220 which = 2;
12221 }
12222
12223 // Tweak the diagnostic if the problem is that we deduced packs of
12224 // different arities. We'll print the actual packs anyway in case that
12225 // includes additional useful information.
12226 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12227 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12228 DeductionFailure.getFirstArg()->pack_size() !=
12229 DeductionFailure.getSecondArg()->pack_size()) {
12230 which = 3;
12231 }
12232
12233 S.Diag(Templated->getLocation(),
12234 diag::note_ovl_candidate_inconsistent_deduction)
12235 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12236 << *DeductionFailure.getSecondArg();
12237 MaybeEmitInheritedConstructorNote(S, Found);
12238 return;
12239 }
12240
12242 assert(ParamD && "no parameter found for invalid explicit arguments");
12243 if (ParamD->getDeclName())
12244 S.Diag(Templated->getLocation(),
12245 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12246 << ParamD->getDeclName();
12247 else {
12248 int index = 0;
12249 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12250 index = TTP->getIndex();
12251 else if (NonTypeTemplateParmDecl *NTTP
12252 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12253 index = NTTP->getIndex();
12254 else
12255 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12256 S.Diag(Templated->getLocation(),
12257 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12258 << (index + 1);
12259 }
12260 MaybeEmitInheritedConstructorNote(S, Found);
12261 return;
12262
12264 // Format the template argument list into the argument string.
12265 SmallString<128> TemplateArgString;
12266 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12267 TemplateArgString = " ";
12268 TemplateArgString += S.getTemplateArgumentBindingsText(
12269 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12270 if (TemplateArgString.size() == 1)
12271 TemplateArgString.clear();
12272 S.Diag(Templated->getLocation(),
12273 diag::note_ovl_candidate_unsatisfied_constraints)
12274 << TemplateArgString;
12275
12277 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12278 return;
12279 }
12282 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12283 return;
12284
12286 S.Diag(Templated->getLocation(),
12287 diag::note_ovl_candidate_instantiation_depth);
12288 MaybeEmitInheritedConstructorNote(S, Found);
12289 return;
12290
12292 // Format the template argument list into the argument string.
12293 SmallString<128> TemplateArgString;
12294 if (TemplateArgumentList *Args =
12295 DeductionFailure.getTemplateArgumentList()) {
12296 TemplateArgString = " ";
12297 TemplateArgString += S.getTemplateArgumentBindingsText(
12298 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12299 if (TemplateArgString.size() == 1)
12300 TemplateArgString.clear();
12301 }
12302
12303 // If this candidate was disabled by enable_if, say so.
12304 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12305 if (PDiag && PDiag->second.getDiagID() ==
12306 diag::err_typename_nested_not_found_enable_if) {
12307 // FIXME: Use the source range of the condition, and the fully-qualified
12308 // name of the enable_if template. These are both present in PDiag.
12309 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12310 << "'enable_if'" << TemplateArgString;
12311 return;
12312 }
12313
12314 // We found a specific requirement that disabled the enable_if.
12315 if (PDiag && PDiag->second.getDiagID() ==
12316 diag::err_typename_nested_not_found_requirement) {
12317 S.Diag(Templated->getLocation(),
12318 diag::note_ovl_candidate_disabled_by_requirement)
12319 << PDiag->second.getStringArg(0) << TemplateArgString;
12320 return;
12321 }
12322
12323 // Format the SFINAE diagnostic into the argument string.
12324 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12325 // formatted message in another diagnostic.
12326 SmallString<128> SFINAEArgString;
12327 SourceRange R;
12328 if (PDiag) {
12329 SFINAEArgString = ": ";
12330 R = SourceRange(PDiag->first, PDiag->first);
12331 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12332 }
12333
12334 S.Diag(Templated->getLocation(),
12335 diag::note_ovl_candidate_substitution_failure)
12336 << TemplateArgString << SFINAEArgString << R;
12337 MaybeEmitInheritedConstructorNote(S, Found);
12338 return;
12339 }
12340
12343 // Format the template argument list into the argument string.
12344 SmallString<128> TemplateArgString;
12345 if (TemplateArgumentList *Args =
12346 DeductionFailure.getTemplateArgumentList()) {
12347 TemplateArgString = " ";
12348 TemplateArgString += S.getTemplateArgumentBindingsText(
12349 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12350 if (TemplateArgString.size() == 1)
12351 TemplateArgString.clear();
12352 }
12353
12354 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12355 << (*DeductionFailure.getCallArgIndex() + 1)
12356 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12357 << TemplateArgString
12358 << (DeductionFailure.getResult() ==
12360 break;
12361 }
12362
12364 // FIXME: Provide a source location to indicate what we couldn't match.
12365 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12366 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12367 if (FirstTA.getKind() == TemplateArgument::Template &&
12368 SecondTA.getKind() == TemplateArgument::Template) {
12369 TemplateName FirstTN = FirstTA.getAsTemplate();
12370 TemplateName SecondTN = SecondTA.getAsTemplate();
12371 if (FirstTN.getKind() == TemplateName::Template &&
12372 SecondTN.getKind() == TemplateName::Template) {
12373 if (FirstTN.getAsTemplateDecl()->getName() ==
12374 SecondTN.getAsTemplateDecl()->getName()) {
12375 // FIXME: This fixes a bad diagnostic where both templates are named
12376 // the same. This particular case is a bit difficult since:
12377 // 1) It is passed as a string to the diagnostic printer.
12378 // 2) The diagnostic printer only attempts to find a better
12379 // name for types, not decls.
12380 // Ideally, this should folded into the diagnostic printer.
12381 S.Diag(Templated->getLocation(),
12382 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12383 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12384 return;
12385 }
12386 }
12387 }
12388
12389 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12391 return;
12392
12393 // FIXME: For generic lambda parameters, check if the function is a lambda
12394 // call operator, and if so, emit a prettier and more informative
12395 // diagnostic that mentions 'auto' and lambda in addition to
12396 // (or instead of?) the canonical template type parameters.
12397 S.Diag(Templated->getLocation(),
12398 diag::note_ovl_candidate_non_deduced_mismatch)
12399 << FirstTA << SecondTA;
12400 return;
12401 }
12402 // TODO: diagnose these individually, then kill off
12403 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12405 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12406 MaybeEmitInheritedConstructorNote(S, Found);
12407 return;
12409 S.Diag(Templated->getLocation(),
12410 diag::note_cuda_ovl_candidate_target_mismatch);
12411 return;
12412 }
12413}
12414
12415/// Diagnose a failed template-argument deduction, for function calls.
12417 unsigned NumArgs,
12418 bool TakingCandidateAddress) {
12419 assert(Cand->Function && "Candidate must be a function");
12420 FunctionDecl *Fn = Cand->Function;
12424 if (CheckArityMismatch(S, Cand, NumArgs))
12425 return;
12426 }
12427 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12428 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12429}
12430
12431/// CUDA: diagnose an invalid call across targets.
12433 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12434 assert(Cand->Function && "Candidate must be a Function.");
12435 FunctionDecl *Callee = Cand->Function;
12436
12437 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12438 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12439
12440 std::string FnDesc;
12441 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12442 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12443 Cand->getRewriteKind(), FnDesc);
12444
12445 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12446 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12447 << FnDesc /* Ignored */
12448 << CalleeTarget << CallerTarget;
12449
12450 // This could be an implicit constructor for which we could not infer the
12451 // target due to a collsion. Diagnose that case.
12452 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12453 if (Meth != nullptr && Meth->isImplicit()) {
12454 CXXRecordDecl *ParentClass = Meth->getParent();
12456
12457 switch (FnKindPair.first) {
12458 default:
12459 return;
12460 case oc_implicit_default_constructor:
12462 break;
12463 case oc_implicit_copy_constructor:
12465 break;
12466 case oc_implicit_move_constructor:
12468 break;
12469 case oc_implicit_copy_assignment:
12471 break;
12472 case oc_implicit_move_assignment:
12474 break;
12475 };
12476
12477 bool ConstRHS = false;
12478 if (Meth->getNumParams()) {
12479 if (const ReferenceType *RT =
12480 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12481 ConstRHS = RT->getPointeeType().isConstQualified();
12482 }
12483 }
12484
12485 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12486 /* ConstRHS */ ConstRHS,
12487 /* Diagnose */ true);
12488 }
12489}
12490
12492 assert(Cand->Function && "Candidate must be a function");
12493 FunctionDecl *Callee = Cand->Function;
12494 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12495
12496 S.Diag(Callee->getLocation(),
12497 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12498 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12499}
12500
12502 assert(Cand->Function && "Candidate must be a function");
12503 FunctionDecl *Fn = Cand->Function;
12505 assert(ES.isExplicit() && "not an explicit candidate");
12506
12507 unsigned Kind;
12508 switch (Fn->getDeclKind()) {
12509 case Decl::Kind::CXXConstructor:
12510 Kind = 0;
12511 break;
12512 case Decl::Kind::CXXConversion:
12513 Kind = 1;
12514 break;
12515 case Decl::Kind::CXXDeductionGuide:
12516 Kind = Fn->isImplicit() ? 0 : 2;
12517 break;
12518 default:
12519 llvm_unreachable("invalid Decl");
12520 }
12521
12522 // Note the location of the first (in-class) declaration; a redeclaration
12523 // (particularly an out-of-class definition) will typically lack the
12524 // 'explicit' specifier.
12525 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12526 FunctionDecl *First = Fn->getFirstDecl();
12527 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12528 First = Pattern->getFirstDecl();
12529
12530 S.Diag(First->getLocation(),
12531 diag::note_ovl_candidate_explicit)
12532 << Kind << (ES.getExpr() ? 1 : 0)
12533 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12534}
12535
12537 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12538 if (!DG)
12539 return;
12540 TemplateDecl *OriginTemplate =
12542 // We want to always print synthesized deduction guides for type aliases.
12543 // They would retain the explicit bit of the corresponding constructor.
12544 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12545 return;
12546 std::string FunctionProto;
12547 llvm::raw_string_ostream OS(FunctionProto);
12548 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12549 if (!Template) {
12550 // This also could be an instantiation. Find out the primary template.
12551 FunctionDecl *Pattern =
12552 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12553 if (!Pattern) {
12554 // The implicit deduction guide is built on an explicit non-template
12555 // deduction guide. Currently, this might be the case only for type
12556 // aliases.
12557 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12558 // gets merged.
12559 assert(OriginTemplate->isTypeAlias() &&
12560 "Non-template implicit deduction guides are only possible for "
12561 "type aliases");
12562 DG->print(OS);
12563 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12564 << FunctionProto;
12565 return;
12566 }
12568 assert(Template && "Cannot find the associated function template of "
12569 "CXXDeductionGuideDecl?");
12570 }
12571 Template->print(OS);
12572 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12573 << FunctionProto;
12574}
12575
12576/// Generates a 'note' diagnostic for an overload candidate. We've
12577/// already generated a primary error at the call site.
12578///
12579/// It really does need to be a single diagnostic with its caret
12580/// pointed at the candidate declaration. Yes, this creates some
12581/// major challenges of technical writing. Yes, this makes pointing
12582/// out problems with specific arguments quite awkward. It's still
12583/// better than generating twenty screens of text for every failed
12584/// overload.
12585///
12586/// It would be great to be able to express per-candidate problems
12587/// more richly for those diagnostic clients that cared, but we'd
12588/// still have to be just as careful with the default diagnostics.
12589/// \param CtorDestAS Addr space of object being constructed (for ctor
12590/// candidates only).
12592 unsigned NumArgs,
12593 bool TakingCandidateAddress,
12594 LangAS CtorDestAS = LangAS::Default) {
12595 assert(Cand->Function && "Candidate must be a function");
12596 FunctionDecl *Fn = Cand->Function;
12598 return;
12599
12600 // There is no physical candidate declaration to point to for OpenCL builtins.
12601 // Except for failed conversions, the notes are identical for each candidate,
12602 // so do not generate such notes.
12603 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12605 return;
12606
12607 // Skip implicit member functions when trying to resolve
12608 // the address of a an overload set for a function pointer.
12609 if (Cand->TookAddressOfOverload &&
12610 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12611 return;
12612
12613 // Note deleted candidates, but only if they're viable.
12614 if (Cand->Viable) {
12615 if (Fn->isDeleted()) {
12616 std::string FnDesc;
12617 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12618 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12619 Cand->getRewriteKind(), FnDesc);
12620
12621 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12622 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12623 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12624 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12625 return;
12626 }
12627
12628 // We don't really have anything else to say about viable candidates.
12629 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12630 return;
12631 }
12632
12633 // If this is a synthesized deduction guide we're deducing against, add a note
12634 // for it. These deduction guides are not explicitly spelled in the source
12635 // code, so simply printing a deduction failure note mentioning synthesized
12636 // template parameters or pointing to the header of the surrounding RecordDecl
12637 // would be confusing.
12638 //
12639 // We prefer adding such notes at the end of the deduction failure because
12640 // duplicate code snippets appearing in the diagnostic would likely become
12641 // noisy.
12642 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12643
12644 switch (Cand->FailureKind) {
12647 return DiagnoseArityMismatch(S, Cand, NumArgs);
12648
12650 return DiagnoseBadDeduction(S, Cand, NumArgs,
12651 TakingCandidateAddress);
12652
12654 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12655 << (Fn->getPrimaryTemplate() ? 1 : 0);
12656 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12657 return;
12658 }
12659
12661 Qualifiers QualsForPrinting;
12662 QualsForPrinting.setAddressSpace(CtorDestAS);
12663 S.Diag(Fn->getLocation(),
12664 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12665 << QualsForPrinting;
12666 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12667 return;
12668 }
12669
12673 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12674
12676 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12677 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12678 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12679 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12680
12681 // FIXME: this currently happens when we're called from SemaInit
12682 // when user-conversion overload fails. Figure out how to handle
12683 // those conditions and diagnose them well.
12684 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12685 }
12686
12688 return DiagnoseBadTarget(S, Cand);
12689
12690 case ovl_fail_enable_if:
12691 return DiagnoseFailedEnableIfAttr(S, Cand);
12692
12693 case ovl_fail_explicit:
12694 return DiagnoseFailedExplicitSpec(S, Cand);
12695
12697 // It's generally not interesting to note copy/move constructors here.
12698 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12699 return;
12700 S.Diag(Fn->getLocation(),
12701 diag::note_ovl_candidate_inherited_constructor_slice)
12702 << (Fn->getPrimaryTemplate() ? 1 : 0)
12703 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12704 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12705 return;
12706
12708 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12709 (void)Available;
12710 assert(!Available);
12711 break;
12712 }
12714 // Do nothing, these should simply be ignored.
12715 break;
12716
12718 std::string FnDesc;
12719 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12720 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12721 Cand->getRewriteKind(), FnDesc);
12722
12723 S.Diag(Fn->getLocation(),
12724 diag::note_ovl_candidate_constraints_not_satisfied)
12725 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12726 << FnDesc /* Ignored */;
12727 ConstraintSatisfaction Satisfaction;
12728 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12729 /*ForOverloadResolution=*/true))
12730 break;
12731 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12732 }
12733 }
12734}
12735
12738 return;
12739
12740 // Desugar the type of the surrogate down to a function type,
12741 // retaining as many typedefs as possible while still showing
12742 // the function type (and, therefore, its parameter types).
12743 QualType FnType = Cand->Surrogate->getConversionType();
12744 bool isLValueReference = false;
12745 bool isRValueReference = false;
12746 bool isPointer = false;
12747 if (const LValueReferenceType *FnTypeRef =
12748 FnType->getAs<LValueReferenceType>()) {
12749 FnType = FnTypeRef->getPointeeType();
12750 isLValueReference = true;
12751 } else if (const RValueReferenceType *FnTypeRef =
12752 FnType->getAs<RValueReferenceType>()) {
12753 FnType = FnTypeRef->getPointeeType();
12754 isRValueReference = true;
12755 }
12756 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12757 FnType = FnTypePtr->getPointeeType();
12758 isPointer = true;
12759 }
12760 // Desugar down to a function type.
12761 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12762 // Reconstruct the pointer/reference as appropriate.
12763 if (isPointer) FnType = S.Context.getPointerType(FnType);
12764 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12765 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12766
12767 if (!Cand->Viable &&
12769 S.Diag(Cand->Surrogate->getLocation(),
12770 diag::note_ovl_surrogate_constraints_not_satisfied)
12771 << Cand->Surrogate;
12772 ConstraintSatisfaction Satisfaction;
12773 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12774 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12775 } else {
12776 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12777 << FnType;
12778 }
12779}
12780
12781static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12782 SourceLocation OpLoc,
12783 OverloadCandidate *Cand) {
12784 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12785 std::string TypeStr("operator");
12786 TypeStr += Opc;
12787 TypeStr += "(";
12788 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12789 if (Cand->Conversions.size() == 1) {
12790 TypeStr += ")";
12791 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12792 } else {
12793 TypeStr += ", ";
12794 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12795 TypeStr += ")";
12796 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12797 }
12798}
12799
12801 OverloadCandidate *Cand) {
12802 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12803 if (ICS.isBad()) break; // all meaningless after first invalid
12804 if (!ICS.isAmbiguous()) continue;
12805
12807 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12808 }
12809}
12810
12812 if (Cand->Function)
12813 return Cand->Function->getLocation();
12814 if (Cand->IsSurrogate)
12815 return Cand->Surrogate->getLocation();
12816 return SourceLocation();
12817}
12818
12819static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12820 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12824 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12825
12829 return 1;
12830
12833 return 2;
12834
12842 return 3;
12843
12845 return 4;
12846
12848 return 5;
12849
12852 return 6;
12853 }
12854 llvm_unreachable("Unhandled deduction result");
12855}
12856
12857namespace {
12858
12859struct CompareOverloadCandidatesForDisplay {
12860 Sema &S;
12861 SourceLocation Loc;
12862 size_t NumArgs;
12864
12865 CompareOverloadCandidatesForDisplay(
12866 Sema &S, SourceLocation Loc, size_t NArgs,
12868 : S(S), NumArgs(NArgs), CSK(CSK) {}
12869
12870 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12871 // If there are too many or too few arguments, that's the high-order bit we
12872 // want to sort by, even if the immediate failure kind was something else.
12873 if (C->FailureKind == ovl_fail_too_many_arguments ||
12874 C->FailureKind == ovl_fail_too_few_arguments)
12875 return static_cast<OverloadFailureKind>(C->FailureKind);
12876
12877 if (C->Function) {
12878 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12880 if (NumArgs < C->Function->getMinRequiredArguments())
12882 }
12883
12884 return static_cast<OverloadFailureKind>(C->FailureKind);
12885 }
12886
12887 bool operator()(const OverloadCandidate *L,
12888 const OverloadCandidate *R) {
12889 // Fast-path this check.
12890 if (L == R) return false;
12891
12892 // Order first by viability.
12893 if (L->Viable) {
12894 if (!R->Viable) return true;
12895
12896 if (int Ord = CompareConversions(*L, *R))
12897 return Ord < 0;
12898 // Use other tie breakers.
12899 } else if (R->Viable)
12900 return false;
12901
12902 assert(L->Viable == R->Viable);
12903
12904 // Criteria by which we can sort non-viable candidates:
12905 if (!L->Viable) {
12906 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12907 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12908
12909 // 1. Arity mismatches come after other candidates.
12910 if (LFailureKind == ovl_fail_too_many_arguments ||
12911 LFailureKind == ovl_fail_too_few_arguments) {
12912 if (RFailureKind == ovl_fail_too_many_arguments ||
12913 RFailureKind == ovl_fail_too_few_arguments) {
12914 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12915 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12916 if (LDist == RDist) {
12917 if (LFailureKind == RFailureKind)
12918 // Sort non-surrogates before surrogates.
12919 return !L->IsSurrogate && R->IsSurrogate;
12920 // Sort candidates requiring fewer parameters than there were
12921 // arguments given after candidates requiring more parameters
12922 // than there were arguments given.
12923 return LFailureKind == ovl_fail_too_many_arguments;
12924 }
12925 return LDist < RDist;
12926 }
12927 return false;
12928 }
12929 if (RFailureKind == ovl_fail_too_many_arguments ||
12930 RFailureKind == ovl_fail_too_few_arguments)
12931 return true;
12932
12933 // 2. Bad conversions come first and are ordered by the number
12934 // of bad conversions and quality of good conversions.
12935 if (LFailureKind == ovl_fail_bad_conversion) {
12936 if (RFailureKind != ovl_fail_bad_conversion)
12937 return true;
12938
12939 // The conversion that can be fixed with a smaller number of changes,
12940 // comes first.
12941 unsigned numLFixes = L->Fix.NumConversionsFixed;
12942 unsigned numRFixes = R->Fix.NumConversionsFixed;
12943 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12944 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12945 if (numLFixes != numRFixes) {
12946 return numLFixes < numRFixes;
12947 }
12948
12949 // If there's any ordering between the defined conversions...
12950 if (int Ord = CompareConversions(*L, *R))
12951 return Ord < 0;
12952 } else if (RFailureKind == ovl_fail_bad_conversion)
12953 return false;
12954
12955 if (LFailureKind == ovl_fail_bad_deduction) {
12956 if (RFailureKind != ovl_fail_bad_deduction)
12957 return true;
12958
12960 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12961 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12962 if (LRank != RRank)
12963 return LRank < RRank;
12964 }
12965 } else if (RFailureKind == ovl_fail_bad_deduction)
12966 return false;
12967
12968 // TODO: others?
12969 }
12970
12971 // Sort everything else by location.
12972 SourceLocation LLoc = GetLocationForCandidate(L);
12973 SourceLocation RLoc = GetLocationForCandidate(R);
12974
12975 // Put candidates without locations (e.g. builtins) at the end.
12976 if (LLoc.isValid() && RLoc.isValid())
12977 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12978 if (LLoc.isValid() && !RLoc.isValid())
12979 return true;
12980 if (RLoc.isValid() && !LLoc.isValid())
12981 return false;
12982 assert(!LLoc.isValid() && !RLoc.isValid());
12983 // For builtins and other functions without locations, fallback to the order
12984 // in which they were added into the candidate set.
12985 return L < R;
12986 }
12987
12988private:
12989 struct ConversionSignals {
12990 unsigned KindRank = 0;
12992
12993 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12994 ConversionSignals Sig;
12995 Sig.KindRank = Seq.getKindRank();
12996 if (Seq.isStandard())
12997 Sig.Rank = Seq.Standard.getRank();
12998 else if (Seq.isUserDefined())
12999 Sig.Rank = Seq.UserDefined.After.getRank();
13000 // We intend StaticObjectArgumentConversion to compare the same as
13001 // StandardConversion with ICR_ExactMatch rank.
13002 return Sig;
13003 }
13004
13005 static ConversionSignals ForObjectArgument() {
13006 // We intend StaticObjectArgumentConversion to compare the same as
13007 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13008 return {};
13009 }
13010 };
13011
13012 // Returns -1 if conversions in L are considered better.
13013 // 0 if they are considered indistinguishable.
13014 // 1 if conversions in R are better.
13015 int CompareConversions(const OverloadCandidate &L,
13016 const OverloadCandidate &R) {
13017 // We cannot use `isBetterOverloadCandidate` because it is defined
13018 // according to the C++ standard and provides a partial order, but we need
13019 // a total order as this function is used in sort.
13020 assert(L.Conversions.size() == R.Conversions.size());
13021 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13022 auto LS = L.IgnoreObjectArgument && I == 0
13023 ? ConversionSignals::ForObjectArgument()
13024 : ConversionSignals::ForSequence(L.Conversions[I]);
13025 auto RS = R.IgnoreObjectArgument
13026 ? ConversionSignals::ForObjectArgument()
13027 : ConversionSignals::ForSequence(R.Conversions[I]);
13028 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13029 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13030 ? -1
13031 : 1;
13032 }
13033 // FIXME: find a way to compare templates for being more or less
13034 // specialized that provides a strict weak ordering.
13035 return 0;
13036 }
13037};
13038}
13039
13040/// CompleteNonViableCandidate - Normally, overload resolution only
13041/// computes up to the first bad conversion. Produces the FixIt set if
13042/// possible.
13043static void
13045 ArrayRef<Expr *> Args,
13047 assert(!Cand->Viable);
13048
13049 // Don't do anything on failures other than bad conversion.
13051 return;
13052
13053 // We only want the FixIts if all the arguments can be corrected.
13054 bool Unfixable = false;
13055 // Use a implicit copy initialization to check conversion fixes.
13057
13058 // Attempt to fix the bad conversion.
13059 unsigned ConvCount = Cand->Conversions.size();
13060 for (unsigned ConvIdx =
13061 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13062 : 0);
13063 /**/; ++ConvIdx) {
13064 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13065 if (Cand->Conversions[ConvIdx].isInitialized() &&
13066 Cand->Conversions[ConvIdx].isBad()) {
13067 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13068 break;
13069 }
13070 }
13071
13072 // FIXME: this should probably be preserved from the overload
13073 // operation somehow.
13074 bool SuppressUserConversions = false;
13075
13076 unsigned ConvIdx = 0;
13077 unsigned ArgIdx = 0;
13078 ArrayRef<QualType> ParamTypes;
13079 bool Reversed = Cand->isReversed();
13080
13081 if (Cand->IsSurrogate) {
13082 QualType ConvType
13084 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13085 ConvType = ConvPtrType->getPointeeType();
13086 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13087 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13088 ConvIdx = 1;
13089 } else if (Cand->Function) {
13090 ParamTypes =
13091 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13092 if (isa<CXXMethodDecl>(Cand->Function) &&
13095 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13096 ConvIdx = 1;
13098 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13100 OO_Subscript)
13101 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13102 ArgIdx = 1;
13103 }
13104 } else {
13105 // Builtin operator.
13106 assert(ConvCount <= 3);
13107 ParamTypes = Cand->BuiltinParamTypes;
13108 }
13109
13110 // Fill in the rest of the conversions.
13111 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13112 ConvIdx != ConvCount && ArgIdx < Args.size();
13113 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13114 if (Cand->Conversions[ConvIdx].isInitialized()) {
13115 // We've already checked this conversion.
13116 } else if (ParamIdx < ParamTypes.size()) {
13117 if (ParamTypes[ParamIdx]->isDependentType())
13118 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13119 Args[ArgIdx]->getType());
13120 else {
13121 Cand->Conversions[ConvIdx] =
13122 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13123 SuppressUserConversions,
13124 /*InOverloadResolution=*/true,
13125 /*AllowObjCWritebackConversion=*/
13126 S.getLangOpts().ObjCAutoRefCount);
13127 // Store the FixIt in the candidate if it exists.
13128 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13129 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13130 }
13131 } else
13132 Cand->Conversions[ConvIdx].setEllipsis();
13133 }
13134}
13135
13138 SourceLocation OpLoc,
13139 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13140
13142
13143 // Sort the candidates by viability and position. Sorting directly would
13144 // be prohibitive, so we make a set of pointers and sort those.
13146 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13147 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13148 Cand != LastCand; ++Cand) {
13149 if (!Filter(*Cand))
13150 continue;
13151 switch (OCD) {
13152 case OCD_AllCandidates:
13153 if (!Cand->Viable) {
13154 if (!Cand->Function && !Cand->IsSurrogate) {
13155 // This a non-viable builtin candidate. We do not, in general,
13156 // want to list every possible builtin candidate.
13157 continue;
13158 }
13159 CompleteNonViableCandidate(S, Cand, Args, Kind);
13160 }
13161 break;
13162
13164 if (!Cand->Viable)
13165 continue;
13166 break;
13167
13169 if (!Cand->Best)
13170 continue;
13171 break;
13172 }
13173
13174 Cands.push_back(Cand);
13175 }
13176
13177 llvm::stable_sort(
13178 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13179
13180 return Cands;
13181}
13182
13184 SourceLocation OpLoc) {
13185 bool DeferHint = false;
13186 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13187 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13188 // host device candidates.
13189 auto WrongSidedCands =
13190 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13191 return (Cand.Viable == false &&
13193 (Cand.Function &&
13194 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13195 Cand.Function->template hasAttr<CUDADeviceAttr>());
13196 });
13197 DeferHint = !WrongSidedCands.empty();
13198 }
13199 return DeferHint;
13200}
13201
13202/// When overload resolution fails, prints diagnostic messages containing the
13203/// candidates in the candidate set.
13206 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13207 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13208
13209 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13210
13211 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13212
13213 // In WebAssembly we don't want to emit further diagnostics if a table is
13214 // passed as an argument to a function.
13215 bool NoteCands = true;
13216 for (const Expr *Arg : Args) {
13217 if (Arg->getType()->isWebAssemblyTableType())
13218 NoteCands = false;
13219 }
13220
13221 if (NoteCands)
13222 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13223
13224 if (OCD == OCD_AmbiguousCandidates)
13226 {Candidates.begin(), Candidates.end()});
13227}
13228
13231 StringRef Opc, SourceLocation OpLoc) {
13232 bool ReportedAmbiguousConversions = false;
13233
13234 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13235 unsigned CandsShown = 0;
13236 auto I = Cands.begin(), E = Cands.end();
13237 for (; I != E; ++I) {
13238 OverloadCandidate *Cand = *I;
13239
13240 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13241 ShowOverloads == Ovl_Best) {
13242 break;
13243 }
13244 ++CandsShown;
13245
13246 if (Cand->Function)
13247 NoteFunctionCandidate(S, Cand, Args.size(),
13248 Kind == CSK_AddressOfOverloadSet, DestAS);
13249 else if (Cand->IsSurrogate)
13250 NoteSurrogateCandidate(S, Cand);
13251 else {
13252 assert(Cand->Viable &&
13253 "Non-viable built-in candidates are not added to Cands.");
13254 // Generally we only see ambiguities including viable builtin
13255 // operators if overload resolution got screwed up by an
13256 // ambiguous user-defined conversion.
13257 //
13258 // FIXME: It's quite possible for different conversions to see
13259 // different ambiguities, though.
13260 if (!ReportedAmbiguousConversions) {
13261 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13262 ReportedAmbiguousConversions = true;
13263 }
13264
13265 // If this is a viable builtin, print it.
13266 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13267 }
13268 }
13269
13270 // Inform S.Diags that we've shown an overload set with N elements. This may
13271 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13272 S.Diags.overloadCandidatesShown(CandsShown);
13273
13274 if (I != E)
13275 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13276 shouldDeferDiags(S, Args, OpLoc))
13277 << int(E - I);
13278}
13279
13280static SourceLocation
13282 return Cand->Specialization ? Cand->Specialization->getLocation()
13283 : SourceLocation();
13284}
13285
13286namespace {
13287struct CompareTemplateSpecCandidatesForDisplay {
13288 Sema &S;
13289 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13290
13291 bool operator()(const TemplateSpecCandidate *L,
13292 const TemplateSpecCandidate *R) {
13293 // Fast-path this check.
13294 if (L == R)
13295 return false;
13296
13297 // Assuming that both candidates are not matches...
13298
13299 // Sort by the ranking of deduction failures.
13303
13304 // Sort everything else by location.
13305 SourceLocation LLoc = GetLocationForCandidate(L);
13306 SourceLocation RLoc = GetLocationForCandidate(R);
13307
13308 // Put candidates without locations (e.g. builtins) at the end.
13309 if (LLoc.isInvalid())
13310 return false;
13311 if (RLoc.isInvalid())
13312 return true;
13313
13314 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13315 }
13316};
13317}
13318
13319/// Diagnose a template argument deduction failure.
13320/// We are treating these failures as overload failures due to bad
13321/// deductions.
13323 bool ForTakingAddress) {
13325 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13326}
13327
13328void TemplateSpecCandidateSet::destroyCandidates() {
13329 for (iterator i = begin(), e = end(); i != e; ++i) {
13330 i->DeductionFailure.Destroy();
13331 }
13332}
13333
13335 destroyCandidates();
13336 Candidates.clear();
13337}
13338
13339/// NoteCandidates - When no template specialization match is found, prints
13340/// diagnostic messages containing the non-matching specializations that form
13341/// the candidate set.
13342/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13343/// OCD == OCD_AllCandidates and Cand->Viable == false.
13345 // Sort the candidates by position (assuming no candidate is a match).
13346 // Sorting directly would be prohibitive, so we make a set of pointers
13347 // and sort those.
13349 Cands.reserve(size());
13350 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13351 if (Cand->Specialization)
13352 Cands.push_back(Cand);
13353 // Otherwise, this is a non-matching builtin candidate. We do not,
13354 // in general, want to list every possible builtin candidate.
13355 }
13356
13357 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13358
13359 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13360 // for generalization purposes (?).
13361 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13362
13364 unsigned CandsShown = 0;
13365 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13366 TemplateSpecCandidate *Cand = *I;
13367
13368 // Set an arbitrary limit on the number of candidates we'll spam
13369 // the user with. FIXME: This limit should depend on details of the
13370 // candidate list.
13371 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13372 break;
13373 ++CandsShown;
13374
13375 assert(Cand->Specialization &&
13376 "Non-matching built-in candidates are not added to Cands.");
13377 Cand->NoteDeductionFailure(S, ForTakingAddress);
13378 }
13379
13380 if (I != E)
13381 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13382}
13383
13384// [PossiblyAFunctionType] --> [Return]
13385// NonFunctionType --> NonFunctionType
13386// R (A) --> R(A)
13387// R (*)(A) --> R (A)
13388// R (&)(A) --> R (A)
13389// R (S::*)(A) --> R (A)
13391 QualType Ret = PossiblyAFunctionType;
13392 if (const PointerType *ToTypePtr =
13393 PossiblyAFunctionType->getAs<PointerType>())
13394 Ret = ToTypePtr->getPointeeType();
13395 else if (const ReferenceType *ToTypeRef =
13396 PossiblyAFunctionType->getAs<ReferenceType>())
13397 Ret = ToTypeRef->getPointeeType();
13398 else if (const MemberPointerType *MemTypePtr =
13399 PossiblyAFunctionType->getAs<MemberPointerType>())
13400 Ret = MemTypePtr->getPointeeType();
13401 Ret =
13402 Context.getCanonicalType(Ret).getUnqualifiedType();
13403 return Ret;
13404}
13405
13407 bool Complain = true) {
13408 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13409 S.DeduceReturnType(FD, Loc, Complain))
13410 return true;
13411
13412 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13413 if (S.getLangOpts().CPlusPlus17 &&
13414 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13415 !S.ResolveExceptionSpec(Loc, FPT))
13416 return true;
13417
13418 return false;
13419}
13420
13421namespace {
13422// A helper class to help with address of function resolution
13423// - allows us to avoid passing around all those ugly parameters
13424class AddressOfFunctionResolver {
13425 Sema& S;
13426 Expr* SourceExpr;
13427 const QualType& TargetType;
13428 QualType TargetFunctionType; // Extracted function type from target type
13429
13430 bool Complain;
13431 //DeclAccessPair& ResultFunctionAccessPair;
13432 ASTContext& Context;
13433
13434 bool TargetTypeIsNonStaticMemberFunction;
13435 bool FoundNonTemplateFunction;
13436 bool StaticMemberFunctionFromBoundPointer;
13437 bool HasComplained;
13438
13439 OverloadExpr::FindResult OvlExprInfo;
13440 OverloadExpr *OvlExpr;
13441 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13442 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13443 TemplateSpecCandidateSet FailedCandidates;
13444
13445public:
13446 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13447 const QualType &TargetType, bool Complain)
13448 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13449 Complain(Complain), Context(S.getASTContext()),
13450 TargetTypeIsNonStaticMemberFunction(
13451 !!TargetType->getAs<MemberPointerType>()),
13452 FoundNonTemplateFunction(false),
13453 StaticMemberFunctionFromBoundPointer(false),
13454 HasComplained(false),
13455 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13456 OvlExpr(OvlExprInfo.Expression),
13457 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13458 ExtractUnqualifiedFunctionTypeFromTargetType();
13459
13460 if (TargetFunctionType->isFunctionType()) {
13461 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13462 if (!UME->isImplicitAccess() &&
13464 StaticMemberFunctionFromBoundPointer = true;
13465 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13466 DeclAccessPair dap;
13467 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13468 OvlExpr, false, &dap)) {
13469 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13470 if (!Method->isStatic()) {
13471 // If the target type is a non-function type and the function found
13472 // is a non-static member function, pretend as if that was the
13473 // target, it's the only possible type to end up with.
13474 TargetTypeIsNonStaticMemberFunction = true;
13475
13476 // And skip adding the function if its not in the proper form.
13477 // We'll diagnose this due to an empty set of functions.
13478 if (!OvlExprInfo.HasFormOfMemberPointer)
13479 return;
13480 }
13481
13482 Matches.push_back(std::make_pair(dap, Fn));
13483 }
13484 return;
13485 }
13486
13487 if (OvlExpr->hasExplicitTemplateArgs())
13488 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13489
13490 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13491 // C++ [over.over]p4:
13492 // If more than one function is selected, [...]
13493 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13494 if (FoundNonTemplateFunction) {
13495 EliminateAllTemplateMatches();
13496 EliminateLessPartialOrderingConstrainedMatches();
13497 } else
13498 EliminateAllExceptMostSpecializedTemplate();
13499 }
13500 }
13501
13502 if (S.getLangOpts().CUDA && Matches.size() > 1)
13503 EliminateSuboptimalCudaMatches();
13504 }
13505
13506 bool hasComplained() const { return HasComplained; }
13507
13508private:
13509 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13510 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13511 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13512 }
13513
13514 /// \return true if A is considered a better overload candidate for the
13515 /// desired type than B.
13516 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13517 // If A doesn't have exactly the correct type, we don't want to classify it
13518 // as "better" than anything else. This way, the user is required to
13519 // disambiguate for us if there are multiple candidates and no exact match.
13520 return candidateHasExactlyCorrectType(A) &&
13521 (!candidateHasExactlyCorrectType(B) ||
13522 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13523 }
13524
13525 /// \return true if we were able to eliminate all but one overload candidate,
13526 /// false otherwise.
13527 bool eliminiateSuboptimalOverloadCandidates() {
13528 // Same algorithm as overload resolution -- one pass to pick the "best",
13529 // another pass to be sure that nothing is better than the best.
13530 auto Best = Matches.begin();
13531 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13532 if (isBetterCandidate(I->second, Best->second))
13533 Best = I;
13534
13535 const FunctionDecl *BestFn = Best->second;
13536 auto IsBestOrInferiorToBest = [this, BestFn](
13537 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13538 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13539 };
13540
13541 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13542 // option, so we can potentially give the user a better error
13543 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13544 return false;
13545 Matches[0] = *Best;
13546 Matches.resize(1);
13547 return true;
13548 }
13549
13550 bool isTargetTypeAFunction() const {
13551 return TargetFunctionType->isFunctionType();
13552 }
13553
13554 // [ToType] [Return]
13555
13556 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13557 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13558 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13559 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13560 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13561 }
13562
13563 // return true if any matching specializations were found
13564 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13565 const DeclAccessPair& CurAccessFunPair) {
13566 if (CXXMethodDecl *Method
13567 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13568 // Skip non-static function templates when converting to pointer, and
13569 // static when converting to member pointer.
13570 bool CanConvertToFunctionPointer =
13571 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13572 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13573 return false;
13574 }
13575 else if (TargetTypeIsNonStaticMemberFunction)
13576 return false;
13577
13578 // C++ [over.over]p2:
13579 // If the name is a function template, template argument deduction is
13580 // done (14.8.2.2), and if the argument deduction succeeds, the
13581 // resulting template argument list is used to generate a single
13582 // function template specialization, which is added to the set of
13583 // overloaded functions considered.
13584 FunctionDecl *Specialization = nullptr;
13585 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13587 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13588 Specialization, Info, /*IsAddressOfFunction*/ true);
13589 Result != TemplateDeductionResult::Success) {
13590 // Make a note of the failed deduction for diagnostics.
13591 FailedCandidates.addCandidate()
13592 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13593 MakeDeductionFailureInfo(Context, Result, Info));
13594 return false;
13595 }
13596
13597 // Template argument deduction ensures that we have an exact match or
13598 // compatible pointer-to-function arguments that would be adjusted by ICS.
13599 // This function template specicalization works.
13601 Context.getCanonicalType(Specialization->getType()),
13602 Context.getCanonicalType(TargetFunctionType)));
13603
13605 return false;
13606
13607 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13608 return true;
13609 }
13610
13611 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13612 const DeclAccessPair& CurAccessFunPair) {
13613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13614 // Skip non-static functions when converting to pointer, and static
13615 // when converting to member pointer.
13616 bool CanConvertToFunctionPointer =
13617 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13618 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13619 return false;
13620 }
13621 else if (TargetTypeIsNonStaticMemberFunction)
13622 return false;
13623
13624 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13625 if (S.getLangOpts().CUDA) {
13626 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13627 if (!(Caller && Caller->isImplicit()) &&
13628 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13629 return false;
13630 }
13631 if (FunDecl->isMultiVersion()) {
13632 const auto *TA = FunDecl->getAttr<TargetAttr>();
13633 if (TA && !TA->isDefaultVersion())
13634 return false;
13635 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13636 if (TVA && !TVA->isDefaultVersion())
13637 return false;
13638 }
13639
13640 // If any candidate has a placeholder return type, trigger its deduction
13641 // now.
13642 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13643 Complain)) {
13644 HasComplained |= Complain;
13645 return false;
13646 }
13647
13648 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13649 return false;
13650
13651 // If we're in C, we need to support types that aren't exactly identical.
13652 if (!S.getLangOpts().CPlusPlus ||
13653 candidateHasExactlyCorrectType(FunDecl)) {
13654 Matches.push_back(std::make_pair(
13655 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13656 FoundNonTemplateFunction = true;
13657 return true;
13658 }
13659 }
13660
13661 return false;
13662 }
13663
13664 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13665 bool Ret = false;
13666
13667 // If the overload expression doesn't have the form of a pointer to
13668 // member, don't try to convert it to a pointer-to-member type.
13669 if (IsInvalidFormOfPointerToMemberFunction())
13670 return false;
13671
13672 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13673 E = OvlExpr->decls_end();
13674 I != E; ++I) {
13675 // Look through any using declarations to find the underlying function.
13676 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13677
13678 // C++ [over.over]p3:
13679 // Non-member functions and static member functions match
13680 // targets of type "pointer-to-function" or "reference-to-function."
13681 // Nonstatic member functions match targets of
13682 // type "pointer-to-member-function."
13683 // Note that according to DR 247, the containing class does not matter.
13684 if (FunctionTemplateDecl *FunctionTemplate
13685 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13686 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13687 Ret = true;
13688 }
13689 // If we have explicit template arguments supplied, skip non-templates.
13690 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13691 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13692 Ret = true;
13693 }
13694 assert(Ret || Matches.empty());
13695 return Ret;
13696 }
13697
13698 void EliminateAllExceptMostSpecializedTemplate() {
13699 // [...] and any given function template specialization F1 is
13700 // eliminated if the set contains a second function template
13701 // specialization whose function template is more specialized
13702 // than the function template of F1 according to the partial
13703 // ordering rules of 14.5.5.2.
13704
13705 // The algorithm specified above is quadratic. We instead use a
13706 // two-pass algorithm (similar to the one used to identify the
13707 // best viable function in an overload set) that identifies the
13708 // best function template (if it exists).
13709
13710 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13711 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13712 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13713
13714 // TODO: It looks like FailedCandidates does not serve much purpose
13715 // here, since the no_viable diagnostic has index 0.
13716 UnresolvedSetIterator Result = S.getMostSpecialized(
13717 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13718 SourceExpr->getBeginLoc(), S.PDiag(),
13719 S.PDiag(diag::err_addr_ovl_ambiguous)
13720 << Matches[0].second->getDeclName(),
13721 S.PDiag(diag::note_ovl_candidate)
13722 << (unsigned)oc_function << (unsigned)ocs_described_template,
13723 Complain, TargetFunctionType);
13724
13725 if (Result != MatchesCopy.end()) {
13726 // Make it the first and only element
13727 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13728 Matches[0].second = cast<FunctionDecl>(*Result);
13729 Matches.resize(1);
13730 } else
13731 HasComplained |= Complain;
13732 }
13733
13734 void EliminateAllTemplateMatches() {
13735 // [...] any function template specializations in the set are
13736 // eliminated if the set also contains a non-template function, [...]
13737 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13738 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13739 ++I;
13740 else {
13741 Matches[I] = Matches[--N];
13742 Matches.resize(N);
13743 }
13744 }
13745 }
13746
13747 void EliminateLessPartialOrderingConstrainedMatches() {
13748 // C++ [over.over]p5:
13749 // [...] Any given non-template function F0 is eliminated if the set
13750 // contains a second non-template function that is more
13751 // partial-ordering-constrained than F0. [...]
13752 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13753 "Call EliminateAllTemplateMatches() first");
13754 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13755 Results.push_back(Matches[0]);
13756 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13757 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13758 FunctionDecl *F = getMorePartialOrderingConstrained(
13759 S, Matches[I].second, Results[0].second,
13760 /*IsFn1Reversed=*/false,
13761 /*IsFn2Reversed=*/false);
13762 if (!F) {
13763 Results.push_back(Matches[I]);
13764 continue;
13765 }
13766 if (F == Matches[I].second) {
13767 Results.clear();
13768 Results.push_back(Matches[I]);
13769 }
13770 }
13771 std::swap(Matches, Results);
13772 }
13773
13774 void EliminateSuboptimalCudaMatches() {
13775 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13776 Matches);
13777 }
13778
13779public:
13780 void ComplainNoMatchesFound() const {
13781 assert(Matches.empty());
13782 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13783 << OvlExpr->getName() << TargetFunctionType
13784 << OvlExpr->getSourceRange();
13785 if (FailedCandidates.empty())
13786 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13787 /*TakingAddress=*/true);
13788 else {
13789 // We have some deduction failure messages. Use them to diagnose
13790 // the function templates, and diagnose the non-template candidates
13791 // normally.
13792 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13793 IEnd = OvlExpr->decls_end();
13794 I != IEnd; ++I)
13795 if (FunctionDecl *Fun =
13796 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13798 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13799 /*TakingAddress=*/true);
13800 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13801 }
13802 }
13803
13804 bool IsInvalidFormOfPointerToMemberFunction() const {
13805 return TargetTypeIsNonStaticMemberFunction &&
13806 !OvlExprInfo.HasFormOfMemberPointer;
13807 }
13808
13809 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13810 // TODO: Should we condition this on whether any functions might
13811 // have matched, or is it more appropriate to do that in callers?
13812 // TODO: a fixit wouldn't hurt.
13813 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13814 << TargetType << OvlExpr->getSourceRange();
13815 }
13816
13817 bool IsStaticMemberFunctionFromBoundPointer() const {
13818 return StaticMemberFunctionFromBoundPointer;
13819 }
13820
13821 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13822 S.Diag(OvlExpr->getBeginLoc(),
13823 diag::err_invalid_form_pointer_member_function)
13824 << OvlExpr->getSourceRange();
13825 }
13826
13827 void ComplainOfInvalidConversion() const {
13828 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13829 << OvlExpr->getName() << TargetType;
13830 }
13831
13832 void ComplainMultipleMatchesFound() const {
13833 assert(Matches.size() > 1);
13834 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13835 << OvlExpr->getName() << OvlExpr->getSourceRange();
13836 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13837 /*TakingAddress=*/true);
13838 }
13839
13840 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13841
13842 int getNumMatches() const { return Matches.size(); }
13843
13844 FunctionDecl* getMatchingFunctionDecl() const {
13845 if (Matches.size() != 1) return nullptr;
13846 return Matches[0].second;
13847 }
13848
13849 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13850 if (Matches.size() != 1) return nullptr;
13851 return &Matches[0].first;
13852 }
13853};
13854}
13855
13856FunctionDecl *
13858 QualType TargetType,
13859 bool Complain,
13860 DeclAccessPair &FoundResult,
13861 bool *pHadMultipleCandidates) {
13862 assert(AddressOfExpr->getType() == Context.OverloadTy);
13863
13864 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13865 Complain);
13866 int NumMatches = Resolver.getNumMatches();
13867 FunctionDecl *Fn = nullptr;
13868 bool ShouldComplain = Complain && !Resolver.hasComplained();
13869 if (NumMatches == 0 && ShouldComplain) {
13870 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13871 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13872 else
13873 Resolver.ComplainNoMatchesFound();
13874 }
13875 else if (NumMatches > 1 && ShouldComplain)
13876 Resolver.ComplainMultipleMatchesFound();
13877 else if (NumMatches == 1) {
13878 Fn = Resolver.getMatchingFunctionDecl();
13879 assert(Fn);
13880 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13881 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13882 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13883 if (Complain) {
13884 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13885 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13886 else
13887 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13888 }
13889 }
13890
13891 if (pHadMultipleCandidates)
13892 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13893 return Fn;
13894}
13895
13899 OverloadExpr *Ovl = R.Expression;
13900 bool IsResultAmbiguous = false;
13901 FunctionDecl *Result = nullptr;
13902 DeclAccessPair DAP;
13903 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13904
13905 // Return positive for better, negative for worse, 0 for equal preference.
13906 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13907 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13908 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13909 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13910 };
13911
13912 // Don't use the AddressOfResolver because we're specifically looking for
13913 // cases where we have one overload candidate that lacks
13914 // enable_if/pass_object_size/...
13915 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13916 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13917 if (!FD)
13918 return nullptr;
13919
13921 continue;
13922
13923 // If we found a better result, update Result.
13924 auto FoundBetter = [&]() {
13925 IsResultAmbiguous = false;
13926 DAP = I.getPair();
13927 Result = FD;
13928 };
13929
13930 // We have more than one result - see if it is more
13931 // partial-ordering-constrained than the previous one.
13932 if (Result) {
13933 // Check CUDA preference first. If the candidates have differennt CUDA
13934 // preference, choose the one with higher CUDA preference. Otherwise,
13935 // choose the one with more constraints.
13936 if (getLangOpts().CUDA) {
13937 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13938 // FD has different preference than Result.
13939 if (PreferenceByCUDA != 0) {
13940 // FD is more preferable than Result.
13941 if (PreferenceByCUDA > 0)
13942 FoundBetter();
13943 continue;
13944 }
13945 }
13946 // FD has the same CUDA preference than Result. Continue to check
13947 // constraints.
13948
13949 // C++ [over.over]p5:
13950 // [...] Any given non-template function F0 is eliminated if the set
13951 // contains a second non-template function that is more
13952 // partial-ordering-constrained than F0 [...]
13953 FunctionDecl *MoreConstrained =
13955 /*IsFn1Reversed=*/false,
13956 /*IsFn2Reversed=*/false);
13957 if (MoreConstrained != FD) {
13958 if (!MoreConstrained) {
13959 IsResultAmbiguous = true;
13960 AmbiguousDecls.push_back(FD);
13961 }
13962 continue;
13963 }
13964 // FD is more constrained - replace Result with it.
13965 }
13966 FoundBetter();
13967 }
13968
13969 if (IsResultAmbiguous)
13970 return nullptr;
13971
13972 if (Result) {
13973 // We skipped over some ambiguous declarations which might be ambiguous with
13974 // the selected result.
13975 for (FunctionDecl *Skipped : AmbiguousDecls) {
13976 // If skipped candidate has different CUDA preference than the result,
13977 // there is no ambiguity. Otherwise check whether they have different
13978 // constraints.
13979 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13980 continue;
13981 if (!getMoreConstrainedFunction(Skipped, Result))
13982 return nullptr;
13983 }
13984 Pair = DAP;
13985 }
13986 return Result;
13987}
13988
13990 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13991 Expr *E = SrcExpr.get();
13992 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13993
13994 DeclAccessPair DAP;
13996 if (!Found || Found->isCPUDispatchMultiVersion() ||
13997 Found->isCPUSpecificMultiVersion())
13998 return false;
13999
14000 // Emitting multiple diagnostics for a function that is both inaccessible and
14001 // unavailable is consistent with our behavior elsewhere. So, always check
14002 // for both.
14006 if (Res.isInvalid())
14007 return false;
14008 Expr *Fixed = Res.get();
14009 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14010 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14011 else
14012 SrcExpr = Fixed;
14013 return true;
14014}
14015
14017 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14018 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14019 // C++ [over.over]p1:
14020 // [...] [Note: any redundant set of parentheses surrounding the
14021 // overloaded function name is ignored (5.1). ]
14022 // C++ [over.over]p1:
14023 // [...] The overloaded function name can be preceded by the &
14024 // operator.
14025
14026 // If we didn't actually find any template-ids, we're done.
14027 if (!ovl->hasExplicitTemplateArgs())
14028 return nullptr;
14029
14030 TemplateArgumentListInfo ExplicitTemplateArgs;
14031 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14032
14033 // Look through all of the overloaded functions, searching for one
14034 // whose type matches exactly.
14035 FunctionDecl *Matched = nullptr;
14036 for (UnresolvedSetIterator I = ovl->decls_begin(),
14037 E = ovl->decls_end(); I != E; ++I) {
14038 // C++0x [temp.arg.explicit]p3:
14039 // [...] In contexts where deduction is done and fails, or in contexts
14040 // where deduction is not done, if a template argument list is
14041 // specified and it, along with any default template arguments,
14042 // identifies a single function template specialization, then the
14043 // template-id is an lvalue for the function template specialization.
14045 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14046 if (!FunctionTemplate)
14047 continue;
14048
14049 // C++ [over.over]p2:
14050 // If the name is a function template, template argument deduction is
14051 // done (14.8.2.2), and if the argument deduction succeeds, the
14052 // resulting template argument list is used to generate a single
14053 // function template specialization, which is added to the set of
14054 // overloaded functions considered.
14055 FunctionDecl *Specialization = nullptr;
14056 TemplateDeductionInfo Info(ovl->getNameLoc());
14058 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14059 /*IsAddressOfFunction*/ true);
14061 // Make a note of the failed deduction for diagnostics.
14062 if (FailedTSC)
14063 FailedTSC->addCandidate().set(
14064 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14066 continue;
14067 }
14068
14069 assert(Specialization && "no specialization and no error?");
14070
14071 // C++ [temp.deduct.call]p6:
14072 // [...] If all successful deductions yield the same deduced A, that
14073 // deduced A is the result of deduction; otherwise, the parameter is
14074 // treated as a non-deduced context.
14075 if (Matched) {
14076 if (ForTypeDeduction &&
14078 Specialization->getType()))
14079 continue;
14080 // Multiple matches; we can't resolve to a single declaration.
14081 if (Complain) {
14082 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14083 << ovl->getName();
14085 }
14086 return nullptr;
14087 }
14088
14089 Matched = Specialization;
14090 if (FoundResult) *FoundResult = I.getPair();
14091 }
14092
14093 if (Matched &&
14094 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14095 return nullptr;
14096
14097 return Matched;
14098}
14099
14101 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14102 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14103 unsigned DiagIDForComplaining) {
14104 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14105
14107
14108 DeclAccessPair found;
14109 ExprResult SingleFunctionExpression;
14111 ovl.Expression, /*complain*/ false, &found)) {
14112 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14113 SrcExpr = ExprError();
14114 return true;
14115 }
14116
14117 // It is only correct to resolve to an instance method if we're
14118 // resolving a form that's permitted to be a pointer to member.
14119 // Otherwise we'll end up making a bound member expression, which
14120 // is illegal in all the contexts we resolve like this.
14121 if (!ovl.HasFormOfMemberPointer &&
14122 isa<CXXMethodDecl>(fn) &&
14123 cast<CXXMethodDecl>(fn)->isInstance()) {
14124 if (!complain) return false;
14125
14126 Diag(ovl.Expression->getExprLoc(),
14127 diag::err_bound_member_function)
14128 << 0 << ovl.Expression->getSourceRange();
14129
14130 // TODO: I believe we only end up here if there's a mix of
14131 // static and non-static candidates (otherwise the expression
14132 // would have 'bound member' type, not 'overload' type).
14133 // Ideally we would note which candidate was chosen and why
14134 // the static candidates were rejected.
14135 SrcExpr = ExprError();
14136 return true;
14137 }
14138
14139 // Fix the expression to refer to 'fn'.
14140 SingleFunctionExpression =
14141 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14142
14143 // If desired, do function-to-pointer decay.
14144 if (doFunctionPointerConversion) {
14145 SingleFunctionExpression =
14146 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14147 if (SingleFunctionExpression.isInvalid()) {
14148 SrcExpr = ExprError();
14149 return true;
14150 }
14151 }
14152 }
14153
14154 if (!SingleFunctionExpression.isUsable()) {
14155 if (complain) {
14156 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14157 << ovl.Expression->getName()
14158 << DestTypeForComplaining
14159 << OpRangeForComplaining
14161 NoteAllOverloadCandidates(SrcExpr.get());
14162
14163 SrcExpr = ExprError();
14164 return true;
14165 }
14166
14167 return false;
14168 }
14169
14170 SrcExpr = SingleFunctionExpression;
14171 return true;
14172}
14173
14174/// Add a single candidate to the overload set.
14176 DeclAccessPair FoundDecl,
14177 TemplateArgumentListInfo *ExplicitTemplateArgs,
14178 ArrayRef<Expr *> Args,
14179 OverloadCandidateSet &CandidateSet,
14180 bool PartialOverloading,
14181 bool KnownValid) {
14182 NamedDecl *Callee = FoundDecl.getDecl();
14183 if (isa<UsingShadowDecl>(Callee))
14184 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14185
14186 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14187 if (ExplicitTemplateArgs) {
14188 assert(!KnownValid && "Explicit template arguments?");
14189 return;
14190 }
14191 // Prevent ill-formed function decls to be added as overload candidates.
14192 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14193 return;
14194
14195 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14196 /*SuppressUserConversions=*/false,
14197 PartialOverloading);
14198 return;
14199 }
14200
14201 if (FunctionTemplateDecl *FuncTemplate
14202 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14203 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14204 ExplicitTemplateArgs, Args, CandidateSet,
14205 /*SuppressUserConversions=*/false,
14206 PartialOverloading);
14207 return;
14208 }
14209
14210 assert(!KnownValid && "unhandled case in overloaded call candidate");
14211}
14212
14214 ArrayRef<Expr *> Args,
14215 OverloadCandidateSet &CandidateSet,
14216 bool PartialOverloading) {
14217
14218#ifndef NDEBUG
14219 // Verify that ArgumentDependentLookup is consistent with the rules
14220 // in C++0x [basic.lookup.argdep]p3:
14221 //
14222 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14223 // and let Y be the lookup set produced by argument dependent
14224 // lookup (defined as follows). If X contains
14225 //
14226 // -- a declaration of a class member, or
14227 //
14228 // -- a block-scope function declaration that is not a
14229 // using-declaration, or
14230 //
14231 // -- a declaration that is neither a function or a function
14232 // template
14233 //
14234 // then Y is empty.
14235
14236 if (ULE->requiresADL()) {
14238 E = ULE->decls_end(); I != E; ++I) {
14239 assert(!(*I)->getDeclContext()->isRecord());
14240 assert(isa<UsingShadowDecl>(*I) ||
14241 !(*I)->getDeclContext()->isFunctionOrMethod());
14242 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14243 }
14244 }
14245#endif
14246
14247 // It would be nice to avoid this copy.
14248 TemplateArgumentListInfo TABuffer;
14249 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14250 if (ULE->hasExplicitTemplateArgs()) {
14251 ULE->copyTemplateArgumentsInto(TABuffer);
14252 ExplicitTemplateArgs = &TABuffer;
14253 }
14254
14256 E = ULE->decls_end(); I != E; ++I)
14257 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14258 CandidateSet, PartialOverloading,
14259 /*KnownValid*/ true);
14260
14261 if (ULE->requiresADL())
14263 Args, ExplicitTemplateArgs,
14264 CandidateSet, PartialOverloading);
14265}
14266
14268 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14269 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14270 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14271 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14272 CandidateSet, false, /*KnownValid*/ false);
14273}
14274
14275/// Determine whether a declaration with the specified name could be moved into
14276/// a different namespace.
14278 switch (Name.getCXXOverloadedOperator()) {
14279 case OO_New: case OO_Array_New:
14280 case OO_Delete: case OO_Array_Delete:
14281 return false;
14282
14283 default:
14284 return true;
14285 }
14286}
14287
14288/// Attempt to recover from an ill-formed use of a non-dependent name in a
14289/// template, where the non-dependent name was declared after the template
14290/// was defined. This is common in code written for a compilers which do not
14291/// correctly implement two-stage name lookup.
14292///
14293/// Returns true if a viable candidate was found and a diagnostic was issued.
14295 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14297 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14298 CXXRecordDecl **FoundInClass = nullptr) {
14299 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14300 return false;
14301
14302 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14303 if (DC->isTransparentContext())
14304 continue;
14305
14306 SemaRef.LookupQualifiedName(R, DC);
14307
14308 if (!R.empty()) {
14310
14311 OverloadCandidateSet Candidates(FnLoc, CSK);
14312 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14313 Candidates);
14314
14317 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14318
14319 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14320 // We either found non-function declarations or a best viable function
14321 // at class scope. A class-scope lookup result disables ADL. Don't
14322 // look past this, but let the caller know that we found something that
14323 // either is, or might be, usable in this class.
14324 if (FoundInClass) {
14325 *FoundInClass = RD;
14326 if (OR == OR_Success) {
14327 R.clear();
14328 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14329 R.resolveKind();
14330 }
14331 }
14332 return false;
14333 }
14334
14335 if (OR != OR_Success) {
14336 // There wasn't a unique best function or function template.
14337 return false;
14338 }
14339
14340 // Find the namespaces where ADL would have looked, and suggest
14341 // declaring the function there instead.
14342 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14343 Sema::AssociatedClassSet AssociatedClasses;
14344 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14345 AssociatedNamespaces,
14346 AssociatedClasses);
14347 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14349 DeclContext *Std = SemaRef.getStdNamespace();
14350 for (Sema::AssociatedNamespaceSet::iterator
14351 it = AssociatedNamespaces.begin(),
14352 end = AssociatedNamespaces.end(); it != end; ++it) {
14353 // Never suggest declaring a function within namespace 'std'.
14354 if (Std && Std->Encloses(*it))
14355 continue;
14356
14357 // Never suggest declaring a function within a namespace with a
14358 // reserved name, like __gnu_cxx.
14359 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14360 if (NS &&
14361 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14362 continue;
14363
14364 SuggestedNamespaces.insert(*it);
14365 }
14366 }
14367
14368 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14369 << R.getLookupName();
14370 if (SuggestedNamespaces.empty()) {
14371 SemaRef.Diag(Best->Function->getLocation(),
14372 diag::note_not_found_by_two_phase_lookup)
14373 << R.getLookupName() << 0;
14374 } else if (SuggestedNamespaces.size() == 1) {
14375 SemaRef.Diag(Best->Function->getLocation(),
14376 diag::note_not_found_by_two_phase_lookup)
14377 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14378 } else {
14379 // FIXME: It would be useful to list the associated namespaces here,
14380 // but the diagnostics infrastructure doesn't provide a way to produce
14381 // a localized representation of a list of items.
14382 SemaRef.Diag(Best->Function->getLocation(),
14383 diag::note_not_found_by_two_phase_lookup)
14384 << R.getLookupName() << 2;
14385 }
14386
14387 // Try to recover by calling this function.
14388 return true;
14389 }
14390
14391 R.clear();
14392 }
14393
14394 return false;
14395}
14396
14397/// Attempt to recover from ill-formed use of a non-dependent operator in a
14398/// template, where the non-dependent operator was declared after the template
14399/// was defined.
14400///
14401/// Returns true if a viable candidate was found and a diagnostic was issued.
14402static bool
14404 SourceLocation OpLoc,
14405 ArrayRef<Expr *> Args) {
14406 DeclarationName OpName =
14408 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14409 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14411 /*ExplicitTemplateArgs=*/nullptr, Args);
14412}
14413
14414namespace {
14415class BuildRecoveryCallExprRAII {
14416 Sema &SemaRef;
14417 Sema::SatisfactionStackResetRAII SatStack;
14418
14419public:
14420 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14421 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14422 SemaRef.IsBuildingRecoveryCallExpr = true;
14423 }
14424
14425 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14426};
14427}
14428
14429/// Attempts to recover from a call where no functions were found.
14430///
14431/// This function will do one of three things:
14432/// * Diagnose, recover, and return a recovery expression.
14433/// * Diagnose, fail to recover, and return ExprError().
14434/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14435/// expected to diagnose as appropriate.
14436static ExprResult
14439 SourceLocation LParenLoc,
14441 SourceLocation RParenLoc,
14442 bool EmptyLookup, bool AllowTypoCorrection) {
14443 // Do not try to recover if it is already building a recovery call.
14444 // This stops infinite loops for template instantiations like
14445 //
14446 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14447 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14448 if (SemaRef.IsBuildingRecoveryCallExpr)
14449 return ExprResult();
14450 BuildRecoveryCallExprRAII RCE(SemaRef);
14451
14452 CXXScopeSpec SS;
14453 SS.Adopt(ULE->getQualifierLoc());
14454 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14455
14456 TemplateArgumentListInfo TABuffer;
14457 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14458 if (ULE->hasExplicitTemplateArgs()) {
14459 ULE->copyTemplateArgumentsInto(TABuffer);
14460 ExplicitTemplateArgs = &TABuffer;
14461 }
14462
14463 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14465 CXXRecordDecl *FoundInClass = nullptr;
14466 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14468 ExplicitTemplateArgs, Args, &FoundInClass)) {
14469 // OK, diagnosed a two-phase lookup issue.
14470 } else if (EmptyLookup) {
14471 // Try to recover from an empty lookup with typo correction.
14472 R.clear();
14473 NoTypoCorrectionCCC NoTypoValidator{};
14474 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14475 ExplicitTemplateArgs != nullptr,
14476 dyn_cast<MemberExpr>(Fn));
14477 CorrectionCandidateCallback &Validator =
14478 AllowTypoCorrection
14479 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14480 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14481 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14482 Args))
14483 return ExprError();
14484 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14485 // We found a usable declaration of the name in a dependent base of some
14486 // enclosing class.
14487 // FIXME: We should also explain why the candidates found by name lookup
14488 // were not viable.
14489 if (SemaRef.DiagnoseDependentMemberLookup(R))
14490 return ExprError();
14491 } else {
14492 // We had viable candidates and couldn't recover; let the caller diagnose
14493 // this.
14494 return ExprResult();
14495 }
14496
14497 // If we get here, we should have issued a diagnostic and formed a recovery
14498 // lookup result.
14499 assert(!R.empty() && "lookup results empty despite recovery");
14500
14501 // If recovery created an ambiguity, just bail out.
14502 if (R.isAmbiguous()) {
14504 return ExprError();
14505 }
14506
14507 // Build an implicit member call if appropriate. Just drop the
14508 // casts and such from the call, we don't really care.
14509 ExprResult NewFn = ExprError();
14510 if ((*R.begin())->isCXXClassMember())
14511 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14512 ExplicitTemplateArgs, S);
14513 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14514 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14515 ExplicitTemplateArgs);
14516 else
14517 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14518
14519 if (NewFn.isInvalid())
14520 return ExprError();
14521
14522 // This shouldn't cause an infinite loop because we're giving it
14523 // an expression with viable lookup results, which should never
14524 // end up here.
14525 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14526 MultiExprArg(Args.data(), Args.size()),
14527 RParenLoc);
14528}
14529
14532 MultiExprArg Args,
14533 SourceLocation RParenLoc,
14534 OverloadCandidateSet *CandidateSet,
14535 ExprResult *Result) {
14536#ifndef NDEBUG
14537 if (ULE->requiresADL()) {
14538 // To do ADL, we must have found an unqualified name.
14539 assert(!ULE->getQualifier() && "qualified name with ADL");
14540
14541 // We don't perform ADL for implicit declarations of builtins.
14542 // Verify that this was correctly set up.
14543 FunctionDecl *F;
14544 if (ULE->decls_begin() != ULE->decls_end() &&
14545 ULE->decls_begin() + 1 == ULE->decls_end() &&
14546 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14547 F->getBuiltinID() && F->isImplicit())
14548 llvm_unreachable("performing ADL for builtin");
14549
14550 // We don't perform ADL in C.
14551 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14552 }
14553#endif
14554
14555 UnbridgedCastsSet UnbridgedCasts;
14556 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14557 *Result = ExprError();
14558 return true;
14559 }
14560
14561 // Add the functions denoted by the callee to the set of candidate
14562 // functions, including those from argument-dependent lookup.
14563 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14564
14565 if (getLangOpts().MSVCCompat &&
14566 CurContext->isDependentContext() && !isSFINAEContext() &&
14568
14570 if (CandidateSet->empty() ||
14571 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14573 // In Microsoft mode, if we are inside a template class member function
14574 // then create a type dependent CallExpr. The goal is to postpone name
14575 // lookup to instantiation time to be able to search into type dependent
14576 // base classes.
14577 CallExpr *CE =
14578 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14579 RParenLoc, CurFPFeatureOverrides());
14581 *Result = CE;
14582 return true;
14583 }
14584 }
14585
14586 if (CandidateSet->empty())
14587 return false;
14588
14589 UnbridgedCasts.restore();
14590 return false;
14591}
14592
14593// Guess at what the return type for an unresolvable overload should be.
14596 std::optional<QualType> Result;
14597 // Adjust Type after seeing a candidate.
14598 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14599 if (!Candidate.Function)
14600 return;
14601 if (Candidate.Function->isInvalidDecl())
14602 return;
14603 QualType T = Candidate.Function->getReturnType();
14604 if (T.isNull())
14605 return;
14606 if (!Result)
14607 Result = T;
14608 else if (Result != T)
14609 Result = QualType();
14610 };
14611
14612 // Look for an unambiguous type from a progressively larger subset.
14613 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14614 //
14615 // First, consider only the best candidate.
14616 if (Best && *Best != CS.end())
14617 ConsiderCandidate(**Best);
14618 // Next, consider only viable candidates.
14619 if (!Result)
14620 for (const auto &C : CS)
14621 if (C.Viable)
14622 ConsiderCandidate(C);
14623 // Finally, consider all candidates.
14624 if (!Result)
14625 for (const auto &C : CS)
14626 ConsiderCandidate(C);
14627
14628 if (!Result)
14629 return QualType();
14630 auto Value = *Result;
14631 if (Value.isNull() || Value->isUndeducedType())
14632 return QualType();
14633 return Value;
14634}
14635
14636/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14637/// the completed call expression. If overload resolution fails, emits
14638/// diagnostics and returns ExprError()
14641 SourceLocation LParenLoc,
14642 MultiExprArg Args,
14643 SourceLocation RParenLoc,
14644 Expr *ExecConfig,
14645 OverloadCandidateSet *CandidateSet,
14647 OverloadingResult OverloadResult,
14648 bool AllowTypoCorrection) {
14649 switch (OverloadResult) {
14650 case OR_Success: {
14651 FunctionDecl *FDecl = (*Best)->Function;
14652 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14653 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14654 return ExprError();
14655 ExprResult Res =
14656 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14657 if (Res.isInvalid())
14658 return ExprError();
14659 return SemaRef.BuildResolvedCallExpr(
14660 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14661 /*IsExecConfig=*/false,
14662 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14663 }
14664
14665 case OR_No_Viable_Function: {
14666 if (*Best != CandidateSet->end() &&
14667 CandidateSet->getKind() ==
14669 if (CXXMethodDecl *M =
14670 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14672 CandidateSet->NoteCandidates(
14674 Fn->getBeginLoc(),
14675 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14676 SemaRef, OCD_AmbiguousCandidates, Args);
14677 return ExprError();
14678 }
14679 }
14680
14681 // Try to recover by looking for viable functions which the user might
14682 // have meant to call.
14683 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14684 Args, RParenLoc,
14685 CandidateSet->empty(),
14686 AllowTypoCorrection);
14687 if (Recovery.isInvalid() || Recovery.isUsable())
14688 return Recovery;
14689
14690 // If the user passes in a function that we can't take the address of, we
14691 // generally end up emitting really bad error messages. Here, we attempt to
14692 // emit better ones.
14693 for (const Expr *Arg : Args) {
14694 if (!Arg->getType()->isFunctionType())
14695 continue;
14696 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14697 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14698 if (FD &&
14699 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14700 Arg->getExprLoc()))
14701 return ExprError();
14702 }
14703 }
14704
14705 CandidateSet->NoteCandidates(
14707 Fn->getBeginLoc(),
14708 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14709 << ULE->getName() << Fn->getSourceRange()),
14710 SemaRef, OCD_AllCandidates, Args);
14711 break;
14712 }
14713
14714 case OR_Ambiguous:
14715 CandidateSet->NoteCandidates(
14716 PartialDiagnosticAt(Fn->getBeginLoc(),
14717 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14718 << ULE->getName() << Fn->getSourceRange()),
14719 SemaRef, OCD_AmbiguousCandidates, Args);
14720 break;
14721
14722 case OR_Deleted: {
14723 FunctionDecl *FDecl = (*Best)->Function;
14724 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14725 Fn->getSourceRange(), ULE->getName(),
14726 *CandidateSet, FDecl, Args);
14727
14728 // We emitted an error for the unavailable/deleted function call but keep
14729 // the call in the AST.
14730 ExprResult Res =
14731 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14732 if (Res.isInvalid())
14733 return ExprError();
14734 return SemaRef.BuildResolvedCallExpr(
14735 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14736 /*IsExecConfig=*/false,
14737 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14738 }
14739 }
14740
14741 // Overload resolution failed, try to recover.
14742 SmallVector<Expr *, 8> SubExprs = {Fn};
14743 SubExprs.append(Args.begin(), Args.end());
14744 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14745 chooseRecoveryType(*CandidateSet, Best));
14746}
14747
14750 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14751 if (I->Viable &&
14752 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14753 I->Viable = false;
14754 I->FailureKind = ovl_fail_addr_not_available;
14755 }
14756 }
14757}
14758
14761 SourceLocation LParenLoc,
14762 MultiExprArg Args,
14763 SourceLocation RParenLoc,
14764 Expr *ExecConfig,
14765 bool AllowTypoCorrection,
14766 bool CalleesAddressIsTaken) {
14767
14771
14772 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14773 ExprResult result;
14774
14775 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14776 &result))
14777 return result;
14778
14779 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14780 // functions that aren't addressible are considered unviable.
14781 if (CalleesAddressIsTaken)
14782 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14783
14785 OverloadingResult OverloadResult =
14786 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14787
14788 // [C++23][over.call.func]
14789 // if overload resolution selects a non-static member function,
14790 // the call is ill-formed;
14792 Best != CandidateSet.end()) {
14793 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14794 M && M->isImplicitObjectMemberFunction()) {
14795 OverloadResult = OR_No_Viable_Function;
14796 }
14797 }
14798
14799 // Model the case with a call to a templated function whose definition
14800 // encloses the call and whose return type contains a placeholder type as if
14801 // the UnresolvedLookupExpr was type-dependent.
14802 if (OverloadResult == OR_Success) {
14803 const FunctionDecl *FDecl = Best->Function;
14804 if (LangOpts.CUDA)
14805 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14806 if (FDecl && FDecl->isTemplateInstantiation() &&
14807 FDecl->getReturnType()->isUndeducedType()) {
14808
14809 // Creating dependent CallExpr is not okay if the enclosing context itself
14810 // is not dependent. This situation notably arises if a non-dependent
14811 // member function calls the later-defined overloaded static function.
14812 //
14813 // For example, in
14814 // class A {
14815 // void c() { callee(1); }
14816 // static auto callee(auto x) { }
14817 // };
14818 //
14819 // Here callee(1) is unresolved at the call site, but is not inside a
14820 // dependent context. There will be no further attempt to resolve this
14821 // call if it is made dependent.
14822
14823 if (const auto *TP =
14824 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14825 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14826 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14827 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14828 }
14829 }
14830 }
14831
14832 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14833 ExecConfig, &CandidateSet, &Best,
14834 OverloadResult, AllowTypoCorrection);
14835}
14836
14840 const UnresolvedSetImpl &Fns,
14841 bool PerformADL) {
14843 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14844 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14845}
14846
14849 bool HadMultipleCandidates) {
14850 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14851 // the FoundDecl as it impedes TransformMemberExpr.
14852 // We go a bit further here: if there's no difference in UnderlyingDecl,
14853 // then using FoundDecl vs Method shouldn't make a difference either.
14854 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14855 FoundDecl = Method;
14856 // Convert the expression to match the conversion function's implicit object
14857 // parameter.
14858 ExprResult Exp;
14859 if (Method->isExplicitObjectMemberFunction())
14861 else
14863 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14864 if (Exp.isInvalid())
14865 return true;
14866
14867 if (Method->getParent()->isLambda() &&
14868 Method->getConversionType()->isBlockPointerType()) {
14869 // This is a lambda conversion to block pointer; check if the argument
14870 // was a LambdaExpr.
14871 Expr *SubE = E;
14872 auto *CE = dyn_cast<CastExpr>(SubE);
14873 if (CE && CE->getCastKind() == CK_NoOp)
14874 SubE = CE->getSubExpr();
14875 SubE = SubE->IgnoreParens();
14876 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14877 SubE = BE->getSubExpr();
14878 if (isa<LambdaExpr>(SubE)) {
14879 // For the conversion to block pointer on a lambda expression, we
14880 // construct a special BlockLiteral instead; this doesn't really make
14881 // a difference in ARC, but outside of ARC the resulting block literal
14882 // follows the normal lifetime rules for block literals instead of being
14883 // autoreleased.
14887 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14889
14890 // FIXME: This note should be produced by a CodeSynthesisContext.
14891 if (BlockExp.isInvalid())
14892 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14893 return BlockExp;
14894 }
14895 }
14896 CallExpr *CE;
14897 QualType ResultType = Method->getReturnType();
14899 ResultType = ResultType.getNonLValueExprType(Context);
14900 if (Method->isExplicitObjectMemberFunction()) {
14901 ExprResult FnExpr =
14902 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14903 HadMultipleCandidates, E->getBeginLoc());
14904 if (FnExpr.isInvalid())
14905 return ExprError();
14906 Expr *ObjectParam = Exp.get();
14907 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14908 ResultType, VK, Exp.get()->getEndLoc(),
14910 CE->setUsesMemberSyntax(true);
14911 } else {
14912 MemberExpr *ME =
14913 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14915 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14916 HadMultipleCandidates, DeclarationNameInfo(),
14917 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14918
14919 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14920 Exp.get()->getEndLoc(),
14922 }
14923
14924 if (CheckFunctionCall(Method, CE,
14925 Method->getType()->castAs<FunctionProtoType>()))
14926 return ExprError();
14927
14929}
14930
14933 const UnresolvedSetImpl &Fns,
14934 Expr *Input, bool PerformADL) {
14936 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14937 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14938 // TODO: provide better source location info.
14939 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14940
14941 if (checkPlaceholderForOverload(*this, Input))
14942 return ExprError();
14943
14944 Expr *Args[2] = { Input, nullptr };
14945 unsigned NumArgs = 1;
14946
14947 // For post-increment and post-decrement, add the implicit '0' as
14948 // the second argument, so that we know this is a post-increment or
14949 // post-decrement.
14950 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14951 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14952 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14953 SourceLocation());
14954 NumArgs = 2;
14955 }
14956
14957 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14958
14959 if (Input->isTypeDependent()) {
14961 // [C++26][expr.unary.op][expr.pre.incr]
14962 // The * operator yields an lvalue of type
14963 // The pre/post increment operators yied an lvalue.
14964 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14965 VK = VK_LValue;
14966
14967 if (Fns.empty())
14968 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14969 OK_Ordinary, OpLoc, false,
14971
14972 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14974 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14975 if (Fn.isInvalid())
14976 return ExprError();
14977 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14978 Context.DependentTy, VK_PRValue, OpLoc,
14980 }
14981
14982 // Build an empty overload set.
14984
14985 // Add the candidates from the given function set.
14986 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14987
14988 // Add operator candidates that are member functions.
14989 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14990
14991 // Add candidates from ADL.
14992 if (PerformADL) {
14993 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14994 /*ExplicitTemplateArgs*/nullptr,
14995 CandidateSet);
14996 }
14997
14998 // Add builtin operator candidates.
14999 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15000
15001 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15002
15003 // Perform overload resolution.
15005 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15006 case OR_Success: {
15007 // We found a built-in operator or an overloaded operator.
15008 FunctionDecl *FnDecl = Best->Function;
15009
15010 if (FnDecl) {
15011 Expr *Base = nullptr;
15012 // We matched an overloaded operator. Build a call to that
15013 // operator.
15014
15015 // Convert the arguments.
15016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15017 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15018
15019 ExprResult InputInit;
15020 if (Method->isExplicitObjectMemberFunction())
15021 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15022 else
15024 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15025 if (InputInit.isInvalid())
15026 return ExprError();
15027 Base = Input = InputInit.get();
15028 } else {
15029 // Convert the arguments.
15030 ExprResult InputInit
15032 Context,
15033 FnDecl->getParamDecl(0)),
15035 Input);
15036 if (InputInit.isInvalid())
15037 return ExprError();
15038 Input = InputInit.get();
15039 }
15040
15041 // Build the actual expression node.
15042 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15043 Base, HadMultipleCandidates,
15044 OpLoc);
15045 if (FnExpr.isInvalid())
15046 return ExprError();
15047
15048 // Determine the result type.
15049 QualType ResultTy = FnDecl->getReturnType();
15051 ResultTy = ResultTy.getNonLValueExprType(Context);
15052
15053 Args[0] = Input;
15055 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15057 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15058
15059 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15060 return ExprError();
15061
15062 if (CheckFunctionCall(FnDecl, TheCall,
15063 FnDecl->getType()->castAs<FunctionProtoType>()))
15064 return ExprError();
15065 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15066 } else {
15067 // We matched a built-in operator. Convert the arguments, then
15068 // break out so that we will build the appropriate built-in
15069 // operator node.
15071 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15074 if (InputRes.isInvalid())
15075 return ExprError();
15076 Input = InputRes.get();
15077 break;
15078 }
15079 }
15080
15082 // This is an erroneous use of an operator which can be overloaded by
15083 // a non-member function. Check for non-member operators which were
15084 // defined too late to be candidates.
15085 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15086 // FIXME: Recover by calling the found function.
15087 return ExprError();
15088
15089 // No viable function; fall through to handling this as a
15090 // built-in operator, which will produce an error message for us.
15091 break;
15092
15093 case OR_Ambiguous:
15094 CandidateSet.NoteCandidates(
15095 PartialDiagnosticAt(OpLoc,
15096 PDiag(diag::err_ovl_ambiguous_oper_unary)
15098 << Input->getType() << Input->getSourceRange()),
15099 *this, OCD_AmbiguousCandidates, ArgsArray,
15100 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15101 return ExprError();
15102
15103 case OR_Deleted: {
15104 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15105 // object whose method was called. Later in NoteCandidates size of ArgsArray
15106 // is passed further and it eventually ends up compared to number of
15107 // function candidate parameters which never includes the object parameter,
15108 // so slice ArgsArray to make sure apples are compared to apples.
15109 StringLiteral *Msg = Best->Function->getDeletedMessage();
15110 CandidateSet.NoteCandidates(
15111 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15113 << (Msg != nullptr)
15114 << (Msg ? Msg->getString() : StringRef())
15115 << Input->getSourceRange()),
15116 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15117 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15118 return ExprError();
15119 }
15120 }
15121
15122 // Either we found no viable overloaded operator or we matched a
15123 // built-in operator. In either case, fall through to trying to
15124 // build a built-in operation.
15125 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15126}
15127
15130 const UnresolvedSetImpl &Fns,
15131 ArrayRef<Expr *> Args, bool PerformADL) {
15132 SourceLocation OpLoc = CandidateSet.getLocation();
15133
15134 OverloadedOperatorKind ExtraOp =
15137 : OO_None;
15138
15139 // Add the candidates from the given function set. This also adds the
15140 // rewritten candidates using these functions if necessary.
15141 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15142
15143 // As template candidates are not deduced immediately,
15144 // persist the array in the overload set.
15145 ArrayRef<Expr *> ReversedArgs;
15146 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15147 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15148 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15149
15150 // Add operator candidates that are member functions.
15151 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15152 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15153 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15155
15156 // In C++20, also add any rewritten member candidates.
15157 if (ExtraOp) {
15158 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15159 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15160 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15162 }
15163
15164 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15165 // performed for an assignment operator (nor for operator[] nor operator->,
15166 // which don't get here).
15167 if (Op != OO_Equal && PerformADL) {
15168 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15169 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15170 /*ExplicitTemplateArgs*/ nullptr,
15171 CandidateSet);
15172 if (ExtraOp) {
15173 DeclarationName ExtraOpName =
15174 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15175 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15176 /*ExplicitTemplateArgs*/ nullptr,
15177 CandidateSet);
15178 }
15179 }
15180
15181 // Add builtin operator candidates.
15182 //
15183 // FIXME: We don't add any rewritten candidates here. This is strictly
15184 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15185 // resulting in our selecting a rewritten builtin candidate. For example:
15186 //
15187 // enum class E { e };
15188 // bool operator!=(E, E) requires false;
15189 // bool k = E::e != E::e;
15190 //
15191 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15192 // it seems unreasonable to consider rewritten builtin candidates. A core
15193 // issue has been filed proposing to removed this requirement.
15194 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15195}
15196
15199 const UnresolvedSetImpl &Fns, Expr *LHS,
15200 Expr *RHS, bool PerformADL,
15201 bool AllowRewrittenCandidates,
15202 FunctionDecl *DefaultedFn) {
15203 Expr *Args[2] = { LHS, RHS };
15204 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15205
15206 if (!getLangOpts().CPlusPlus20)
15207 AllowRewrittenCandidates = false;
15208
15210
15211 // If either side is type-dependent, create an appropriate dependent
15212 // expression.
15213 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15214 if (Fns.empty()) {
15215 // If there are no functions to store, just build a dependent
15216 // BinaryOperator or CompoundAssignment.
15219 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15220 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15221 Context.DependentTy);
15223 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15225 }
15226
15227 // FIXME: save results of ADL from here?
15228 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15229 // TODO: provide better source location info in DNLoc component.
15230 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15231 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15233 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15234 if (Fn.isInvalid())
15235 return ExprError();
15236 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15237 Context.DependentTy, VK_PRValue, OpLoc,
15239 }
15240
15241 // If this is the .* operator, which is not overloadable, just
15242 // create a built-in binary operator.
15243 if (Opc == BO_PtrMemD) {
15244 auto CheckPlaceholder = [&](Expr *&Arg) {
15246 if (Res.isUsable())
15247 Arg = Res.get();
15248 return !Res.isUsable();
15249 };
15250
15251 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15252 // expression that contains placeholders (in either the LHS or RHS).
15253 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15254 return ExprError();
15255 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15256 }
15257
15258 // Always do placeholder-like conversions on the RHS.
15259 if (checkPlaceholderForOverload(*this, Args[1]))
15260 return ExprError();
15261
15262 // Do placeholder-like conversion on the LHS; note that we should
15263 // not get here with a PseudoObject LHS.
15264 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15265 if (checkPlaceholderForOverload(*this, Args[0]))
15266 return ExprError();
15267
15268 // If this is the assignment operator, we only perform overload resolution
15269 // if the left-hand side is a class or enumeration type. This is actually
15270 // a hack. The standard requires that we do overload resolution between the
15271 // various built-in candidates, but as DR507 points out, this can lead to
15272 // problems. So we do it this way, which pretty much follows what GCC does.
15273 // Note that we go the traditional code path for compound assignment forms.
15274 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15275 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15276
15277 // Build the overload set.
15280 Op, OpLoc, AllowRewrittenCandidates));
15281 if (DefaultedFn)
15282 CandidateSet.exclude(DefaultedFn);
15283 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15284
15285 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15286
15287 // Perform overload resolution.
15289 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15290 case OR_Success: {
15291 // We found a built-in operator or an overloaded operator.
15292 FunctionDecl *FnDecl = Best->Function;
15293
15294 bool IsReversed = Best->isReversed();
15295 if (IsReversed)
15296 std::swap(Args[0], Args[1]);
15297
15298 if (FnDecl) {
15299
15300 if (FnDecl->isInvalidDecl())
15301 return ExprError();
15302
15303 Expr *Base = nullptr;
15304 // We matched an overloaded operator. Build a call to that
15305 // operator.
15306
15307 OverloadedOperatorKind ChosenOp =
15309
15310 // C++2a [over.match.oper]p9:
15311 // If a rewritten operator== candidate is selected by overload
15312 // resolution for an operator@, its return type shall be cv bool
15313 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15314 !FnDecl->getReturnType()->isBooleanType()) {
15315 bool IsExtension =
15317 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15318 : diag::err_ovl_rewrite_equalequal_not_bool)
15319 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15320 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15321 Diag(FnDecl->getLocation(), diag::note_declared_at);
15322 if (!IsExtension)
15323 return ExprError();
15324 }
15325
15326 if (AllowRewrittenCandidates && !IsReversed &&
15327 CandidateSet.getRewriteInfo().isReversible()) {
15328 // We could have reversed this operator, but didn't. Check if some
15329 // reversed form was a viable candidate, and if so, if it had a
15330 // better conversion for either parameter. If so, this call is
15331 // formally ambiguous, and allowing it is an extension.
15333 for (OverloadCandidate &Cand : CandidateSet) {
15334 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15335 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15336 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15338 *this, OpLoc, Cand.Conversions[ArgIdx],
15339 Best->Conversions[ArgIdx]) ==
15341 AmbiguousWith.push_back(Cand.Function);
15342 break;
15343 }
15344 }
15345 }
15346 }
15347
15348 if (!AmbiguousWith.empty()) {
15349 bool AmbiguousWithSelf =
15350 AmbiguousWith.size() == 1 &&
15351 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15352 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15354 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15355 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15356 if (AmbiguousWithSelf) {
15357 Diag(FnDecl->getLocation(),
15358 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15359 // Mark member== const or provide matching != to disallow reversed
15360 // args. Eg.
15361 // struct S { bool operator==(const S&); };
15362 // S()==S();
15363 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15364 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15365 !MD->isConst() &&
15366 !MD->hasCXXExplicitFunctionObjectParameter() &&
15367 Context.hasSameUnqualifiedType(
15368 MD->getFunctionObjectParameterType(),
15369 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15370 Context.hasSameUnqualifiedType(
15371 MD->getFunctionObjectParameterType(),
15372 Args[0]->getType()) &&
15373 Context.hasSameUnqualifiedType(
15374 MD->getFunctionObjectParameterType(),
15375 Args[1]->getType()))
15376 Diag(FnDecl->getLocation(),
15377 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15378 } else {
15379 Diag(FnDecl->getLocation(),
15380 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15381 for (auto *F : AmbiguousWith)
15382 Diag(F->getLocation(),
15383 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15384 }
15385 }
15386 }
15387
15388 // Check for nonnull = nullable.
15389 // This won't be caught in the arg's initialization: the parameter to
15390 // the assignment operator is not marked nonnull.
15391 if (Op == OO_Equal)
15393 Args[1]->getType(), OpLoc);
15394
15395 // Convert the arguments.
15396 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15397 // Best->Access is only meaningful for class members.
15398 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15399
15400 ExprResult Arg0, Arg1;
15401 unsigned ParamIdx = 0;
15402 if (Method->isExplicitObjectMemberFunction()) {
15403 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15404 ParamIdx = 1;
15405 } else {
15407 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15408 }
15411 Context, FnDecl->getParamDecl(ParamIdx)),
15412 SourceLocation(), Args[1]);
15413 if (Arg0.isInvalid() || Arg1.isInvalid())
15414 return ExprError();
15415
15416 Base = Args[0] = Arg0.getAs<Expr>();
15417 Args[1] = RHS = Arg1.getAs<Expr>();
15418 } else {
15419 // Convert the arguments.
15422 FnDecl->getParamDecl(0)),
15423 SourceLocation(), Args[0]);
15424 if (Arg0.isInvalid())
15425 return ExprError();
15426
15427 ExprResult Arg1 =
15430 FnDecl->getParamDecl(1)),
15431 SourceLocation(), Args[1]);
15432 if (Arg1.isInvalid())
15433 return ExprError();
15434 Args[0] = LHS = Arg0.getAs<Expr>();
15435 Args[1] = RHS = Arg1.getAs<Expr>();
15436 }
15437
15438 // Build the actual expression node.
15439 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15440 Best->FoundDecl, Base,
15441 HadMultipleCandidates, OpLoc);
15442 if (FnExpr.isInvalid())
15443 return ExprError();
15444
15445 // Determine the result type.
15446 QualType ResultTy = FnDecl->getReturnType();
15448 ResultTy = ResultTy.getNonLValueExprType(Context);
15449
15450 CallExpr *TheCall;
15451 ArrayRef<const Expr *> ArgsArray(Args, 2);
15452 const Expr *ImplicitThis = nullptr;
15453
15454 // We always create a CXXOperatorCallExpr, even for explicit object
15455 // members; CodeGen should take care not to emit the this pointer.
15457 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15459 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15460
15461 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15462 Method && Method->isImplicitObjectMemberFunction()) {
15463 // Cut off the implicit 'this'.
15464 ImplicitThis = ArgsArray[0];
15465 ArgsArray = ArgsArray.slice(1);
15466 }
15467
15468 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15469 FnDecl))
15470 return ExprError();
15471
15472 if (Op == OO_Equal) {
15473 // Check for a self move.
15474 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15475 // lifetime check.
15477 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15478 Args[1]);
15479 }
15480 if (ImplicitThis) {
15481 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15482 QualType ThisTypeFromDecl = Context.getPointerType(
15483 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15484
15485 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15486 ThisTypeFromDecl);
15487 }
15488
15489 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15490 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15492
15493 ExprResult R = MaybeBindToTemporary(TheCall);
15494 if (R.isInvalid())
15495 return ExprError();
15496
15497 R = CheckForImmediateInvocation(R, FnDecl);
15498 if (R.isInvalid())
15499 return ExprError();
15500
15501 // For a rewritten candidate, we've already reversed the arguments
15502 // if needed. Perform the rest of the rewrite now.
15503 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15504 (Op == OO_Spaceship && IsReversed)) {
15505 if (Op == OO_ExclaimEqual) {
15506 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15507 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15508 } else {
15509 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15510 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15511 Expr *ZeroLiteral =
15513
15516 Ctx.Entity = FnDecl;
15518
15520 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15521 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15522 /*AllowRewrittenCandidates=*/false);
15523
15525 }
15526 if (R.isInvalid())
15527 return ExprError();
15528 } else {
15529 assert(ChosenOp == Op && "unexpected operator name");
15530 }
15531
15532 // Make a note in the AST if we did any rewriting.
15533 if (Best->RewriteKind != CRK_None)
15534 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15535
15536 return R;
15537 } else {
15538 // We matched a built-in operator. Convert the arguments, then
15539 // break out so that we will build the appropriate built-in
15540 // operator node.
15542 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15545 if (ArgsRes0.isInvalid())
15546 return ExprError();
15547 Args[0] = ArgsRes0.get();
15548
15550 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15553 if (ArgsRes1.isInvalid())
15554 return ExprError();
15555 Args[1] = ArgsRes1.get();
15556 break;
15557 }
15558 }
15559
15560 case OR_No_Viable_Function: {
15561 // C++ [over.match.oper]p9:
15562 // If the operator is the operator , [...] and there are no
15563 // viable functions, then the operator is assumed to be the
15564 // built-in operator and interpreted according to clause 5.
15565 if (Opc == BO_Comma)
15566 break;
15567
15568 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15569 // compare result using '==' and '<'.
15570 if (DefaultedFn && Opc == BO_Cmp) {
15571 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15572 Args[1], DefaultedFn);
15573 if (E.isInvalid() || E.isUsable())
15574 return E;
15575 }
15576
15577 // For class as left operand for assignment or compound assignment
15578 // operator do not fall through to handling in built-in, but report that
15579 // no overloaded assignment operator found
15581 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15582 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15583 Args, OpLoc);
15584 DeferDiagsRAII DDR(*this,
15585 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15586 if (Args[0]->getType()->isRecordType() &&
15587 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15588 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15590 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15591 if (Args[0]->getType()->isIncompleteType()) {
15592 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15593 << Args[0]->getType()
15594 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15595 }
15596 } else {
15597 // This is an erroneous use of an operator which can be overloaded by
15598 // a non-member function. Check for non-member operators which were
15599 // defined too late to be candidates.
15600 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15601 // FIXME: Recover by calling the found function.
15602 return ExprError();
15603
15604 // No viable function; try to create a built-in operation, which will
15605 // produce an error. Then, show the non-viable candidates.
15606 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15607 }
15608 assert(Result.isInvalid() &&
15609 "C++ binary operator overloading is missing candidates!");
15610 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15611 return Result;
15612 }
15613
15614 case OR_Ambiguous:
15615 CandidateSet.NoteCandidates(
15616 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15618 << Args[0]->getType()
15619 << Args[1]->getType()
15620 << Args[0]->getSourceRange()
15621 << Args[1]->getSourceRange()),
15623 OpLoc);
15624 return ExprError();
15625
15626 case OR_Deleted: {
15627 if (isImplicitlyDeleted(Best->Function)) {
15628 FunctionDecl *DeletedFD = Best->Function;
15630 if (DFK.isSpecialMember()) {
15631 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15632 << Args[0]->getType() << DFK.asSpecialMember();
15633 } else {
15634 assert(DFK.isComparison());
15635 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15636 << Args[0]->getType() << DeletedFD;
15637 }
15638
15639 // The user probably meant to call this special member. Just
15640 // explain why it's deleted.
15641 NoteDeletedFunction(DeletedFD);
15642 return ExprError();
15643 }
15644
15645 StringLiteral *Msg = Best->Function->getDeletedMessage();
15646 CandidateSet.NoteCandidates(
15648 OpLoc,
15649 PDiag(diag::err_ovl_deleted_oper)
15650 << getOperatorSpelling(Best->Function->getDeclName()
15651 .getCXXOverloadedOperator())
15652 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15653 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15655 OpLoc);
15656 return ExprError();
15657 }
15658 }
15659
15660 // We matched a built-in operator; build it.
15661 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15662}
15663
15665 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15666 FunctionDecl *DefaultedFn) {
15667 const ComparisonCategoryInfo *Info =
15668 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15669 // If we're not producing a known comparison category type, we can't
15670 // synthesize a three-way comparison. Let the caller diagnose this.
15671 if (!Info)
15672 return ExprResult((Expr*)nullptr);
15673
15674 // If we ever want to perform this synthesis more generally, we will need to
15675 // apply the temporary materialization conversion to the operands.
15676 assert(LHS->isGLValue() && RHS->isGLValue() &&
15677 "cannot use prvalue expressions more than once");
15678 Expr *OrigLHS = LHS;
15679 Expr *OrigRHS = RHS;
15680
15681 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15682 // each of them multiple times below.
15683 LHS = new (Context)
15684 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15685 LHS->getObjectKind(), LHS);
15686 RHS = new (Context)
15687 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15688 RHS->getObjectKind(), RHS);
15689
15690 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15691 DefaultedFn);
15692 if (Eq.isInvalid())
15693 return ExprError();
15694
15695 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15696 true, DefaultedFn);
15697 if (Less.isInvalid())
15698 return ExprError();
15699
15701 if (Info->isPartial()) {
15702 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15703 DefaultedFn);
15704 if (Greater.isInvalid())
15705 return ExprError();
15706 }
15707
15708 // Form the list of comparisons we're going to perform.
15709 struct Comparison {
15710 ExprResult Cmp;
15712 } Comparisons[4] =
15718 };
15719
15720 int I = Info->isPartial() ? 3 : 2;
15721
15722 // Combine the comparisons with suitable conditional expressions.
15724 for (; I >= 0; --I) {
15725 // Build a reference to the comparison category constant.
15726 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15727 // FIXME: Missing a constant for a comparison category. Diagnose this?
15728 if (!VI)
15729 return ExprResult((Expr*)nullptr);
15730 ExprResult ThisResult =
15732 if (ThisResult.isInvalid())
15733 return ExprError();
15734
15735 // Build a conditional unless this is the final case.
15736 if (Result.get()) {
15737 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15738 ThisResult.get(), Result.get());
15739 if (Result.isInvalid())
15740 return ExprError();
15741 } else {
15742 Result = ThisResult;
15743 }
15744 }
15745
15746 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15747 // bind the OpaqueValueExprs before they're (repeatedly) used.
15748 Expr *SyntacticForm = BinaryOperator::Create(
15749 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15750 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15752 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15753 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15754}
15755
15757 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15758 MultiExprArg Args, SourceLocation LParenLoc) {
15759
15760 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15761 unsigned NumParams = Proto->getNumParams();
15762 unsigned NumArgsSlots =
15763 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15764 // Build the full argument list for the method call (the implicit object
15765 // parameter is placed at the beginning of the list).
15766 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15767 bool IsError = false;
15768 // Initialize the implicit object parameter.
15769 // Check the argument types.
15770 for (unsigned i = 0; i != NumParams; i++) {
15771 Expr *Arg;
15772 if (i < Args.size()) {
15773 Arg = Args[i];
15774 ExprResult InputInit =
15776 S.Context, Method->getParamDecl(i)),
15777 SourceLocation(), Arg);
15778 IsError |= InputInit.isInvalid();
15779 Arg = InputInit.getAs<Expr>();
15780 } else {
15781 ExprResult DefArg =
15782 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15783 if (DefArg.isInvalid()) {
15784 IsError = true;
15785 break;
15786 }
15787 Arg = DefArg.getAs<Expr>();
15788 }
15789
15790 MethodArgs.push_back(Arg);
15791 }
15792 return IsError;
15793}
15794
15796 SourceLocation RLoc,
15797 Expr *Base,
15798 MultiExprArg ArgExpr) {
15800 Args.push_back(Base);
15801 for (auto *e : ArgExpr) {
15802 Args.push_back(e);
15803 }
15804 DeclarationName OpName =
15805 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15806
15807 SourceRange Range = ArgExpr.empty()
15808 ? SourceRange{}
15809 : SourceRange(ArgExpr.front()->getBeginLoc(),
15810 ArgExpr.back()->getEndLoc());
15811
15812 // If either side is type-dependent, create an appropriate dependent
15813 // expression.
15815
15816 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15817 // CHECKME: no 'operator' keyword?
15818 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15819 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15821 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15822 if (Fn.isInvalid())
15823 return ExprError();
15824 // Can't add any actual overloads yet
15825
15826 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15827 Context.DependentTy, VK_PRValue, RLoc,
15829 }
15830
15831 // Handle placeholders
15832 UnbridgedCastsSet UnbridgedCasts;
15833 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15834 return ExprError();
15835 }
15836 // Build an empty overload set.
15838
15839 // Subscript can only be overloaded as a member function.
15840
15841 // Add operator candidates that are member functions.
15842 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15843
15844 // Add builtin operator candidates.
15845 if (Args.size() == 2)
15846 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15847
15848 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15849
15850 // Perform overload resolution.
15852 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15853 case OR_Success: {
15854 // We found a built-in operator or an overloaded operator.
15855 FunctionDecl *FnDecl = Best->Function;
15856
15857 if (FnDecl) {
15858 // We matched an overloaded operator. Build a call to that
15859 // operator.
15860
15861 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15862
15863 // Convert the arguments.
15865 SmallVector<Expr *, 2> MethodArgs;
15866
15867 // Initialize the object parameter.
15868 if (Method->isExplicitObjectMemberFunction()) {
15869 ExprResult Res =
15871 if (Res.isInvalid())
15872 return ExprError();
15873 Args[0] = Res.get();
15874 ArgExpr = Args;
15875 } else {
15877 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15878 if (Arg0.isInvalid())
15879 return ExprError();
15880
15881 MethodArgs.push_back(Arg0.get());
15882 }
15883
15885 *this, MethodArgs, Method, ArgExpr, LLoc);
15886 if (IsError)
15887 return ExprError();
15888
15889 // Build the actual expression node.
15890 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15891 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15893 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15894 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15895 if (FnExpr.isInvalid())
15896 return ExprError();
15897
15898 // Determine the result type
15899 QualType ResultTy = FnDecl->getReturnType();
15901 ResultTy = ResultTy.getNonLValueExprType(Context);
15902
15904 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15906
15907 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15908 return ExprError();
15909
15910 if (CheckFunctionCall(Method, TheCall,
15911 Method->getType()->castAs<FunctionProtoType>()))
15912 return ExprError();
15913
15915 FnDecl);
15916 } else {
15917 // We matched a built-in operator. Convert the arguments, then
15918 // break out so that we will build the appropriate built-in
15919 // operator node.
15921 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15924 if (ArgsRes0.isInvalid())
15925 return ExprError();
15926 Args[0] = ArgsRes0.get();
15927
15929 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15932 if (ArgsRes1.isInvalid())
15933 return ExprError();
15934 Args[1] = ArgsRes1.get();
15935
15936 break;
15937 }
15938 }
15939
15940 case OR_No_Viable_Function: {
15942 CandidateSet.empty()
15943 ? (PDiag(diag::err_ovl_no_oper)
15944 << Args[0]->getType() << /*subscript*/ 0
15945 << Args[0]->getSourceRange() << Range)
15946 : (PDiag(diag::err_ovl_no_viable_subscript)
15947 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15948 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15949 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15950 return ExprError();
15951 }
15952
15953 case OR_Ambiguous:
15954 if (Args.size() == 2) {
15955 CandidateSet.NoteCandidates(
15957 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15958 << "[]" << Args[0]->getType() << Args[1]->getType()
15959 << Args[0]->getSourceRange() << Range),
15960 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15961 } else {
15962 CandidateSet.NoteCandidates(
15964 PDiag(diag::err_ovl_ambiguous_subscript_call)
15965 << Args[0]->getType()
15966 << Args[0]->getSourceRange() << Range),
15967 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15968 }
15969 return ExprError();
15970
15971 case OR_Deleted: {
15972 StringLiteral *Msg = Best->Function->getDeletedMessage();
15973 CandidateSet.NoteCandidates(
15975 PDiag(diag::err_ovl_deleted_oper)
15976 << "[]" << (Msg != nullptr)
15977 << (Msg ? Msg->getString() : StringRef())
15978 << Args[0]->getSourceRange() << Range),
15979 *this, OCD_AllCandidates, Args, "[]", LLoc);
15980 return ExprError();
15981 }
15982 }
15983
15984 // We matched a built-in operator; build it.
15985 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15986}
15987
15989 SourceLocation LParenLoc,
15990 MultiExprArg Args,
15991 SourceLocation RParenLoc,
15992 Expr *ExecConfig, bool IsExecConfig,
15993 bool AllowRecovery) {
15994 assert(MemExprE->getType() == Context.BoundMemberTy ||
15995 MemExprE->getType() == Context.OverloadTy);
15996
15997 // Dig out the member expression. This holds both the object
15998 // argument and the member function we're referring to.
15999 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16000
16001 // Determine whether this is a call to a pointer-to-member function.
16002 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16003 assert(op->getType() == Context.BoundMemberTy);
16004 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16005
16006 QualType fnType =
16007 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16008
16009 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16010 QualType resultType = proto->getCallResultType(Context);
16012
16013 // Check that the object type isn't more qualified than the
16014 // member function we're calling.
16015 Qualifiers funcQuals = proto->getMethodQuals();
16016
16017 QualType objectType = op->getLHS()->getType();
16018 if (op->getOpcode() == BO_PtrMemI)
16019 objectType = objectType->castAs<PointerType>()->getPointeeType();
16020 Qualifiers objectQuals = objectType.getQualifiers();
16021
16022 Qualifiers difference = objectQuals - funcQuals;
16023 difference.removeObjCGCAttr();
16024 difference.removeAddressSpace();
16025 if (difference) {
16026 std::string qualsString = difference.getAsString();
16027 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16028 << fnType.getUnqualifiedType()
16029 << qualsString
16030 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16031 }
16032
16034 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16036
16037 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16038 call, nullptr))
16039 return ExprError();
16040
16041 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16042 return ExprError();
16043
16044 if (CheckOtherCall(call, proto))
16045 return ExprError();
16046
16047 return MaybeBindToTemporary(call);
16048 }
16049
16050 // We only try to build a recovery expr at this level if we can preserve
16051 // the return type, otherwise we return ExprError() and let the caller
16052 // recover.
16053 auto BuildRecoveryExpr = [&](QualType Type) {
16054 if (!AllowRecovery)
16055 return ExprError();
16056 std::vector<Expr *> SubExprs = {MemExprE};
16057 llvm::append_range(SubExprs, Args);
16058 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16059 Type);
16060 };
16061 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16062 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16063 RParenLoc, CurFPFeatureOverrides());
16064
16065 UnbridgedCastsSet UnbridgedCasts;
16066 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16067 return ExprError();
16068
16069 MemberExpr *MemExpr;
16070 CXXMethodDecl *Method = nullptr;
16071 bool HadMultipleCandidates = false;
16072 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16073 NestedNameSpecifier Qualifier = std::nullopt;
16074 if (isa<MemberExpr>(NakedMemExpr)) {
16075 MemExpr = cast<MemberExpr>(NakedMemExpr);
16077 FoundDecl = MemExpr->getFoundDecl();
16078 Qualifier = MemExpr->getQualifier();
16079 UnbridgedCasts.restore();
16080 } else {
16081 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16082 Qualifier = UnresExpr->getQualifier();
16083
16084 QualType ObjectType = UnresExpr->getBaseType();
16085 Expr::Classification ObjectClassification
16087 : UnresExpr->getBase()->Classify(Context);
16088
16089 // Add overload candidates
16090 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16092
16093 // FIXME: avoid copy.
16094 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16095 if (UnresExpr->hasExplicitTemplateArgs()) {
16096 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16097 TemplateArgs = &TemplateArgsBuffer;
16098 }
16099
16101 E = UnresExpr->decls_end(); I != E; ++I) {
16102
16103 QualType ExplicitObjectType = ObjectType;
16104
16105 NamedDecl *Func = *I;
16106 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16108 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16109
16110 bool HasExplicitParameter = false;
16111 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16112 M && M->hasCXXExplicitFunctionObjectParameter())
16113 HasExplicitParameter = true;
16114 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16115 M &&
16116 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16117 HasExplicitParameter = true;
16118
16119 if (HasExplicitParameter)
16120 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16121
16122 // Microsoft supports direct constructor calls.
16123 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16125 CandidateSet,
16126 /*SuppressUserConversions*/ false);
16127 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16128 // If explicit template arguments were provided, we can't call a
16129 // non-template member function.
16130 if (TemplateArgs)
16131 continue;
16132
16133 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16134 ObjectClassification, Args, CandidateSet,
16135 /*SuppressUserConversions=*/false);
16136 } else {
16138 I.getPair(), ActingDC, TemplateArgs,
16139 ExplicitObjectType, ObjectClassification,
16140 Args, CandidateSet,
16141 /*SuppressUserConversions=*/false);
16142 }
16143 }
16144
16145 HadMultipleCandidates = (CandidateSet.size() > 1);
16146
16147 DeclarationName DeclName = UnresExpr->getMemberName();
16148
16149 UnbridgedCasts.restore();
16150
16152 bool Succeeded = false;
16153 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16154 Best)) {
16155 case OR_Success:
16156 Method = cast<CXXMethodDecl>(Best->Function);
16157 FoundDecl = Best->FoundDecl;
16158 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16159 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16160 break;
16161 // If FoundDecl is different from Method (such as if one is a template
16162 // and the other a specialization), make sure DiagnoseUseOfDecl is
16163 // called on both.
16164 // FIXME: This would be more comprehensively addressed by modifying
16165 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16166 // being used.
16167 if (Method != FoundDecl.getDecl() &&
16169 break;
16170 Succeeded = true;
16171 break;
16172
16174 CandidateSet.NoteCandidates(
16176 UnresExpr->getMemberLoc(),
16177 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16178 << DeclName << MemExprE->getSourceRange()),
16179 *this, OCD_AllCandidates, Args);
16180 break;
16181 case OR_Ambiguous:
16182 CandidateSet.NoteCandidates(
16183 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16184 PDiag(diag::err_ovl_ambiguous_member_call)
16185 << DeclName << MemExprE->getSourceRange()),
16186 *this, OCD_AmbiguousCandidates, Args);
16187 break;
16188 case OR_Deleted:
16190 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16191 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16192 break;
16193 }
16194 // Overload resolution fails, try to recover.
16195 if (!Succeeded)
16196 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16197
16198 ExprResult Res =
16199 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16200 if (Res.isInvalid())
16201 return ExprError();
16202 MemExprE = Res.get();
16203
16204 // If overload resolution picked a static member
16205 // build a non-member call based on that function.
16206 if (Method->isStatic()) {
16207 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16208 ExecConfig, IsExecConfig);
16209 }
16210
16211 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16212 }
16213
16214 QualType ResultType = Method->getReturnType();
16216 ResultType = ResultType.getNonLValueExprType(Context);
16217
16218 assert(Method && "Member call to something that isn't a method?");
16219 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16220
16221 CallExpr *TheCall = nullptr;
16223 if (Method->isExplicitObjectMemberFunction()) {
16224 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16225 NewArgs))
16226 return ExprError();
16227
16228 // Build the actual expression node.
16229 ExprResult FnExpr =
16230 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16231 HadMultipleCandidates, MemExpr->getExprLoc());
16232 if (FnExpr.isInvalid())
16233 return ExprError();
16234
16235 TheCall =
16236 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16237 CurFPFeatureOverrides(), Proto->getNumParams());
16238 TheCall->setUsesMemberSyntax(true);
16239 } else {
16240 // Convert the object argument (for a non-static member function call).
16242 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16243 if (ObjectArg.isInvalid())
16244 return ExprError();
16245 MemExpr->setBase(ObjectArg.get());
16246 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16247 RParenLoc, CurFPFeatureOverrides(),
16248 Proto->getNumParams());
16249 }
16250
16251 // Check for a valid return type.
16252 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16253 TheCall, Method))
16254 return BuildRecoveryExpr(ResultType);
16255
16256 // Convert the rest of the arguments
16257 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16258 RParenLoc))
16259 return BuildRecoveryExpr(ResultType);
16260
16261 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16262
16263 if (CheckFunctionCall(Method, TheCall, Proto))
16264 return ExprError();
16265
16266 // In the case the method to call was not selected by the overloading
16267 // resolution process, we still need to handle the enable_if attribute. Do
16268 // that here, so it will not hide previous -- and more relevant -- errors.
16269 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16270 if (const EnableIfAttr *Attr =
16271 CheckEnableIf(Method, LParenLoc, Args, true)) {
16272 Diag(MemE->getMemberLoc(),
16273 diag::err_ovl_no_viable_member_function_in_call)
16274 << Method << Method->getSourceRange();
16275 Diag(Method->getLocation(),
16276 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16277 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16278 return ExprError();
16279 }
16280 }
16281
16283 TheCall->getDirectCallee()->isPureVirtual()) {
16284 const FunctionDecl *MD = TheCall->getDirectCallee();
16285
16286 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16288 Diag(MemExpr->getBeginLoc(),
16289 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16291 << MD->getParent();
16292
16293 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16294 if (getLangOpts().AppleKext)
16295 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16296 << MD->getParent() << MD->getDeclName();
16297 }
16298 }
16299
16300 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16301 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16302 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16303 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16304 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16305 MemExpr->getMemberLoc());
16306 }
16307
16309 TheCall->getDirectCallee());
16310}
16311
16314 SourceLocation LParenLoc,
16315 MultiExprArg Args,
16316 SourceLocation RParenLoc) {
16317 if (checkPlaceholderForOverload(*this, Obj))
16318 return ExprError();
16319 ExprResult Object = Obj;
16320
16321 UnbridgedCastsSet UnbridgedCasts;
16322 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16323 return ExprError();
16324
16325 assert(Object.get()->getType()->isRecordType() &&
16326 "Requires object type argument");
16327
16328 // C++ [over.call.object]p1:
16329 // If the primary-expression E in the function call syntax
16330 // evaluates to a class object of type "cv T", then the set of
16331 // candidate functions includes at least the function call
16332 // operators of T. The function call operators of T are obtained by
16333 // ordinary lookup of the name operator() in the context of
16334 // (E).operator().
16335 OverloadCandidateSet CandidateSet(LParenLoc,
16337 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16338
16339 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16340 diag::err_incomplete_object_call, Object.get()))
16341 return true;
16342
16343 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16344 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16347
16348 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16349 Oper != OperEnd; ++Oper) {
16350 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16351 Object.get()->Classify(Context), Args, CandidateSet,
16352 /*SuppressUserConversion=*/false);
16353 }
16354
16355 // When calling a lambda, both the call operator, and
16356 // the conversion operator to function pointer
16357 // are considered. But when constraint checking
16358 // on the call operator fails, it will also fail on the
16359 // conversion operator as the constraints are always the same.
16360 // As the user probably does not intend to perform a surrogate call,
16361 // we filter them out to produce better error diagnostics, ie to avoid
16362 // showing 2 failed overloads instead of one.
16363 bool IgnoreSurrogateFunctions = false;
16364 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16365 const OverloadCandidate &Candidate = *CandidateSet.begin();
16366 if (!Candidate.Viable &&
16368 IgnoreSurrogateFunctions = true;
16369 }
16370
16371 // C++ [over.call.object]p2:
16372 // In addition, for each (non-explicit in C++0x) conversion function
16373 // declared in T of the form
16374 //
16375 // operator conversion-type-id () cv-qualifier;
16376 //
16377 // where cv-qualifier is the same cv-qualification as, or a
16378 // greater cv-qualification than, cv, and where conversion-type-id
16379 // denotes the type "pointer to function of (P1,...,Pn) returning
16380 // R", or the type "reference to pointer to function of
16381 // (P1,...,Pn) returning R", or the type "reference to function
16382 // of (P1,...,Pn) returning R", a surrogate call function [...]
16383 // is also considered as a candidate function. Similarly,
16384 // surrogate call functions are added to the set of candidate
16385 // functions for each conversion function declared in an
16386 // accessible base class provided the function is not hidden
16387 // within T by another intervening declaration.
16388 const auto &Conversions = Record->getVisibleConversionFunctions();
16389 for (auto I = Conversions.begin(), E = Conversions.end();
16390 !IgnoreSurrogateFunctions && I != E; ++I) {
16391 NamedDecl *D = *I;
16392 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16393 if (isa<UsingShadowDecl>(D))
16394 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16395
16396 // Skip over templated conversion functions; they aren't
16397 // surrogates.
16399 continue;
16400
16402 if (!Conv->isExplicit()) {
16403 // Strip the reference type (if any) and then the pointer type (if
16404 // any) to get down to what might be a function type.
16405 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16406 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16407 ConvType = ConvPtrType->getPointeeType();
16408
16409 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16410 {
16411 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16412 Object.get(), Args, CandidateSet);
16413 }
16414 }
16415 }
16416
16417 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16418
16419 // Perform overload resolution.
16421 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16422 Best)) {
16423 case OR_Success:
16424 // Overload resolution succeeded; we'll build the appropriate call
16425 // below.
16426 break;
16427
16428 case OR_No_Viable_Function: {
16430 CandidateSet.empty()
16431 ? (PDiag(diag::err_ovl_no_oper)
16432 << Object.get()->getType() << /*call*/ 1
16433 << Object.get()->getSourceRange())
16434 : (PDiag(diag::err_ovl_no_viable_object_call)
16435 << Object.get()->getType() << Object.get()->getSourceRange());
16436 CandidateSet.NoteCandidates(
16437 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16438 OCD_AllCandidates, Args);
16439 break;
16440 }
16441 case OR_Ambiguous:
16442 if (!R.isAmbiguous())
16443 CandidateSet.NoteCandidates(
16444 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16445 PDiag(diag::err_ovl_ambiguous_object_call)
16446 << Object.get()->getType()
16447 << Object.get()->getSourceRange()),
16448 *this, OCD_AmbiguousCandidates, Args);
16449 break;
16450
16451 case OR_Deleted: {
16452 // FIXME: Is this diagnostic here really necessary? It seems that
16453 // 1. we don't have any tests for this diagnostic, and
16454 // 2. we already issue err_deleted_function_use for this later on anyway.
16455 StringLiteral *Msg = Best->Function->getDeletedMessage();
16456 CandidateSet.NoteCandidates(
16457 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16458 PDiag(diag::err_ovl_deleted_object_call)
16459 << Object.get()->getType() << (Msg != nullptr)
16460 << (Msg ? Msg->getString() : StringRef())
16461 << Object.get()->getSourceRange()),
16462 *this, OCD_AllCandidates, Args);
16463 break;
16464 }
16465 }
16466
16467 if (Best == CandidateSet.end())
16468 return true;
16469
16470 UnbridgedCasts.restore();
16471
16472 if (Best->Function == nullptr) {
16473 // Since there is no function declaration, this is one of the
16474 // surrogate candidates. Dig out the conversion function.
16475 CXXConversionDecl *Conv
16477 Best->Conversions[0].UserDefined.ConversionFunction);
16478
16479 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16480 Best->FoundDecl);
16481 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16482 return ExprError();
16483 assert(Conv == Best->FoundDecl.getDecl() &&
16484 "Found Decl & conversion-to-functionptr should be same, right?!");
16485 // We selected one of the surrogate functions that converts the
16486 // object parameter to a function pointer. Perform the conversion
16487 // on the object argument, then let BuildCallExpr finish the job.
16488
16489 // Create an implicit member expr to refer to the conversion operator.
16490 // and then call it.
16491 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16492 Conv, HadMultipleCandidates);
16493 if (Call.isInvalid())
16494 return ExprError();
16495 // Record usage of conversion in an implicit cast.
16497 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16498 nullptr, VK_PRValue, CurFPFeatureOverrides());
16499
16500 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16501 }
16502
16503 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16504
16505 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16506 // that calls this method, using Object for the implicit object
16507 // parameter and passing along the remaining arguments.
16508 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16509
16510 // An error diagnostic has already been printed when parsing the declaration.
16511 if (Method->isInvalidDecl())
16512 return ExprError();
16513
16514 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16515 unsigned NumParams = Proto->getNumParams();
16516
16517 DeclarationNameInfo OpLocInfo(
16518 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16519 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16520 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16521 Obj, HadMultipleCandidates,
16522 OpLocInfo.getLoc(),
16523 OpLocInfo.getInfo());
16524 if (NewFn.isInvalid())
16525 return true;
16526
16527 SmallVector<Expr *, 8> MethodArgs;
16528 MethodArgs.reserve(NumParams + 1);
16529
16530 bool IsError = false;
16531
16532 // Initialize the object parameter.
16534 if (Method->isExplicitObjectMemberFunction()) {
16535 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16536 } else {
16538 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16539 if (ObjRes.isInvalid())
16540 IsError = true;
16541 else
16542 Object = ObjRes;
16543 MethodArgs.push_back(Object.get());
16544 }
16545
16547 *this, MethodArgs, Method, Args, LParenLoc);
16548
16549 // If this is a variadic call, handle args passed through "...".
16550 if (Proto->isVariadic()) {
16551 // Promote the arguments (C99 6.5.2.2p7).
16552 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16554 Args[i], VariadicCallType::Method, nullptr);
16555 IsError |= Arg.isInvalid();
16556 MethodArgs.push_back(Arg.get());
16557 }
16558 }
16559
16560 if (IsError)
16561 return true;
16562
16563 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16564
16565 // Once we've built TheCall, all of the expressions are properly owned.
16566 QualType ResultTy = Method->getReturnType();
16568 ResultTy = ResultTy.getNonLValueExprType(Context);
16569
16571 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16573
16574 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16575 return true;
16576
16577 if (CheckFunctionCall(Method, TheCall, Proto))
16578 return true;
16579
16581}
16582
16584 SourceLocation OpLoc,
16585 bool *NoArrowOperatorFound) {
16586 assert(Base->getType()->isRecordType() &&
16587 "left-hand side must have class type");
16588
16590 return ExprError();
16591
16592 SourceLocation Loc = Base->getExprLoc();
16593
16594 // C++ [over.ref]p1:
16595 //
16596 // [...] An expression x->m is interpreted as (x.operator->())->m
16597 // for a class object x of type T if T::operator->() exists and if
16598 // the operator is selected as the best match function by the
16599 // overload resolution mechanism (13.3).
16600 DeclarationName OpName =
16601 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16603
16604 if (RequireCompleteType(Loc, Base->getType(),
16605 diag::err_typecheck_incomplete_tag, Base))
16606 return ExprError();
16607
16608 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16609 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16611
16612 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16613 Oper != OperEnd; ++Oper) {
16614 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16615 {}, CandidateSet,
16616 /*SuppressUserConversion=*/false);
16617 }
16618
16619 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16620
16621 // Perform overload resolution.
16623 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16624 case OR_Success:
16625 // Overload resolution succeeded; we'll build the call below.
16626 break;
16627
16628 case OR_No_Viable_Function: {
16629 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16630 if (CandidateSet.empty()) {
16631 QualType BaseType = Base->getType();
16632 if (NoArrowOperatorFound) {
16633 // Report this specific error to the caller instead of emitting a
16634 // diagnostic, as requested.
16635 *NoArrowOperatorFound = true;
16636 return ExprError();
16637 }
16638 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16639 << BaseType << Base->getSourceRange();
16640 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16641 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16642 << FixItHint::CreateReplacement(OpLoc, ".");
16643 }
16644 } else
16645 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16646 << "operator->" << Base->getSourceRange();
16647 CandidateSet.NoteCandidates(*this, Base, Cands);
16648 return ExprError();
16649 }
16650 case OR_Ambiguous:
16651 if (!R.isAmbiguous())
16652 CandidateSet.NoteCandidates(
16653 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16654 << "->" << Base->getType()
16655 << Base->getSourceRange()),
16657 return ExprError();
16658
16659 case OR_Deleted: {
16660 StringLiteral *Msg = Best->Function->getDeletedMessage();
16661 CandidateSet.NoteCandidates(
16662 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16663 << "->" << (Msg != nullptr)
16664 << (Msg ? Msg->getString() : StringRef())
16665 << Base->getSourceRange()),
16666 *this, OCD_AllCandidates, Base);
16667 return ExprError();
16668 }
16669 }
16670
16671 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16672
16673 // Convert the object parameter.
16674 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16675
16676 if (Method->isExplicitObjectMemberFunction()) {
16678 if (R.isInvalid())
16679 return ExprError();
16680 Base = R.get();
16681 } else {
16683 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16684 if (BaseResult.isInvalid())
16685 return ExprError();
16686 Base = BaseResult.get();
16687 }
16688
16689 // Build the operator call.
16690 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16691 Base, HadMultipleCandidates, OpLoc);
16692 if (FnExpr.isInvalid())
16693 return ExprError();
16694
16695 QualType ResultTy = Method->getReturnType();
16697 ResultTy = ResultTy.getNonLValueExprType(Context);
16698
16699 CallExpr *TheCall =
16700 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16701 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16702
16703 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16704 return ExprError();
16705
16706 if (CheckFunctionCall(Method, TheCall,
16707 Method->getType()->castAs<FunctionProtoType>()))
16708 return ExprError();
16709
16711}
16712
16714 DeclarationNameInfo &SuffixInfo,
16715 ArrayRef<Expr*> Args,
16716 SourceLocation LitEndLoc,
16717 TemplateArgumentListInfo *TemplateArgs) {
16718 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16719
16720 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16722 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16723 TemplateArgs);
16724
16725 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16726
16727 // Perform overload resolution. This will usually be trivial, but might need
16728 // to perform substitutions for a literal operator template.
16730 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16731 case OR_Success:
16732 case OR_Deleted:
16733 break;
16734
16736 CandidateSet.NoteCandidates(
16737 PartialDiagnosticAt(UDSuffixLoc,
16738 PDiag(diag::err_ovl_no_viable_function_in_call)
16739 << R.getLookupName()),
16740 *this, OCD_AllCandidates, Args);
16741 return ExprError();
16742
16743 case OR_Ambiguous:
16744 CandidateSet.NoteCandidates(
16745 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16746 << R.getLookupName()),
16747 *this, OCD_AmbiguousCandidates, Args);
16748 return ExprError();
16749 }
16750
16751 FunctionDecl *FD = Best->Function;
16752 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16753 nullptr, HadMultipleCandidates,
16754 SuffixInfo.getLoc(),
16755 SuffixInfo.getInfo());
16756 if (Fn.isInvalid())
16757 return true;
16758
16759 // Check the argument types. This should almost always be a no-op, except
16760 // that array-to-pointer decay is applied to string literals.
16761 Expr *ConvArgs[2];
16762 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16765 SourceLocation(), Args[ArgIdx]);
16766 if (InputInit.isInvalid())
16767 return true;
16768 ConvArgs[ArgIdx] = InputInit.get();
16769 }
16770
16771 QualType ResultTy = FD->getReturnType();
16773 ResultTy = ResultTy.getNonLValueExprType(Context);
16774
16776 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16777 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16778
16779 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16780 return ExprError();
16781
16782 if (CheckFunctionCall(FD, UDL, nullptr))
16783 return ExprError();
16784
16786}
16787
16790 SourceLocation RangeLoc,
16791 const DeclarationNameInfo &NameInfo,
16792 LookupResult &MemberLookup,
16793 OverloadCandidateSet *CandidateSet,
16794 Expr *Range, ExprResult *CallExpr) {
16795 Scope *S = nullptr;
16796
16798 if (!MemberLookup.empty()) {
16799 ExprResult MemberRef =
16800 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16801 /*IsPtr=*/false, CXXScopeSpec(),
16802 /*TemplateKWLoc=*/SourceLocation(),
16803 /*FirstQualifierInScope=*/nullptr,
16804 MemberLookup,
16805 /*TemplateArgs=*/nullptr, S);
16806 if (MemberRef.isInvalid()) {
16807 *CallExpr = ExprError();
16808 return FRS_DiagnosticIssued;
16809 }
16810 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16811 if (CallExpr->isInvalid()) {
16812 *CallExpr = ExprError();
16813 return FRS_DiagnosticIssued;
16814 }
16815 } else {
16816 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16818 NameInfo, UnresolvedSet<0>());
16819 if (FnR.isInvalid())
16820 return FRS_DiagnosticIssued;
16822
16823 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16824 CandidateSet, CallExpr);
16825 if (CandidateSet->empty() || CandidateSetError) {
16826 *CallExpr = ExprError();
16827 return FRS_NoViableFunction;
16828 }
16830 OverloadingResult OverloadResult =
16831 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16832
16833 if (OverloadResult == OR_No_Viable_Function) {
16834 *CallExpr = ExprError();
16835 return FRS_NoViableFunction;
16836 }
16837 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16838 Loc, nullptr, CandidateSet, &Best,
16839 OverloadResult,
16840 /*AllowTypoCorrection=*/false);
16841 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16842 *CallExpr = ExprError();
16843 return FRS_DiagnosticIssued;
16844 }
16845 }
16846 return FRS_Success;
16847}
16848
16850 FunctionDecl *Fn) {
16851 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16852 ExprResult SubExpr =
16853 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16854 if (SubExpr.isInvalid())
16855 return ExprError();
16856 if (SubExpr.get() == PE->getSubExpr())
16857 return PE;
16858
16859 return new (Context)
16860 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16861 }
16862
16863 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16864 ExprResult SubExpr =
16865 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16866 if (SubExpr.isInvalid())
16867 return ExprError();
16868 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16869 SubExpr.get()->getType()) &&
16870 "Implicit cast type cannot be determined from overload");
16871 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16872 if (SubExpr.get() == ICE->getSubExpr())
16873 return ICE;
16874
16875 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16876 SubExpr.get(), nullptr, ICE->getValueKind(),
16878 }
16879
16880 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16881 if (!GSE->isResultDependent()) {
16882 ExprResult SubExpr =
16883 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16884 if (SubExpr.isInvalid())
16885 return ExprError();
16886 if (SubExpr.get() == GSE->getResultExpr())
16887 return GSE;
16888
16889 // Replace the resulting type information before rebuilding the generic
16890 // selection expression.
16891 ArrayRef<Expr *> A = GSE->getAssocExprs();
16892 SmallVector<Expr *, 4> AssocExprs(A);
16893 unsigned ResultIdx = GSE->getResultIndex();
16894 AssocExprs[ResultIdx] = SubExpr.get();
16895
16896 if (GSE->isExprPredicate())
16898 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16899 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16900 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16901 ResultIdx);
16903 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16904 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16905 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16906 ResultIdx);
16907 }
16908 // Rather than fall through to the unreachable, return the original generic
16909 // selection expression.
16910 return GSE;
16911 }
16912
16913 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16914 assert(UnOp->getOpcode() == UO_AddrOf &&
16915 "Can only take the address of an overloaded function");
16916 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16917 if (!Method->isImplicitObjectMemberFunction()) {
16918 // Do nothing: the address of static and
16919 // explicit object member functions is a (non-member) function pointer.
16920 } else {
16921 // Fix the subexpression, which really has to be an
16922 // UnresolvedLookupExpr holding an overloaded member function
16923 // or template.
16924 ExprResult SubExpr =
16925 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16926 if (SubExpr.isInvalid())
16927 return ExprError();
16928 if (SubExpr.get() == UnOp->getSubExpr())
16929 return UnOp;
16930
16931 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16932 SubExpr.get(), Method))
16933 return ExprError();
16934
16935 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16936 "fixed to something other than a decl ref");
16937 NestedNameSpecifier Qualifier =
16938 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16939 assert(Qualifier &&
16940 "fixed to a member ref with no nested name qualifier");
16941
16942 // We have taken the address of a pointer to member
16943 // function. Perform the computation here so that we get the
16944 // appropriate pointer to member type.
16945 QualType MemPtrType = Context.getMemberPointerType(
16946 Fn->getType(), Qualifier,
16947 cast<CXXRecordDecl>(Method->getDeclContext()));
16948 // Under the MS ABI, lock down the inheritance model now.
16949 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16950 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16951
16952 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16953 MemPtrType, VK_PRValue, OK_Ordinary,
16954 UnOp->getOperatorLoc(), false,
16956 }
16957 }
16958 ExprResult SubExpr =
16959 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16960 if (SubExpr.isInvalid())
16961 return ExprError();
16962 if (SubExpr.get() == UnOp->getSubExpr())
16963 return UnOp;
16964
16965 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16966 SubExpr.get());
16967 }
16968
16969 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16970 if (Found.getAccess() == AS_none) {
16972 }
16973 // FIXME: avoid copy.
16974 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16975 if (ULE->hasExplicitTemplateArgs()) {
16976 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16977 TemplateArgs = &TemplateArgsBuffer;
16978 }
16979
16980 QualType Type = Fn->getType();
16981 ExprValueKind ValueKind =
16982 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16983 ? VK_LValue
16984 : VK_PRValue;
16985
16986 // FIXME: Duplicated from BuildDeclarationNameExpr.
16987 if (unsigned BID = Fn->getBuiltinID()) {
16988 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16989 Type = Context.BuiltinFnTy;
16990 ValueKind = VK_PRValue;
16991 }
16992 }
16993
16995 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16996 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16997 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16998 return DRE;
16999 }
17000
17001 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17002 // FIXME: avoid copy.
17003 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17004 if (MemExpr->hasExplicitTemplateArgs()) {
17005 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17006 TemplateArgs = &TemplateArgsBuffer;
17007 }
17008
17009 Expr *Base;
17010
17011 // If we're filling in a static method where we used to have an
17012 // implicit member access, rewrite to a simple decl ref.
17013 if (MemExpr->isImplicitAccess()) {
17014 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17016 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17017 MemExpr->getQualifierLoc(), Found.getDecl(),
17018 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17019 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17020 return DRE;
17021 } else {
17022 SourceLocation Loc = MemExpr->getMemberLoc();
17023 if (MemExpr->getQualifier())
17024 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17025 Base =
17026 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17027 }
17028 } else
17029 Base = MemExpr->getBase();
17030
17031 ExprValueKind valueKind;
17032 QualType type;
17033 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17034 valueKind = VK_LValue;
17035 type = Fn->getType();
17036 } else {
17037 valueKind = VK_PRValue;
17038 type = Context.BoundMemberTy;
17039 }
17040
17041 return BuildMemberExpr(
17042 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17043 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17044 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17045 type, valueKind, OK_Ordinary, TemplateArgs);
17046 }
17047
17048 llvm_unreachable("Invalid reference to overloaded function");
17049}
17050
17056
17057bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17059 if (!PartialOverloading || !Function)
17060 return true;
17061 if (Function->isVariadic())
17062 return false;
17063 if (const auto *Proto =
17064 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17065 if (Proto->isTemplateVariadic())
17066 return false;
17067 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17068 if (const auto *Proto =
17069 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17070 if (Proto->isTemplateVariadic())
17071 return false;
17072 return true;
17073}
17074
17076 DeclarationName Name,
17077 OverloadCandidateSet &CandidateSet,
17078 FunctionDecl *Fn, MultiExprArg Args,
17079 bool IsMember) {
17080 StringLiteral *Msg = Fn->getDeletedMessage();
17081 CandidateSet.NoteCandidates(
17082 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17083 << IsMember << Name << (Msg != nullptr)
17084 << (Msg ? Msg->getString() : StringRef())
17085 << Range),
17086 *this, OCD_AllCandidates, Args);
17087}
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:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:776
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
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:892
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.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType Char8Ty
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
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:3722
QualType getElementType() const
Definition TypeBase.h:3734
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8077
Attr - This represents one attribute.
Definition Attr.h:44
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
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:4038
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:4977
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
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:2943
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2979
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2983
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:2877
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:3060
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3041
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3259
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:3275
QualType getElementType() const
Definition TypeBase.h:3285
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:4999
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
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:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h: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:1270
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:1463
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
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:273
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:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:777
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:762
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:753
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
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:3090
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) 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:3081
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:3334
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4203
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
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:811
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:4042
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:4267
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
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:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4182
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3751
param_iterator param_end()
Definition Decl.h:2787
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3655
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3854
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
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:4253
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4302
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3736
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3122
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4318
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4246
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3858
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4119
bool isConsteval() const
Definition Decl.h:2482
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3699
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:2862
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:3704
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3815
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5758
unsigned getNumParams() const
Definition TypeBase.h:5532
Qualifiers getMethodQuals() const
Definition TypeBase.h:5680
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5694
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:4561
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4632
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4489
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
CallingConv getCallConv() const
Definition TypeBase.h:4805
QualType getReturnType() const
Definition TypeBase.h:4790
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4818
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:4599
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:3787
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:5233
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5348
unsigned getNumInits() const
Definition Expr.h:5263
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5287
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:3617
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:3298
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3487
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3409
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3395
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3375
void setBase(Expr *E)
Definition Expr.h:3374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3493
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3385
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3685
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5449
QualType getPointeeType() const
Definition TypeBase.h:3671
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:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7840
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7896
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:7985
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7954
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7908
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7948
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:7960
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
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:3130
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3282
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3191
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3246
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3243
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3221
decls_iterator decls_begin() const
Definition ExprCXX.h:3223
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3234
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3256
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3252
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3344
decls_iterator decls_end() const
Definition ExprCXX.h:3226
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3240
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3047
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5071
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8356
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8367
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3555
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:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
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:8463
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
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:8432
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8399
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8324
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:8443
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8310
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8218
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8225
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4659
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:3635
Represents a struct/union/class.
Definition Decl.h:4312
field_range fields() const
Definition Decl.h:4515
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
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:374
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:315
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:321
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:228
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:10280
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:6336
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6365
RAII class to control scope of DeferDiags.
Definition Sema.h:10017
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:12404
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12437
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
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:10033
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:9306
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9333
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9318
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9314
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:411
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:1445
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:10363
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10366
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10372
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10370
@ AR_dependent
Definition Sema.h:1660
@ AR_accessible
Definition Sema.h:1658
@ AR_inaccessible
Definition Sema.h:1659
@ AR_delayed
Definition Sema.h:1661
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:2049
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:1283
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:922
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:1490
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:754
ASTContext & getASTContext() const
Definition Sema.h:925
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:10751
@ FRS_DiagnosticIssued
Definition Sema.h:10753
@ FRS_NoViableFunction
Definition Sema.h:10752
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9299
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:10084
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:1191
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3581
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:12118
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:918
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:1281
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:1455
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9298
MemberPointerConversionDirection
Definition Sema.h:10204
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:10391
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.
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:639
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:15389
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:6950
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:1418
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8145
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:13866
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7445
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:224
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:15344
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:6721
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6690
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:10196
SourceManager & SourceMgr
Definition Sema.h:1286
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:515
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6398
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:1425
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:8624
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:362
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
StringRef getString() const
Definition Expr.h:1867
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:3538
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:2485
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isObjCBuiltinType() const
Definition TypeBase.h:8735
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
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:1951
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isFloat16Type() const
Definition TypeBase.h:8880
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:2115
bool isRValueReferenceType() const
Definition TypeBase.h:8547
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:8618
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9031
bool isArrayType() const
Definition TypeBase.h:8614
bool isCharType() const
Definition Type.cpp:2132
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:8939
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2337
bool isPointerType() const
Definition TypeBase.h:8515
bool isArrayParameterType() const
Definition TypeBase.h:8630
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2573
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8705
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:8989
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2168
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8692
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isLValueReferenceType() const
Definition TypeBase.h:8543
bool isBitIntType() const
Definition TypeBase.h:8780
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2411
bool isAnyComplexType() const
Definition TypeBase.h:8650
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8927
bool isHalfType() const
Definition TypeBase.h:8875
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8853
bool isQueueT() const
Definition TypeBase.h:8761
bool isMemberPointerType() const
Definition TypeBase.h:8596
bool isObjCIdType() const
Definition TypeBase.h:8717
bool isMatrixType() const
Definition TypeBase.h:8672
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8753
bool isBFloat16Type() const
Definition TypeBase.h:8892
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool isVectorType() const
Definition TypeBase.h:8654
bool isObjCClassType() const
Definition TypeBase.h:8723
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2594
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8828
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:2253
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8749
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
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:5034
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:3392
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3461
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:4128
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4236
QualType getBaseType() const
Definition ExprCXX.h:4210
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4220
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4201
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4246
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4240
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:723
unsigned getNumElements() const
Definition TypeBase.h:4190
QualType getElementType() const
Definition TypeBase.h:4189
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:1042
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
const FunctionProtoType * T
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:214
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:425
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
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
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:308
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:304
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:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:417
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:412
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:388
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:374
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:410
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:407
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:377
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:371
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:391
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:380
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:394
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:383
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:404
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:398
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:401
@ 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:5867
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:446
__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:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
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:5339
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5344
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1188
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1210
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1237
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
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:10483
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10490
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13013
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13101
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13142
Abstract class used to diagnose incomplete types.
Definition Sema.h:8226
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.