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 (CanonFrom == CanonTo)
2536 return true;
2537
2538 // If we have not converted the argument type to the parameter type,
2539 // this is a bad conversion sequence, unless we're resolving an overload in C.
2540 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2541 return false;
2542
2543 ExprResult ER = ExprResult{From};
2544 AssignConvertType Conv =
2546 /*Diagnose=*/false,
2547 /*DiagnoseCFAudited=*/false,
2548 /*ConvertRHS=*/false);
2549 ImplicitConversionKind SecondConv;
2550 switch (Conv) {
2552 case AssignConvertType::
2553 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2554 SecondConv = ICK_C_Only_Conversion;
2555 break;
2556 // For our purposes, discarding qualifiers is just as bad as using an
2557 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2558 // qualifiers, as well.
2563 break;
2564 default:
2565 return false;
2566 }
2567
2568 // First can only be an lvalue conversion, so we pretend that this was the
2569 // second conversion. First should already be valid from earlier in the
2570 // function.
2571 SCS.Second = SecondConv;
2572 SCS.setToType(1, ToType);
2573
2574 // Third is Identity, because Second should rank us worse than any other
2575 // conversion. This could also be ICK_Qualification, but it's simpler to just
2576 // lump everything in with the second conversion, and we don't gain anything
2577 // from making this ICK_Qualification.
2578 SCS.Third = ICK_Identity;
2579 SCS.setToType(2, ToType);
2580 return true;
2581}
2582
2583static bool
2585 QualType &ToType,
2586 bool InOverloadResolution,
2588 bool CStyle) {
2589
2590 const RecordType *UT = ToType->getAsUnionType();
2591 if (!UT)
2592 return false;
2593 // The field to initialize within the transparent union.
2594 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2595 if (!UD->hasAttr<TransparentUnionAttr>())
2596 return false;
2597 // It's compatible if the expression matches any of the fields.
2598 for (const auto *it : UD->fields()) {
2599 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2600 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2601 ToType = it->getType();
2602 return true;
2603 }
2604 }
2605 return false;
2606}
2607
2608bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2609 const BuiltinType *To = ToType->getAs<BuiltinType>();
2610 // All integers are built-in.
2611 if (!To) {
2612 return false;
2613 }
2614
2615 // An rvalue of type char, signed char, unsigned char, short int, or
2616 // unsigned short int can be converted to an rvalue of type int if
2617 // int can represent all the values of the source type; otherwise,
2618 // the source rvalue can be converted to an rvalue of type unsigned
2619 // int (C++ 4.5p1).
2620 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2621 !FromType->isEnumeralType()) {
2622 if ( // We can promote any signed, promotable integer type to an int
2623 (FromType->isSignedIntegerType() ||
2624 // We can promote any unsigned integer type whose size is
2625 // less than int to an int.
2626 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2627 return To->getKind() == BuiltinType::Int;
2628 }
2629
2630 return To->getKind() == BuiltinType::UInt;
2631 }
2632
2633 // C++11 [conv.prom]p3:
2634 // A prvalue of an unscoped enumeration type whose underlying type is not
2635 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2636 // following types that can represent all the values of the enumeration
2637 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2638 // unsigned int, long int, unsigned long int, long long int, or unsigned
2639 // long long int. If none of the types in that list can represent all the
2640 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2641 // type can be converted to an rvalue a prvalue of the extended integer type
2642 // with lowest integer conversion rank (4.13) greater than the rank of long
2643 // long in which all the values of the enumeration can be represented. If
2644 // there are two such extended types, the signed one is chosen.
2645 // C++11 [conv.prom]p4:
2646 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2647 // can be converted to a prvalue of its underlying type. Moreover, if
2648 // integral promotion can be applied to its underlying type, a prvalue of an
2649 // unscoped enumeration type whose underlying type is fixed can also be
2650 // converted to a prvalue of the promoted underlying type.
2651 if (const auto *FromED = FromType->getAsEnumDecl()) {
2652 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2653 // provided for a scoped enumeration.
2654 if (FromED->isScoped())
2655 return false;
2656
2657 // We can perform an integral promotion to the underlying type of the enum,
2658 // even if that's not the promoted type. Note that the check for promoting
2659 // the underlying type is based on the type alone, and does not consider
2660 // the bitfield-ness of the actual source expression.
2661 if (FromED->isFixed()) {
2662 QualType Underlying = FromED->getIntegerType();
2663 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2664 IsIntegralPromotion(nullptr, Underlying, ToType);
2665 }
2666
2667 // We have already pre-calculated the promotion type, so this is trivial.
2668 if (ToType->isIntegerType() &&
2669 isCompleteType(From->getBeginLoc(), FromType))
2670 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2671
2672 // C++ [conv.prom]p5:
2673 // If the bit-field has an enumerated type, it is treated as any other
2674 // value of that type for promotion purposes.
2675 //
2676 // ... so do not fall through into the bit-field checks below in C++.
2677 if (getLangOpts().CPlusPlus)
2678 return false;
2679 }
2680
2681 // C++0x [conv.prom]p2:
2682 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2683 // to an rvalue a prvalue of the first of the following types that can
2684 // represent all the values of its underlying type: int, unsigned int,
2685 // long int, unsigned long int, long long int, or unsigned long long int.
2686 // If none of the types in that list can represent all the values of its
2687 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2688 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2689 // type.
2690 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2691 ToType->isIntegerType()) {
2692 // Determine whether the type we're converting from is signed or
2693 // unsigned.
2694 bool FromIsSigned = FromType->isSignedIntegerType();
2695 uint64_t FromSize = Context.getTypeSize(FromType);
2696
2697 // The types we'll try to promote to, in the appropriate
2698 // order. Try each of these types.
2699 QualType PromoteTypes[6] = {
2700 Context.IntTy, Context.UnsignedIntTy,
2701 Context.LongTy, Context.UnsignedLongTy ,
2702 Context.LongLongTy, Context.UnsignedLongLongTy
2703 };
2704 for (int Idx = 0; Idx < 6; ++Idx) {
2705 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2706 if (FromSize < ToSize ||
2707 (FromSize == ToSize &&
2708 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2709 // We found the type that we can promote to. If this is the
2710 // type we wanted, we have a promotion. Otherwise, no
2711 // promotion.
2712 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2713 }
2714 }
2715 }
2716
2717 // An rvalue for an integral bit-field (9.6) can be converted to an
2718 // rvalue of type int if int can represent all the values of the
2719 // bit-field; otherwise, it can be converted to unsigned int if
2720 // unsigned int can represent all the values of the bit-field. If
2721 // the bit-field is larger yet, no integral promotion applies to
2722 // it. If the bit-field has an enumerated type, it is treated as any
2723 // other value of that type for promotion purposes (C++ 4.5p3).
2724 // FIXME: We should delay checking of bit-fields until we actually perform the
2725 // conversion.
2726 //
2727 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2728 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2729 // bit-fields and those whose underlying type is larger than int) for GCC
2730 // compatibility.
2731 if (From) {
2732 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2733 std::optional<llvm::APSInt> BitWidth;
2734 if (FromType->isIntegralType(Context) &&
2735 (BitWidth =
2736 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2737 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2738 ToSize = Context.getTypeSize(ToType);
2739
2740 // Are we promoting to an int from a bitfield that fits in an int?
2741 if (*BitWidth < ToSize ||
2742 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2743 return To->getKind() == BuiltinType::Int;
2744 }
2745
2746 // Are we promoting to an unsigned int from an unsigned bitfield
2747 // that fits into an unsigned int?
2748 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2749 return To->getKind() == BuiltinType::UInt;
2750 }
2751
2752 return false;
2753 }
2754 }
2755 }
2756
2757 // An rvalue of type bool can be converted to an rvalue of type int,
2758 // with false becoming zero and true becoming one (C++ 4.5p4).
2759 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2760 return true;
2761 }
2762
2763 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2764 // integral type.
2765 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2766 ToType->isIntegerType())
2767 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2768
2769 return false;
2770}
2771
2773 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2774 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2775 /// An rvalue of type float can be converted to an rvalue of type
2776 /// double. (C++ 4.6p1).
2777 if (FromBuiltin->getKind() == BuiltinType::Float &&
2778 ToBuiltin->getKind() == BuiltinType::Double)
2779 return true;
2780
2781 // C99 6.3.1.5p1:
2782 // When a float is promoted to double or long double, or a
2783 // double is promoted to long double [...].
2784 if (!getLangOpts().CPlusPlus &&
2785 (FromBuiltin->getKind() == BuiltinType::Float ||
2786 FromBuiltin->getKind() == BuiltinType::Double) &&
2787 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2788 ToBuiltin->getKind() == BuiltinType::Float128 ||
2789 ToBuiltin->getKind() == BuiltinType::Ibm128))
2790 return true;
2791
2792 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2793 // or not native half types are enabled.
2794 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2795 (ToBuiltin->getKind() == BuiltinType::Float ||
2796 ToBuiltin->getKind() == BuiltinType::Double))
2797 return true;
2798
2799 // Half can be promoted to float.
2800 if (!getLangOpts().NativeHalfType &&
2801 FromBuiltin->getKind() == BuiltinType::Half &&
2802 ToBuiltin->getKind() == BuiltinType::Float)
2803 return true;
2804 }
2805
2806 return false;
2807}
2808
2810 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2811 if (!FromComplex)
2812 return false;
2813
2814 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2815 if (!ToComplex)
2816 return false;
2817
2818 return IsFloatingPointPromotion(FromComplex->getElementType(),
2819 ToComplex->getElementType()) ||
2820 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2821 ToComplex->getElementType());
2822}
2823
2824/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2825/// the pointer type FromPtr to a pointer to type ToPointee, with the
2826/// same type qualifiers as FromPtr has on its pointee type. ToType,
2827/// if non-empty, will be a pointer to ToType that may or may not have
2828/// the right set of qualifiers on its pointee.
2829///
2830static QualType
2832 QualType ToPointee, QualType ToType,
2833 ASTContext &Context,
2834 bool StripObjCLifetime = false) {
2835 assert((FromPtr->getTypeClass() == Type::Pointer ||
2836 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2837 "Invalid similarly-qualified pointer type");
2838
2839 /// Conversions to 'id' subsume cv-qualifier conversions.
2840 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2841 return ToType.getUnqualifiedType();
2842
2843 QualType CanonFromPointee
2844 = Context.getCanonicalType(FromPtr->getPointeeType());
2845 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2846 Qualifiers Quals = CanonFromPointee.getQualifiers();
2847
2848 if (StripObjCLifetime)
2849 Quals.removeObjCLifetime();
2850
2851 // Exact qualifier match -> return the pointer type we're converting to.
2852 if (CanonToPointee.getLocalQualifiers() == Quals) {
2853 // ToType is exactly what we need. Return it.
2854 if (!ToType.isNull())
2855 return ToType.getUnqualifiedType();
2856
2857 // Build a pointer to ToPointee. It has the right qualifiers
2858 // already.
2859 if (isa<ObjCObjectPointerType>(ToType))
2860 return Context.getObjCObjectPointerType(ToPointee);
2861 return Context.getPointerType(ToPointee);
2862 }
2863
2864 // Just build a canonical type that has the right qualifiers.
2865 QualType QualifiedCanonToPointee
2866 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2867
2868 if (isa<ObjCObjectPointerType>(ToType))
2869 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2870 return Context.getPointerType(QualifiedCanonToPointee);
2871}
2872
2874 bool InOverloadResolution,
2875 ASTContext &Context) {
2876 // Handle value-dependent integral null pointer constants correctly.
2877 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2878 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2880 return !InOverloadResolution;
2881
2882 return Expr->isNullPointerConstant(Context,
2883 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2885}
2886
2888 bool InOverloadResolution,
2889 QualType& ConvertedType,
2890 bool &IncompatibleObjC) {
2891 IncompatibleObjC = false;
2892 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2893 IncompatibleObjC))
2894 return true;
2895
2896 // Conversion from a null pointer constant to any Objective-C pointer type.
2897 if (ToType->isObjCObjectPointerType() &&
2898 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2899 ConvertedType = ToType;
2900 return true;
2901 }
2902
2903 // Blocks: Block pointers can be converted to void*.
2904 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2905 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2906 ConvertedType = ToType;
2907 return true;
2908 }
2909 // Blocks: A null pointer constant can be converted to a block
2910 // pointer type.
2911 if (ToType->isBlockPointerType() &&
2912 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2913 ConvertedType = ToType;
2914 return true;
2915 }
2916
2917 // If the left-hand-side is nullptr_t, the right side can be a null
2918 // pointer constant.
2919 if (ToType->isNullPtrType() &&
2920 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2921 ConvertedType = ToType;
2922 return true;
2923 }
2924
2925 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2926 if (!ToTypePtr)
2927 return false;
2928
2929 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2930 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2931 ConvertedType = ToType;
2932 return true;
2933 }
2934
2935 // Beyond this point, both types need to be pointers
2936 // , including objective-c pointers.
2937 QualType ToPointeeType = ToTypePtr->getPointeeType();
2938 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2939 !getLangOpts().ObjCAutoRefCount) {
2940 ConvertedType = BuildSimilarlyQualifiedPointerType(
2941 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2942 Context);
2943 return true;
2944 }
2945 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2946 if (!FromTypePtr)
2947 return false;
2948
2949 QualType FromPointeeType = FromTypePtr->getPointeeType();
2950
2951 // If the unqualified pointee types are the same, this can't be a
2952 // pointer conversion, so don't do all of the work below.
2953 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2954 return false;
2955
2956 // An rvalue of type "pointer to cv T," where T is an object type,
2957 // can be converted to an rvalue of type "pointer to cv void" (C++
2958 // 4.10p2).
2959 if (FromPointeeType->isIncompleteOrObjectType() &&
2960 ToPointeeType->isVoidType()) {
2961 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2962 ToPointeeType,
2963 ToType, Context,
2964 /*StripObjCLifetime=*/true);
2965 return true;
2966 }
2967
2968 // MSVC allows implicit function to void* type conversion.
2969 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2970 ToPointeeType->isVoidType()) {
2971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2972 ToPointeeType,
2973 ToType, Context);
2974 return true;
2975 }
2976
2977 // When we're overloading in C, we allow a special kind of pointer
2978 // conversion for compatible-but-not-identical pointee types.
2979 if (!getLangOpts().CPlusPlus &&
2980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2982 ToPointeeType,
2983 ToType, Context);
2984 return true;
2985 }
2986
2987 // C++ [conv.ptr]p3:
2988 //
2989 // An rvalue of type "pointer to cv D," where D is a class type,
2990 // can be converted to an rvalue of type "pointer to cv B," where
2991 // B is a base class (clause 10) of D. If B is an inaccessible
2992 // (clause 11) or ambiguous (10.2) base class of D, a program that
2993 // necessitates this conversion is ill-formed. The result of the
2994 // conversion is a pointer to the base class sub-object of the
2995 // derived class object. The null pointer value is converted to
2996 // the null pointer value of the destination type.
2997 //
2998 // Note that we do not check for ambiguity or inaccessibility
2999 // here. That is handled by CheckPointerConversion.
3000 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3001 ToPointeeType->isRecordType() &&
3002 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3003 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3005 ToPointeeType,
3006 ToType, Context);
3007 return true;
3008 }
3009
3010 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3011 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3012 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3013 ToPointeeType,
3014 ToType, Context);
3015 return true;
3016 }
3017
3018 return false;
3019}
3020
3021/// Adopt the given qualifiers for the given type.
3023 Qualifiers TQs = T.getQualifiers();
3024
3025 // Check whether qualifiers already match.
3026 if (TQs == Qs)
3027 return T;
3028
3029 if (Qs.compatiblyIncludes(TQs, Context))
3030 return Context.getQualifiedType(T, Qs);
3031
3032 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3033}
3034
3036 QualType& ConvertedType,
3037 bool &IncompatibleObjC) {
3038 if (!getLangOpts().ObjC)
3039 return false;
3040
3041 // The set of qualifiers on the type we're converting from.
3042 Qualifiers FromQualifiers = FromType.getQualifiers();
3043
3044 // First, we handle all conversions on ObjC object pointer types.
3045 const ObjCObjectPointerType* ToObjCPtr =
3046 ToType->getAs<ObjCObjectPointerType>();
3047 const ObjCObjectPointerType *FromObjCPtr =
3048 FromType->getAs<ObjCObjectPointerType>();
3049
3050 if (ToObjCPtr && FromObjCPtr) {
3051 // If the pointee types are the same (ignoring qualifications),
3052 // then this is not a pointer conversion.
3053 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3054 FromObjCPtr->getPointeeType()))
3055 return false;
3056
3057 // Conversion between Objective-C pointers.
3058 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3059 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3060 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3061 if (getLangOpts().CPlusPlus && LHS && RHS &&
3063 FromObjCPtr->getPointeeType(), getASTContext()))
3064 return false;
3065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3066 ToObjCPtr->getPointeeType(),
3067 ToType, Context);
3068 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3069 return true;
3070 }
3071
3072 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3073 // Okay: this is some kind of implicit downcast of Objective-C
3074 // interfaces, which is permitted. However, we're going to
3075 // complain about it.
3076 IncompatibleObjC = true;
3077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3078 ToObjCPtr->getPointeeType(),
3079 ToType, Context);
3080 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3081 return true;
3082 }
3083 }
3084 // Beyond this point, both types need to be C pointers or block pointers.
3085 QualType ToPointeeType;
3086 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3087 ToPointeeType = ToCPtr->getPointeeType();
3088 else if (const BlockPointerType *ToBlockPtr =
3089 ToType->getAs<BlockPointerType>()) {
3090 // Objective C++: We're able to convert from a pointer to any object
3091 // to a block pointer type.
3092 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3093 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3094 return true;
3095 }
3096 ToPointeeType = ToBlockPtr->getPointeeType();
3097 }
3098 else if (FromType->getAs<BlockPointerType>() &&
3099 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3100 // Objective C++: We're able to convert from a block pointer type to a
3101 // pointer to any object.
3102 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3103 return true;
3104 }
3105 else
3106 return false;
3107
3108 QualType FromPointeeType;
3109 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3110 FromPointeeType = FromCPtr->getPointeeType();
3111 else if (const BlockPointerType *FromBlockPtr =
3112 FromType->getAs<BlockPointerType>())
3113 FromPointeeType = FromBlockPtr->getPointeeType();
3114 else
3115 return false;
3116
3117 // If we have pointers to pointers, recursively check whether this
3118 // is an Objective-C conversion.
3119 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3120 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3121 IncompatibleObjC)) {
3122 // We always complain about this conversion.
3123 IncompatibleObjC = true;
3124 ConvertedType = Context.getPointerType(ConvertedType);
3125 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3126 return true;
3127 }
3128 // Allow conversion of pointee being objective-c pointer to another one;
3129 // as in I* to id.
3130 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3131 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3132 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3133 IncompatibleObjC)) {
3134
3135 ConvertedType = Context.getPointerType(ConvertedType);
3136 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3137 return true;
3138 }
3139
3140 // If we have pointers to functions or blocks, check whether the only
3141 // differences in the argument and result types are in Objective-C
3142 // pointer conversions. If so, we permit the conversion (but
3143 // complain about it).
3144 const FunctionProtoType *FromFunctionType
3145 = FromPointeeType->getAs<FunctionProtoType>();
3146 const FunctionProtoType *ToFunctionType
3147 = ToPointeeType->getAs<FunctionProtoType>();
3148 if (FromFunctionType && ToFunctionType) {
3149 // If the function types are exactly the same, this isn't an
3150 // Objective-C pointer conversion.
3151 if (Context.getCanonicalType(FromPointeeType)
3152 == Context.getCanonicalType(ToPointeeType))
3153 return false;
3154
3155 // Perform the quick checks that will tell us whether these
3156 // function types are obviously different.
3157 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3158 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3159 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3160 return false;
3161
3162 bool HasObjCConversion = false;
3163 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3164 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3165 // Okay, the types match exactly. Nothing to do.
3166 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3167 ToFunctionType->getReturnType(),
3168 ConvertedType, IncompatibleObjC)) {
3169 // Okay, we have an Objective-C pointer conversion.
3170 HasObjCConversion = true;
3171 } else {
3172 // Function types are too different. Abort.
3173 return false;
3174 }
3175
3176 // Check argument types.
3177 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3178 ArgIdx != NumArgs; ++ArgIdx) {
3179 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3180 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3181 if (Context.getCanonicalType(FromArgType)
3182 == Context.getCanonicalType(ToArgType)) {
3183 // Okay, the types match exactly. Nothing to do.
3184 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3185 ConvertedType, IncompatibleObjC)) {
3186 // Okay, we have an Objective-C pointer conversion.
3187 HasObjCConversion = true;
3188 } else {
3189 // Argument types are too different. Abort.
3190 return false;
3191 }
3192 }
3193
3194 if (HasObjCConversion) {
3195 // We had an Objective-C conversion. Allow this pointer
3196 // conversion, but complain about it.
3197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3198 IncompatibleObjC = true;
3199 return true;
3200 }
3201 }
3202
3203 return false;
3204}
3205
3207 QualType& ConvertedType) {
3208 QualType ToPointeeType;
3209 if (const BlockPointerType *ToBlockPtr =
3210 ToType->getAs<BlockPointerType>())
3211 ToPointeeType = ToBlockPtr->getPointeeType();
3212 else
3213 return false;
3214
3215 QualType FromPointeeType;
3216 if (const BlockPointerType *FromBlockPtr =
3217 FromType->getAs<BlockPointerType>())
3218 FromPointeeType = FromBlockPtr->getPointeeType();
3219 else
3220 return false;
3221 // We have pointer to blocks, check whether the only
3222 // differences in the argument and result types are in Objective-C
3223 // pointer conversions. If so, we permit the conversion.
3224
3225 const FunctionProtoType *FromFunctionType
3226 = FromPointeeType->getAs<FunctionProtoType>();
3227 const FunctionProtoType *ToFunctionType
3228 = ToPointeeType->getAs<FunctionProtoType>();
3229
3230 if (!FromFunctionType || !ToFunctionType)
3231 return false;
3232
3233 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3234 return true;
3235
3236 // Perform the quick checks that will tell us whether these
3237 // function types are obviously different.
3238 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3239 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3240 return false;
3241
3242 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3243 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3244 if (FromEInfo != ToEInfo)
3245 return false;
3246
3247 bool IncompatibleObjC = false;
3248 if (Context.hasSameType(FromFunctionType->getReturnType(),
3249 ToFunctionType->getReturnType())) {
3250 // Okay, the types match exactly. Nothing to do.
3251 } else {
3252 QualType RHS = FromFunctionType->getReturnType();
3253 QualType LHS = ToFunctionType->getReturnType();
3254 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3255 !RHS.hasQualifiers() && LHS.hasQualifiers())
3256 LHS = LHS.getUnqualifiedType();
3257
3258 if (Context.hasSameType(RHS,LHS)) {
3259 // OK exact match.
3260 } else if (isObjCPointerConversion(RHS, LHS,
3261 ConvertedType, IncompatibleObjC)) {
3262 if (IncompatibleObjC)
3263 return false;
3264 // Okay, we have an Objective-C pointer conversion.
3265 }
3266 else
3267 return false;
3268 }
3269
3270 // Check argument types.
3271 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3272 ArgIdx != NumArgs; ++ArgIdx) {
3273 IncompatibleObjC = false;
3274 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3275 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3276 if (Context.hasSameType(FromArgType, ToArgType)) {
3277 // Okay, the types match exactly. Nothing to do.
3278 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3279 ConvertedType, IncompatibleObjC)) {
3280 if (IncompatibleObjC)
3281 return false;
3282 // Okay, we have an Objective-C pointer conversion.
3283 } else
3284 // Argument types are too different. Abort.
3285 return false;
3286 }
3287
3289 bool CanUseToFPT, CanUseFromFPT;
3290 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3291 CanUseToFPT, CanUseFromFPT,
3292 NewParamInfos))
3293 return false;
3294
3295 ConvertedType = ToType;
3296 return true;
3297}
3298
3299enum {
3307};
3308
3309/// Attempts to get the FunctionProtoType from a Type. Handles
3310/// MemberFunctionPointers properly.
3312 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3313 return FPT;
3314
3315 if (auto *MPT = FromType->getAs<MemberPointerType>())
3316 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3317
3318 return nullptr;
3319}
3320
3322 QualType FromType, QualType ToType) {
3323 // If either type is not valid, include no extra info.
3324 if (FromType.isNull() || ToType.isNull()) {
3325 PDiag << ft_default;
3326 return;
3327 }
3328
3329 // Get the function type from the pointers.
3330 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3331 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3332 *ToMember = ToType->castAs<MemberPointerType>();
3333 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3334 ToMember->getMostRecentCXXRecordDecl())) {
3336 if (ToMember->isSugared())
3337 PDiag << Context.getCanonicalTagType(
3338 ToMember->getMostRecentCXXRecordDecl());
3339 else
3340 PDiag << ToMember->getQualifier();
3341 if (FromMember->isSugared())
3342 PDiag << Context.getCanonicalTagType(
3343 FromMember->getMostRecentCXXRecordDecl());
3344 else
3345 PDiag << FromMember->getQualifier();
3346 return;
3347 }
3348 FromType = FromMember->getPointeeType();
3349 ToType = ToMember->getPointeeType();
3350 }
3351
3352 if (FromType->isPointerType())
3353 FromType = FromType->getPointeeType();
3354 if (ToType->isPointerType())
3355 ToType = ToType->getPointeeType();
3356
3357 // Remove references.
3358 FromType = FromType.getNonReferenceType();
3359 ToType = ToType.getNonReferenceType();
3360
3361 // Don't print extra info for non-specialized template functions.
3362 if (FromType->isInstantiationDependentType() &&
3363 !FromType->getAs<TemplateSpecializationType>()) {
3364 PDiag << ft_default;
3365 return;
3366 }
3367
3368 // No extra info for same types.
3369 if (Context.hasSameType(FromType, ToType)) {
3370 PDiag << ft_default;
3371 return;
3372 }
3373
3374 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3375 *ToFunction = tryGetFunctionProtoType(ToType);
3376
3377 // Both types need to be function types.
3378 if (!FromFunction || !ToFunction) {
3379 PDiag << ft_default;
3380 return;
3381 }
3382
3383 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3384 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3385 << FromFunction->getNumParams();
3386 return;
3387 }
3388
3389 // Handle different parameter types.
3390 unsigned ArgPos;
3391 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3392 PDiag << ft_parameter_mismatch << ArgPos + 1
3393 << ToFunction->getParamType(ArgPos)
3394 << FromFunction->getParamType(ArgPos);
3395 return;
3396 }
3397
3398 // Handle different return type.
3399 if (!Context.hasSameType(FromFunction->getReturnType(),
3400 ToFunction->getReturnType())) {
3401 PDiag << ft_return_type << ToFunction->getReturnType()
3402 << FromFunction->getReturnType();
3403 return;
3404 }
3405
3406 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3407 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3408 << FromFunction->getMethodQuals();
3409 return;
3410 }
3411
3412 // Handle exception specification differences on canonical type (in C++17
3413 // onwards).
3415 ->isNothrow() !=
3416 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3417 ->isNothrow()) {
3418 PDiag << ft_noexcept;
3419 return;
3420 }
3421
3422 // Unable to find a difference, so add no extra info.
3423 PDiag << ft_default;
3424}
3425
3427 ArrayRef<QualType> New, unsigned *ArgPos,
3428 bool Reversed) {
3429 assert(llvm::size(Old) == llvm::size(New) &&
3430 "Can't compare parameters of functions with different number of "
3431 "parameters!");
3432
3433 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3434 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3435 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3436
3437 // Ignore address spaces in pointee type. This is to disallow overloading
3438 // on __ptr32/__ptr64 address spaces.
3439 QualType OldType =
3440 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3441 QualType NewType =
3442 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3443
3444 if (!Context.hasSameType(OldType, NewType)) {
3445 if (ArgPos)
3446 *ArgPos = Idx;
3447 return false;
3448 }
3449 }
3450 return true;
3451}
3452
3454 const FunctionProtoType *NewType,
3455 unsigned *ArgPos, bool Reversed) {
3456 return FunctionParamTypesAreEqual(OldType->param_types(),
3457 NewType->param_types(), ArgPos, Reversed);
3458}
3459
3461 const FunctionDecl *NewFunction,
3462 unsigned *ArgPos,
3463 bool Reversed) {
3464
3465 if (OldFunction->getNumNonObjectParams() !=
3466 NewFunction->getNumNonObjectParams())
3467 return false;
3468
3469 unsigned OldIgnore =
3471 unsigned NewIgnore =
3473
3474 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3475 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3476
3477 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3478 NewPT->param_types().slice(NewIgnore),
3479 ArgPos, Reversed);
3480}
3481
3483 CastKind &Kind,
3484 CXXCastPath& BasePath,
3485 bool IgnoreBaseAccess,
3486 bool Diagnose) {
3487 QualType FromType = From->getType();
3488 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3489
3490 Kind = CK_BitCast;
3491
3492 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3495 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3496 DiagRuntimeBehavior(From->getExprLoc(), From,
3497 PDiag(diag::warn_impcast_bool_to_null_pointer)
3498 << ToType << From->getSourceRange());
3499 else if (!isUnevaluatedContext())
3500 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3501 << ToType << From->getSourceRange();
3502 }
3503 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3504 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3505 QualType FromPointeeType = FromPtrType->getPointeeType(),
3506 ToPointeeType = ToPtrType->getPointeeType();
3507
3508 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3509 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3510 // We must have a derived-to-base conversion. Check an
3511 // ambiguous or inaccessible conversion.
3512 unsigned InaccessibleID = 0;
3513 unsigned AmbiguousID = 0;
3514 if (Diagnose) {
3515 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3516 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3517 }
3519 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3520 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3521 &BasePath, IgnoreBaseAccess))
3522 return true;
3523
3524 // The conversion was successful.
3525 Kind = CK_DerivedToBase;
3526 }
3527
3528 if (Diagnose && !IsCStyleOrFunctionalCast &&
3529 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3530 assert(getLangOpts().MSVCCompat &&
3531 "this should only be possible with MSVCCompat!");
3532 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3533 << From->getSourceRange();
3534 }
3535 }
3536 } else if (const ObjCObjectPointerType *ToPtrType =
3537 ToType->getAs<ObjCObjectPointerType>()) {
3538 if (const ObjCObjectPointerType *FromPtrType =
3539 FromType->getAs<ObjCObjectPointerType>()) {
3540 // Objective-C++ conversions are always okay.
3541 // FIXME: We should have a different class of conversions for the
3542 // Objective-C++ implicit conversions.
3543 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3544 return false;
3545 } else if (FromType->isBlockPointerType()) {
3546 Kind = CK_BlockPointerToObjCPointerCast;
3547 } else {
3548 Kind = CK_CPointerToObjCPointerCast;
3549 }
3550 } else if (ToType->isBlockPointerType()) {
3551 if (!FromType->isBlockPointerType())
3552 Kind = CK_AnyPointerToBlockPointerCast;
3553 }
3554
3555 // We shouldn't fall into this case unless it's valid for other
3556 // reasons.
3558 Kind = CK_NullToPointer;
3559
3560 return false;
3561}
3562
3564 QualType ToType,
3565 bool InOverloadResolution,
3566 QualType &ConvertedType) {
3567 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3568 if (!ToTypePtr)
3569 return false;
3570
3571 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3573 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3575 ConvertedType = ToType;
3576 return true;
3577 }
3578
3579 // Otherwise, both types have to be member pointers.
3580 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3581 if (!FromTypePtr)
3582 return false;
3583
3584 // A pointer to member of B can be converted to a pointer to member of D,
3585 // where D is derived from B (C++ 4.11p2).
3586 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3587 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3588
3589 if (!declaresSameEntity(FromClass, ToClass) &&
3590 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3591 ConvertedType = Context.getMemberPointerType(
3592 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3593 return true;
3594 }
3595
3596 return false;
3597}
3598
3600 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3601 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3602 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3603 // Lock down the inheritance model right now in MS ABI, whether or not the
3604 // pointee types are the same.
3605 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3606 (void)isCompleteType(CheckLoc, FromType);
3607 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3608 }
3609
3610 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3611 if (!FromPtrType) {
3612 // This must be a null pointer to member pointer conversion
3613 Kind = CK_NullToMemberPointer;
3615 }
3616
3617 // T == T, modulo cv
3619 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3620 ToPtrType->getPointeeType()))
3622
3623 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3624 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3625
3626 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3627 const CXXRecordDecl *Cls) {
3628 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3629 PD << Qual;
3630 else
3631 PD << Context.getCanonicalTagType(Cls);
3632 };
3633 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3634 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3635 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3636 return PD;
3637 };
3638
3639 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3641 std::swap(Base, Derived);
3642
3643 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3644 /*DetectVirtual=*/true);
3645 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3647
3648 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3649 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3650 PD << int(Direction);
3651 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3652 Diag(CheckLoc, PD);
3654 }
3655
3656 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3657 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3658 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3659 Diag(CheckLoc, PD);
3661 }
3662
3663 // Must be a base to derived member conversion.
3664 BuildBasePathArray(Paths, BasePath);
3666 ? CK_DerivedToBaseMemberPointer
3667 : CK_BaseToDerivedMemberPointer;
3668
3669 if (!IgnoreBaseAccess)
3670 switch (CheckBaseClassAccess(
3671 CheckLoc, Base, Derived, Paths.front(),
3673 ? diag::err_upcast_to_inaccessible_base
3674 : diag::err_downcast_from_inaccessible_base,
3675 [&](PartialDiagnostic &PD) {
3676 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3677 DerivedQual = ToPtrType->getQualifier();
3678 if (Direction == MemberPointerConversionDirection::Upcast)
3679 std::swap(BaseQual, DerivedQual);
3680 DiagCls(PD, DerivedQual, Derived);
3681 DiagCls(PD, BaseQual, Base);
3682 })) {
3684 case Sema::AR_delayed:
3685 case Sema::AR_dependent:
3686 // Optimistically assume that the delayed and dependent cases
3687 // will work out.
3688 break;
3689
3692 }
3693
3695}
3696
3697/// Determine whether the lifetime conversion between the two given
3698/// qualifiers sets is nontrivial.
3700 Qualifiers ToQuals) {
3701 // Converting anything to const __unsafe_unretained is trivial.
3702 if (ToQuals.hasConst() &&
3704 return false;
3705
3706 return true;
3707}
3708
3709/// Perform a single iteration of the loop for checking if a qualification
3710/// conversion is valid.
3711///
3712/// Specifically, check whether any change between the qualifiers of \p
3713/// FromType and \p ToType is permissible, given knowledge about whether every
3714/// outer layer is const-qualified.
3716 bool CStyle, bool IsTopLevel,
3717 bool &PreviousToQualsIncludeConst,
3718 bool &ObjCLifetimeConversion,
3719 const ASTContext &Ctx) {
3720 Qualifiers FromQuals = FromType.getQualifiers();
3721 Qualifiers ToQuals = ToType.getQualifiers();
3722
3723 // Ignore __unaligned qualifier.
3724 FromQuals.removeUnaligned();
3725
3726 // Objective-C ARC:
3727 // Check Objective-C lifetime conversions.
3728 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3729 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3730 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3731 ObjCLifetimeConversion = true;
3732 FromQuals.removeObjCLifetime();
3733 ToQuals.removeObjCLifetime();
3734 } else {
3735 // Qualification conversions cannot cast between different
3736 // Objective-C lifetime qualifiers.
3737 return false;
3738 }
3739 }
3740
3741 // Allow addition/removal of GC attributes but not changing GC attributes.
3742 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3743 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3744 FromQuals.removeObjCGCAttr();
3745 ToQuals.removeObjCGCAttr();
3746 }
3747
3748 // __ptrauth qualifiers must match exactly.
3749 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3750 return false;
3751
3752 // -- for every j > 0, if const is in cv 1,j then const is in cv
3753 // 2,j, and similarly for volatile.
3754 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3755 return false;
3756
3757 // If address spaces mismatch:
3758 // - in top level it is only valid to convert to addr space that is a
3759 // superset in all cases apart from C-style casts where we allow
3760 // conversions between overlapping address spaces.
3761 // - in non-top levels it is not a valid conversion.
3762 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3763 (!IsTopLevel ||
3764 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3765 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3766 return false;
3767
3768 // -- if the cv 1,j and cv 2,j are different, then const is in
3769 // every cv for 0 < k < j.
3770 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3771 !PreviousToQualsIncludeConst)
3772 return false;
3773
3774 // The following wording is from C++20, where the result of the conversion
3775 // is T3, not T2.
3776 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3777 // "array of unknown bound of"
3778 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3779 return false;
3780
3781 // -- if the resulting P3,i is different from P1,i [...], then const is
3782 // added to every cv 3_k for 0 < k < i.
3783 if (!CStyle && FromType->isConstantArrayType() &&
3784 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3785 return false;
3786
3787 // Keep track of whether all prior cv-qualifiers in the "to" type
3788 // include const.
3789 PreviousToQualsIncludeConst =
3790 PreviousToQualsIncludeConst && ToQuals.hasConst();
3791 return true;
3792}
3793
3794bool
3796 bool CStyle, bool &ObjCLifetimeConversion) {
3797 FromType = Context.getCanonicalType(FromType);
3798 ToType = Context.getCanonicalType(ToType);
3799 ObjCLifetimeConversion = false;
3800
3801 // If FromType and ToType are the same type, this is not a
3802 // qualification conversion.
3803 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3804 return false;
3805
3806 // (C++ 4.4p4):
3807 // A conversion can add cv-qualifiers at levels other than the first
3808 // in multi-level pointers, subject to the following rules: [...]
3809 bool PreviousToQualsIncludeConst = true;
3810 bool UnwrappedAnyPointer = false;
3811 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3812 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3813 !UnwrappedAnyPointer,
3814 PreviousToQualsIncludeConst,
3815 ObjCLifetimeConversion, getASTContext()))
3816 return false;
3817 UnwrappedAnyPointer = true;
3818 }
3819
3820 // We are left with FromType and ToType being the pointee types
3821 // after unwrapping the original FromType and ToType the same number
3822 // of times. If we unwrapped any pointers, and if FromType and
3823 // ToType have the same unqualified type (since we checked
3824 // qualifiers above), then this is a qualification conversion.
3825 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3826}
3827
3828/// - Determine whether this is a conversion from a scalar type to an
3829/// atomic type.
3830///
3831/// If successful, updates \c SCS's second and third steps in the conversion
3832/// sequence to finish the conversion.
3833static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3834 bool InOverloadResolution,
3836 bool CStyle) {
3837 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3838 if (!ToAtomic)
3839 return false;
3840
3842 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3843 InOverloadResolution, InnerSCS,
3844 CStyle, /*AllowObjCWritebackConversion=*/false))
3845 return false;
3846
3847 SCS.Second = InnerSCS.Second;
3848 SCS.setToType(1, InnerSCS.getToType(1));
3849 SCS.Third = InnerSCS.Third;
3852 SCS.setToType(2, InnerSCS.getToType(2));
3853 return true;
3854}
3855
3858 QualType Type) {
3859 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3860 if (CtorType->getNumParams() > 0) {
3861 QualType FirstArg = CtorType->getParamType(0);
3862 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3863 return true;
3864 }
3865 return false;
3866}
3867
3868static OverloadingResult
3870 CXXRecordDecl *To,
3872 OverloadCandidateSet &CandidateSet,
3873 bool AllowExplicit) {
3875 for (auto *D : S.LookupConstructors(To)) {
3876 auto Info = getConstructorInfo(D);
3877 if (!Info)
3878 continue;
3879
3880 bool Usable = !Info.Constructor->isInvalidDecl() &&
3881 S.isInitListConstructor(Info.Constructor);
3882 if (Usable) {
3883 bool SuppressUserConversions = false;
3884 if (Info.ConstructorTmpl)
3885 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3886 /*ExplicitArgs*/ nullptr, From,
3887 CandidateSet, SuppressUserConversions,
3888 /*PartialOverloading*/ false,
3889 AllowExplicit);
3890 else
3891 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3892 CandidateSet, SuppressUserConversions,
3893 /*PartialOverloading*/ false, AllowExplicit);
3894 }
3895 }
3896
3897 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3898
3900 switch (auto Result =
3901 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3902 case OR_Deleted:
3903 case OR_Success: {
3904 // Record the standard conversion we used and the conversion function.
3906 QualType ThisType = Constructor->getFunctionObjectParameterType();
3907 // Initializer lists don't have conversions as such.
3909 User.HadMultipleCandidates = HadMultipleCandidates;
3911 User.FoundConversionFunction = Best->FoundDecl;
3913 User.After.setFromType(ThisType);
3914 User.After.setAllToTypes(ToType);
3915 return Result;
3916 }
3917
3919 return OR_No_Viable_Function;
3920 case OR_Ambiguous:
3921 return OR_Ambiguous;
3922 }
3923
3924 llvm_unreachable("Invalid OverloadResult!");
3925}
3926
3927/// Determines whether there is a user-defined conversion sequence
3928/// (C++ [over.ics.user]) that converts expression From to the type
3929/// ToType. If such a conversion exists, User will contain the
3930/// user-defined conversion sequence that performs such a conversion
3931/// and this routine will return true. Otherwise, this routine returns
3932/// false and User is unspecified.
3933///
3934/// \param AllowExplicit true if the conversion should consider C++0x
3935/// "explicit" conversion functions as well as non-explicit conversion
3936/// functions (C++0x [class.conv.fct]p2).
3937///
3938/// \param AllowObjCConversionOnExplicit true if the conversion should
3939/// allow an extra Objective-C pointer conversion on uses of explicit
3940/// constructors. Requires \c AllowExplicit to also be set.
3941static OverloadingResult
3944 OverloadCandidateSet &CandidateSet,
3945 AllowedExplicit AllowExplicit,
3946 bool AllowObjCConversionOnExplicit) {
3947 assert(AllowExplicit != AllowedExplicit::None ||
3948 !AllowObjCConversionOnExplicit);
3950
3951 // Whether we will only visit constructors.
3952 bool ConstructorsOnly = false;
3953
3954 // If the type we are conversion to is a class type, enumerate its
3955 // constructors.
3956 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3957 // C++ [over.match.ctor]p1:
3958 // When objects of class type are direct-initialized (8.5), or
3959 // copy-initialized from an expression of the same or a
3960 // derived class type (8.5), overload resolution selects the
3961 // constructor. [...] For copy-initialization, the candidate
3962 // functions are all the converting constructors (12.3.1) of
3963 // that class. The argument list is the expression-list within
3964 // the parentheses of the initializer.
3965 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3966 (From->getType()->isRecordType() &&
3967 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3968 ConstructorsOnly = true;
3969
3970 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3971 // We're not going to find any constructors.
3972 } else if (auto *ToRecordDecl =
3973 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3974 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
3975
3976 Expr **Args = &From;
3977 unsigned NumArgs = 1;
3978 bool ListInitializing = false;
3979 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3980 // But first, see if there is an init-list-constructor that will work.
3982 S, From, ToType, ToRecordDecl, User, CandidateSet,
3983 AllowExplicit == AllowedExplicit::All);
3984 if (Result != OR_No_Viable_Function)
3985 return Result;
3986 // Never mind.
3987 CandidateSet.clear(
3989
3990 // If we're list-initializing, we pass the individual elements as
3991 // arguments, not the entire list.
3992 Args = InitList->getInits();
3993 NumArgs = InitList->getNumInits();
3994 ListInitializing = true;
3995 }
3996
3997 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3998 auto Info = getConstructorInfo(D);
3999 if (!Info)
4000 continue;
4001
4002 bool Usable = !Info.Constructor->isInvalidDecl();
4003 if (!ListInitializing)
4004 Usable = Usable && Info.Constructor->isConvertingConstructor(
4005 /*AllowExplicit*/ true);
4006 if (Usable) {
4007 bool SuppressUserConversions = !ConstructorsOnly;
4008 // C++20 [over.best.ics.general]/4.5:
4009 // if the target is the first parameter of a constructor [of class
4010 // X] and the constructor [...] is a candidate by [...] the second
4011 // phase of [over.match.list] when the initializer list has exactly
4012 // one element that is itself an initializer list, [...] and the
4013 // conversion is to X or reference to cv X, user-defined conversion
4014 // sequences are not considered.
4015 if (SuppressUserConversions && ListInitializing) {
4016 SuppressUserConversions =
4017 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4018 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4019 ToType);
4020 }
4021 if (Info.ConstructorTmpl)
4023 Info.ConstructorTmpl, Info.FoundDecl,
4024 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4025 CandidateSet, SuppressUserConversions,
4026 /*PartialOverloading*/ false,
4027 AllowExplicit == AllowedExplicit::All);
4028 else
4029 // Allow one user-defined conversion when user specifies a
4030 // From->ToType conversion via an static cast (c-style, etc).
4031 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4032 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4033 SuppressUserConversions,
4034 /*PartialOverloading*/ false,
4035 AllowExplicit == AllowedExplicit::All);
4036 }
4037 }
4038 }
4039 }
4040
4041 // Enumerate conversion functions, if we're allowed to.
4042 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4043 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4044 // No conversion functions from incomplete types.
4045 } else if (const RecordType *FromRecordType =
4046 From->getType()->getAsCanonical<RecordType>()) {
4047 if (auto *FromRecordDecl =
4048 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4049 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4050 // Add all of the conversion functions as candidates.
4051 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4052 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4053 DeclAccessPair FoundDecl = I.getPair();
4054 NamedDecl *D = FoundDecl.getDecl();
4055 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4056 if (isa<UsingShadowDecl>(D))
4057 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4058
4059 CXXConversionDecl *Conv;
4060 FunctionTemplateDecl *ConvTemplate;
4061 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4062 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4063 else
4064 Conv = cast<CXXConversionDecl>(D);
4065
4066 if (ConvTemplate)
4068 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4069 CandidateSet, AllowObjCConversionOnExplicit,
4070 AllowExplicit != AllowedExplicit::None);
4071 else
4072 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4073 CandidateSet, AllowObjCConversionOnExplicit,
4074 AllowExplicit != AllowedExplicit::None);
4075 }
4076 }
4077 }
4078
4079 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4080
4082 switch (auto Result =
4083 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4084 case OR_Success:
4085 case OR_Deleted:
4086 // Record the standard conversion we used and the conversion function.
4088 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4089 // C++ [over.ics.user]p1:
4090 // If the user-defined conversion is specified by a
4091 // constructor (12.3.1), the initial standard conversion
4092 // sequence converts the source type to the type required by
4093 // the argument of the constructor.
4094 //
4095 if (isa<InitListExpr>(From)) {
4096 // Initializer lists don't have conversions as such.
4098 User.Before.FromBracedInitList = true;
4099 } else {
4100 if (Best->Conversions[0].isEllipsis())
4101 User.EllipsisConversion = true;
4102 else {
4103 User.Before = Best->Conversions[0].Standard;
4104 User.EllipsisConversion = false;
4105 }
4106 }
4107 User.HadMultipleCandidates = HadMultipleCandidates;
4109 User.FoundConversionFunction = Best->FoundDecl;
4111 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4112 User.After.setAllToTypes(ToType);
4113 return Result;
4114 }
4115 if (CXXConversionDecl *Conversion
4116 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4117
4118 assert(Best->HasFinalConversion);
4119
4120 // C++ [over.ics.user]p1:
4121 //
4122 // [...] If the user-defined conversion is specified by a
4123 // conversion function (12.3.2), the initial standard
4124 // conversion sequence converts the source type to the
4125 // implicit object parameter of the conversion function.
4126 User.Before = Best->Conversions[0].Standard;
4127 User.HadMultipleCandidates = HadMultipleCandidates;
4128 User.ConversionFunction = Conversion;
4129 User.FoundConversionFunction = Best->FoundDecl;
4130 User.EllipsisConversion = false;
4131
4132 // C++ [over.ics.user]p2:
4133 // The second standard conversion sequence converts the
4134 // result of the user-defined conversion to the target type
4135 // for the sequence. Since an implicit conversion sequence
4136 // is an initialization, the special rules for
4137 // initialization by user-defined conversion apply when
4138 // selecting the best user-defined conversion for a
4139 // user-defined conversion sequence (see 13.3.3 and
4140 // 13.3.3.1).
4141 User.After = Best->FinalConversion;
4142 return Result;
4143 }
4144 llvm_unreachable("Not a constructor or conversion function?");
4145
4147 return OR_No_Viable_Function;
4148
4149 case OR_Ambiguous:
4150 return OR_Ambiguous;
4151 }
4152
4153 llvm_unreachable("Invalid OverloadResult!");
4154}
4155
4156bool
4159 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4161 OverloadingResult OvResult =
4162 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4163 CandidateSet, AllowedExplicit::None, false);
4164
4165 if (!(OvResult == OR_Ambiguous ||
4166 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4167 return false;
4168
4169 auto Cands = CandidateSet.CompleteCandidates(
4170 *this,
4172 From);
4173 if (OvResult == OR_Ambiguous)
4174 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4175 << From->getType() << ToType << From->getSourceRange();
4176 else { // OR_No_Viable_Function && !CandidateSet.empty()
4177 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4178 diag::err_typecheck_nonviable_condition_incomplete,
4179 From->getType(), From->getSourceRange()))
4180 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4181 << false << From->getType() << From->getSourceRange() << ToType;
4182 }
4183
4184 CandidateSet.NoteCandidates(
4185 *this, From, Cands);
4186 return true;
4187}
4188
4189// Helper for compareConversionFunctions that gets the FunctionType that the
4190// conversion-operator return value 'points' to, or nullptr.
4191static const FunctionType *
4193 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4194 const PointerType *RetPtrTy =
4195 ConvFuncTy->getReturnType()->getAs<PointerType>();
4196
4197 if (!RetPtrTy)
4198 return nullptr;
4199
4200 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4201}
4202
4203/// Compare the user-defined conversion functions or constructors
4204/// of two user-defined conversion sequences to determine whether any ordering
4205/// is possible.
4208 FunctionDecl *Function2) {
4209 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4210 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4211 if (!Conv1 || !Conv2)
4213
4214 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4216
4217 // Objective-C++:
4218 // If both conversion functions are implicitly-declared conversions from
4219 // a lambda closure type to a function pointer and a block pointer,
4220 // respectively, always prefer the conversion to a function pointer,
4221 // because the function pointer is more lightweight and is more likely
4222 // to keep code working.
4223 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4224 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4225 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4226 if (Block1 != Block2)
4227 return Block1 ? ImplicitConversionSequence::Worse
4229 }
4230
4231 // In order to support multiple calling conventions for the lambda conversion
4232 // operator (such as when the free and member function calling convention is
4233 // different), prefer the 'free' mechanism, followed by the calling-convention
4234 // of operator(). The latter is in place to support the MSVC-like solution of
4235 // defining ALL of the possible conversions in regards to calling-convention.
4236 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4237 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4238
4239 if (Conv1FuncRet && Conv2FuncRet &&
4240 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4241 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4242 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4243
4244 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4245 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4246
4247 CallingConv CallOpCC =
4248 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4250 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4252 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4253
4254 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4255 for (CallingConv CC : PrefOrder) {
4256 if (Conv1CC == CC)
4258 if (Conv2CC == CC)
4260 }
4261 }
4262
4264}
4265
4272
4273/// CompareImplicitConversionSequences - Compare two implicit
4274/// conversion sequences to determine whether one is better than the
4275/// other or if they are indistinguishable (C++ 13.3.3.2).
4278 const ImplicitConversionSequence& ICS1,
4279 const ImplicitConversionSequence& ICS2)
4280{
4281 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4282 // conversion sequences (as defined in 13.3.3.1)
4283 // -- a standard conversion sequence (13.3.3.1.1) is a better
4284 // conversion sequence than a user-defined conversion sequence or
4285 // an ellipsis conversion sequence, and
4286 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4287 // conversion sequence than an ellipsis conversion sequence
4288 // (13.3.3.1.3).
4289 //
4290 // C++0x [over.best.ics]p10:
4291 // For the purpose of ranking implicit conversion sequences as
4292 // described in 13.3.3.2, the ambiguous conversion sequence is
4293 // treated as a user-defined sequence that is indistinguishable
4294 // from any other user-defined conversion sequence.
4295
4296 // String literal to 'char *' conversion has been deprecated in C++03. It has
4297 // been removed from C++11. We still accept this conversion, if it happens at
4298 // the best viable function. Otherwise, this conversion is considered worse
4299 // than ellipsis conversion. Consider this as an extension; this is not in the
4300 // standard. For example:
4301 //
4302 // int &f(...); // #1
4303 // void f(char*); // #2
4304 // void g() { int &r = f("foo"); }
4305 //
4306 // In C++03, we pick #2 as the best viable function.
4307 // In C++11, we pick #1 as the best viable function, because ellipsis
4308 // conversion is better than string-literal to char* conversion (since there
4309 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4310 // convert arguments, #2 would be the best viable function in C++11.
4311 // If the best viable function has this conversion, a warning will be issued
4312 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4313
4314 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4317 // Ill-formedness must not differ
4318 ICS1.isBad() == ICS2.isBad())
4322
4323 if (ICS1.getKindRank() < ICS2.getKindRank())
4325 if (ICS2.getKindRank() < ICS1.getKindRank())
4327
4328 // The following checks require both conversion sequences to be of
4329 // the same kind.
4330 if (ICS1.getKind() != ICS2.getKind())
4332
4335
4336 // Two implicit conversion sequences of the same form are
4337 // indistinguishable conversion sequences unless one of the
4338 // following rules apply: (C++ 13.3.3.2p3):
4339
4340 // List-initialization sequence L1 is a better conversion sequence than
4341 // list-initialization sequence L2 if:
4342 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4343 // if not that,
4344 // — L1 and L2 convert to arrays of the same element type, and either the
4345 // number of elements n_1 initialized by L1 is less than the number of
4346 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4347 // an array of unknown bound and L1 does not,
4348 // even if one of the other rules in this paragraph would otherwise apply.
4349 if (!ICS1.isBad()) {
4350 bool StdInit1 = false, StdInit2 = false;
4353 nullptr);
4356 nullptr);
4357 if (StdInit1 != StdInit2)
4358 return StdInit1 ? ImplicitConversionSequence::Better
4360
4363 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4365 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4367 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4368 CAT2->getElementType())) {
4369 // Both to arrays of the same element type
4370 if (CAT1->getSize() != CAT2->getSize())
4371 // Different sized, the smaller wins
4372 return CAT1->getSize().ult(CAT2->getSize())
4377 // One is incomplete, it loses
4381 }
4382 }
4383 }
4384
4385 if (ICS1.isStandard())
4386 // Standard conversion sequence S1 is a better conversion sequence than
4387 // standard conversion sequence S2 if [...]
4388 Result = CompareStandardConversionSequences(S, Loc,
4389 ICS1.Standard, ICS2.Standard);
4390 else if (ICS1.isUserDefined()) {
4391 // With lazy template loading, it is possible to find non-canonical
4392 // FunctionDecls, depending on when redecl chains are completed. Make sure
4393 // to compare the canonical decls of conversion functions. This avoids
4394 // ambiguity problems for templated conversion operators.
4395 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4396 if (ConvFunc1)
4397 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4398 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4399 if (ConvFunc2)
4400 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4401 // User-defined conversion sequence U1 is a better conversion
4402 // sequence than another user-defined conversion sequence U2 if
4403 // they contain the same user-defined conversion function or
4404 // constructor and if the second standard conversion sequence of
4405 // U1 is better than the second standard conversion sequence of
4406 // U2 (C++ 13.3.3.2p3).
4407 if (ConvFunc1 == ConvFunc2)
4408 Result = CompareStandardConversionSequences(S, Loc,
4409 ICS1.UserDefined.After,
4410 ICS2.UserDefined.After);
4411 else
4412 Result = compareConversionFunctions(S,
4415 }
4416
4417 return Result;
4418}
4419
4420// Per 13.3.3.2p3, compare the given standard conversion sequences to
4421// determine if one is a proper subset of the other.
4424 const StandardConversionSequence& SCS1,
4425 const StandardConversionSequence& SCS2) {
4428
4429 // the identity conversion sequence is considered to be a subsequence of
4430 // any non-identity conversion sequence
4431 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4433 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4435
4436 if (SCS1.Second != SCS2.Second) {
4437 if (SCS1.Second == ICK_Identity)
4439 else if (SCS2.Second == ICK_Identity)
4441 else
4443 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4445
4446 if (SCS1.Third == SCS2.Third) {
4447 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4449 }
4450
4451 if (SCS1.Third == ICK_Identity)
4452 return Result == ImplicitConversionSequence::Worse
4455
4456 if (SCS2.Third == ICK_Identity)
4457 return Result == ImplicitConversionSequence::Better
4460
4462}
4463
4464/// Determine whether one of the given reference bindings is better
4465/// than the other based on what kind of bindings they are.
4466static bool
4468 const StandardConversionSequence &SCS2) {
4469 // C++0x [over.ics.rank]p3b4:
4470 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4471 // implicit object parameter of a non-static member function declared
4472 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4473 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4474 // lvalue reference to a function lvalue and S2 binds an rvalue
4475 // reference*.
4476 //
4477 // FIXME: Rvalue references. We're going rogue with the above edits,
4478 // because the semantics in the current C++0x working paper (N3225 at the
4479 // time of this writing) break the standard definition of std::forward
4480 // and std::reference_wrapper when dealing with references to functions.
4481 // Proposed wording changes submitted to CWG for consideration.
4484 return false;
4485
4486 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4487 SCS2.IsLvalueReference) ||
4490}
4491
4497
4498/// Returns kind of fixed enum promotion the \a SCS uses.
4499static FixedEnumPromotion
4501
4502 if (SCS.Second != ICK_Integral_Promotion)
4504
4505 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4506 if (!Enum)
4508
4509 if (!Enum->isFixed())
4511
4512 QualType UnderlyingType = Enum->getIntegerType();
4513 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4515
4517}
4518
4519/// CompareStandardConversionSequences - Compare two standard
4520/// conversion sequences to determine whether one is better than the
4521/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4524 const StandardConversionSequence& SCS1,
4525 const StandardConversionSequence& SCS2)
4526{
4527 // Standard conversion sequence S1 is a better conversion sequence
4528 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4529
4530 // -- S1 is a proper subsequence of S2 (comparing the conversion
4531 // sequences in the canonical form defined by 13.3.3.1.1,
4532 // excluding any Lvalue Transformation; the identity conversion
4533 // sequence is considered to be a subsequence of any
4534 // non-identity conversion sequence) or, if not that,
4537 return CK;
4538
4539 // -- the rank of S1 is better than the rank of S2 (by the rules
4540 // defined below), or, if not that,
4541 ImplicitConversionRank Rank1 = SCS1.getRank();
4542 ImplicitConversionRank Rank2 = SCS2.getRank();
4543 if (Rank1 < Rank2)
4545 else if (Rank2 < Rank1)
4547
4548 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4549 // are indistinguishable unless one of the following rules
4550 // applies:
4551
4552 // A conversion that is not a conversion of a pointer, or
4553 // pointer to member, to bool is better than another conversion
4554 // that is such a conversion.
4556 return SCS2.isPointerConversionToBool()
4559
4560 // C++14 [over.ics.rank]p4b2:
4561 // This is retroactively applied to C++11 by CWG 1601.
4562 //
4563 // A conversion that promotes an enumeration whose underlying type is fixed
4564 // to its underlying type is better than one that promotes to the promoted
4565 // underlying type, if the two are different.
4568 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4569 FEP1 != FEP2)
4573
4574 // C++ [over.ics.rank]p4b2:
4575 //
4576 // If class B is derived directly or indirectly from class A,
4577 // conversion of B* to A* is better than conversion of B* to
4578 // void*, and conversion of A* to void* is better than conversion
4579 // of B* to void*.
4580 bool SCS1ConvertsToVoid
4582 bool SCS2ConvertsToVoid
4584 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4585 // Exactly one of the conversion sequences is a conversion to
4586 // a void pointer; it's the worse conversion.
4587 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4589 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4590 // Neither conversion sequence converts to a void pointer; compare
4591 // their derived-to-base conversions.
4593 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4594 return DerivedCK;
4595 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4596 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4597 // Both conversion sequences are conversions to void
4598 // pointers. Compare the source types to determine if there's an
4599 // inheritance relationship in their sources.
4600 QualType FromType1 = SCS1.getFromType();
4601 QualType FromType2 = SCS2.getFromType();
4602
4603 // Adjust the types we're converting from via the array-to-pointer
4604 // conversion, if we need to.
4605 if (SCS1.First == ICK_Array_To_Pointer)
4606 FromType1 = S.Context.getArrayDecayedType(FromType1);
4607 if (SCS2.First == ICK_Array_To_Pointer)
4608 FromType2 = S.Context.getArrayDecayedType(FromType2);
4609
4610 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4611 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4612
4613 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4615 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4617
4618 // Objective-C++: If one interface is more specific than the
4619 // other, it is the better one.
4620 const ObjCObjectPointerType* FromObjCPtr1
4621 = FromType1->getAs<ObjCObjectPointerType>();
4622 const ObjCObjectPointerType* FromObjCPtr2
4623 = FromType2->getAs<ObjCObjectPointerType>();
4624 if (FromObjCPtr1 && FromObjCPtr2) {
4625 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4626 FromObjCPtr2);
4627 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4628 FromObjCPtr1);
4629 if (AssignLeft != AssignRight) {
4630 return AssignLeft? ImplicitConversionSequence::Better
4632 }
4633 }
4634 }
4635
4636 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4637 // Check for a better reference binding based on the kind of bindings.
4638 if (isBetterReferenceBindingKind(SCS1, SCS2))
4640 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4642 }
4643
4644 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4645 // bullet 3).
4647 = CompareQualificationConversions(S, SCS1, SCS2))
4648 return QualCK;
4649
4650 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4651 // C++ [over.ics.rank]p3b4:
4652 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4653 // which the references refer are the same type except for
4654 // top-level cv-qualifiers, and the type to which the reference
4655 // initialized by S2 refers is more cv-qualified than the type
4656 // to which the reference initialized by S1 refers.
4657 QualType T1 = SCS1.getToType(2);
4658 QualType T2 = SCS2.getToType(2);
4659 T1 = S.Context.getCanonicalType(T1);
4660 T2 = S.Context.getCanonicalType(T2);
4661 Qualifiers T1Quals, T2Quals;
4662 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4663 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4664 if (UnqualT1 == UnqualT2) {
4665 // Objective-C++ ARC: If the references refer to objects with different
4666 // lifetimes, prefer bindings that don't change lifetime.
4672 }
4673
4674 // If the type is an array type, promote the element qualifiers to the
4675 // type for comparison.
4676 if (isa<ArrayType>(T1) && T1Quals)
4677 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4678 if (isa<ArrayType>(T2) && T2Quals)
4679 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4680 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4682 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4684 }
4685 }
4686
4687 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4688 // floating-to-integral conversion if the integral conversion
4689 // is between types of the same size.
4690 // For example:
4691 // void f(float);
4692 // void f(int);
4693 // int main {
4694 // long a;
4695 // f(a);
4696 // }
4697 // Here, MSVC will call f(int) instead of generating a compile error
4698 // as clang will do in standard mode.
4699 if (S.getLangOpts().MSVCCompat &&
4702 SCS2.Second == ICK_Floating_Integral &&
4703 S.Context.getTypeSize(SCS1.getFromType()) ==
4704 S.Context.getTypeSize(SCS1.getToType(2)))
4706
4707 // Prefer a compatible vector conversion over a lax vector conversion
4708 // For example:
4709 //
4710 // typedef float __v4sf __attribute__((__vector_size__(16)));
4711 // void f(vector float);
4712 // void f(vector signed int);
4713 // int main() {
4714 // __v4sf a;
4715 // f(a);
4716 // }
4717 // Here, we'd like to choose f(vector float) and not
4718 // report an ambiguous call error
4719 if (SCS1.Second == ICK_Vector_Conversion &&
4720 SCS2.Second == ICK_Vector_Conversion) {
4721 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4722 SCS1.getFromType(), SCS1.getToType(2));
4723 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4724 SCS2.getFromType(), SCS2.getToType(2));
4725
4726 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4727 return SCS1IsCompatibleVectorConversion
4730 }
4731
4732 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4734 bool SCS1IsCompatibleSVEVectorConversion =
4735 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4736 bool SCS2IsCompatibleSVEVectorConversion =
4737 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4738
4739 if (SCS1IsCompatibleSVEVectorConversion !=
4740 SCS2IsCompatibleSVEVectorConversion)
4741 return SCS1IsCompatibleSVEVectorConversion
4744 }
4745
4746 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4748 bool SCS1IsCompatibleRVVVectorConversion =
4750 bool SCS2IsCompatibleRVVVectorConversion =
4752
4753 if (SCS1IsCompatibleRVVVectorConversion !=
4754 SCS2IsCompatibleRVVVectorConversion)
4755 return SCS1IsCompatibleRVVVectorConversion
4758 }
4760}
4761
4762/// CompareQualificationConversions - Compares two standard conversion
4763/// sequences to determine whether they can be ranked based on their
4764/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4767 const StandardConversionSequence& SCS1,
4768 const StandardConversionSequence& SCS2) {
4769 // C++ [over.ics.rank]p3:
4770 // -- S1 and S2 differ only in their qualification conversion and
4771 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4772 // [C++98]
4773 // [...] and the cv-qualification signature of type T1 is a proper subset
4774 // of the cv-qualification signature of type T2, and S1 is not the
4775 // deprecated string literal array-to-pointer conversion (4.2).
4776 // [C++2a]
4777 // [...] where T1 can be converted to T2 by a qualification conversion.
4778 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4779 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4781
4782 // FIXME: the example in the standard doesn't use a qualification
4783 // conversion (!)
4784 QualType T1 = SCS1.getToType(2);
4785 QualType T2 = SCS2.getToType(2);
4786 T1 = S.Context.getCanonicalType(T1);
4787 T2 = S.Context.getCanonicalType(T2);
4788 assert(!T1->isReferenceType() && !T2->isReferenceType());
4789 Qualifiers T1Quals, T2Quals;
4790 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4791 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4792
4793 // If the types are the same, we won't learn anything by unwrapping
4794 // them.
4795 if (UnqualT1 == UnqualT2)
4797
4798 // Don't ever prefer a standard conversion sequence that uses the deprecated
4799 // string literal array to pointer conversion.
4800 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4801 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4802
4803 // Objective-C++ ARC:
4804 // Prefer qualification conversions not involving a change in lifetime
4805 // to qualification conversions that do change lifetime.
4808 CanPick1 = false;
4811 CanPick2 = false;
4812
4813 bool ObjCLifetimeConversion;
4814 if (CanPick1 &&
4815 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4816 CanPick1 = false;
4817 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4818 // directions, so we can't short-cut this second check in general.
4819 if (CanPick2 &&
4820 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4821 CanPick2 = false;
4822
4823 if (CanPick1 != CanPick2)
4824 return CanPick1 ? ImplicitConversionSequence::Better
4827}
4828
4829/// CompareDerivedToBaseConversions - Compares two standard conversion
4830/// sequences to determine whether they can be ranked based on their
4831/// various kinds of derived-to-base conversions (C++
4832/// [over.ics.rank]p4b3). As part of these checks, we also look at
4833/// conversions between Objective-C interface types.
4836 const StandardConversionSequence& SCS1,
4837 const StandardConversionSequence& SCS2) {
4838 QualType FromType1 = SCS1.getFromType();
4839 QualType ToType1 = SCS1.getToType(1);
4840 QualType FromType2 = SCS2.getFromType();
4841 QualType ToType2 = SCS2.getToType(1);
4842
4843 // Adjust the types we're converting from via the array-to-pointer
4844 // conversion, if we need to.
4845 if (SCS1.First == ICK_Array_To_Pointer)
4846 FromType1 = S.Context.getArrayDecayedType(FromType1);
4847 if (SCS2.First == ICK_Array_To_Pointer)
4848 FromType2 = S.Context.getArrayDecayedType(FromType2);
4849
4850 // Canonicalize all of the types.
4851 FromType1 = S.Context.getCanonicalType(FromType1);
4852 ToType1 = S.Context.getCanonicalType(ToType1);
4853 FromType2 = S.Context.getCanonicalType(FromType2);
4854 ToType2 = S.Context.getCanonicalType(ToType2);
4855
4856 // C++ [over.ics.rank]p4b3:
4857 //
4858 // If class B is derived directly or indirectly from class A and
4859 // class C is derived directly or indirectly from B,
4860 //
4861 // Compare based on pointer conversions.
4862 if (SCS1.Second == ICK_Pointer_Conversion &&
4864 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4865 FromType1->isPointerType() && FromType2->isPointerType() &&
4866 ToType1->isPointerType() && ToType2->isPointerType()) {
4867 QualType FromPointee1 =
4869 QualType ToPointee1 =
4871 QualType FromPointee2 =
4873 QualType ToPointee2 =
4875
4876 // -- conversion of C* to B* is better than conversion of C* to A*,
4877 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4878 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4880 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4882 }
4883
4884 // -- conversion of B* to A* is better than conversion of C* to A*,
4885 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4886 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4888 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4890 }
4891 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4893 const ObjCObjectPointerType *FromPtr1
4894 = FromType1->getAs<ObjCObjectPointerType>();
4895 const ObjCObjectPointerType *FromPtr2
4896 = FromType2->getAs<ObjCObjectPointerType>();
4897 const ObjCObjectPointerType *ToPtr1
4898 = ToType1->getAs<ObjCObjectPointerType>();
4899 const ObjCObjectPointerType *ToPtr2
4900 = ToType2->getAs<ObjCObjectPointerType>();
4901
4902 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4903 // Apply the same conversion ranking rules for Objective-C pointer types
4904 // that we do for C++ pointers to class types. However, we employ the
4905 // Objective-C pseudo-subtyping relationship used for assignment of
4906 // Objective-C pointer types.
4907 bool FromAssignLeft
4908 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4909 bool FromAssignRight
4910 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4911 bool ToAssignLeft
4912 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4913 bool ToAssignRight
4914 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4915
4916 // A conversion to an a non-id object pointer type or qualified 'id'
4917 // type is better than a conversion to 'id'.
4918 if (ToPtr1->isObjCIdType() &&
4919 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4921 if (ToPtr2->isObjCIdType() &&
4922 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4924
4925 // A conversion to a non-id object pointer type is better than a
4926 // conversion to a qualified 'id' type
4927 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4929 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4931
4932 // A conversion to an a non-Class object pointer type or qualified 'Class'
4933 // type is better than a conversion to 'Class'.
4934 if (ToPtr1->isObjCClassType() &&
4935 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4937 if (ToPtr2->isObjCClassType() &&
4938 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4940
4941 // A conversion to a non-Class object pointer type is better than a
4942 // conversion to a qualified 'Class' type.
4943 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4945 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4947
4948 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4949 if (S.Context.hasSameType(FromType1, FromType2) &&
4950 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4951 (ToAssignLeft != ToAssignRight)) {
4952 if (FromPtr1->isSpecialized()) {
4953 // "conversion of B<A> * to B * is better than conversion of B * to
4954 // C *.
4955 bool IsFirstSame =
4956 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4957 bool IsSecondSame =
4958 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4959 if (IsFirstSame) {
4960 if (!IsSecondSame)
4962 } else if (IsSecondSame)
4964 }
4965 return ToAssignLeft? ImplicitConversionSequence::Worse
4967 }
4968
4969 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4970 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4971 (FromAssignLeft != FromAssignRight))
4972 return FromAssignLeft? ImplicitConversionSequence::Better
4974 }
4975 }
4976
4977 // Ranking of member-pointer types.
4978 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4979 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4980 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4981 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4982 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4983 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4984 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4985 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4986 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4987 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4988 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4989 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4990 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4991 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4993 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4995 }
4996 // conversion of B::* to C::* is better than conversion of A::* to C::*
4997 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4998 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5000 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5002 }
5003 }
5004
5005 if (SCS1.Second == ICK_Derived_To_Base) {
5006 // -- conversion of C to B is better than conversion of C to A,
5007 // -- binding of an expression of type C to a reference of type
5008 // B& is better than binding an expression of type C to a
5009 // reference of type A&,
5010 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5011 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5012 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5014 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5016 }
5017
5018 // -- conversion of B to A is better than conversion of C to A.
5019 // -- binding of an expression of type B to a reference of type
5020 // A& is better than binding an expression of type C to a
5021 // reference of type A&,
5022 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5023 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5024 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5026 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5028 }
5029 }
5030
5032}
5033
5035 if (!T.getQualifiers().hasUnaligned())
5036 return T;
5037
5038 Qualifiers Q;
5039 T = Ctx.getUnqualifiedArrayType(T, Q);
5040 Q.removeUnaligned();
5041 return Ctx.getQualifiedType(T, Q);
5042}
5043
5046 QualType OrigT1, QualType OrigT2,
5047 ReferenceConversions *ConvOut) {
5048 assert(!OrigT1->isReferenceType() &&
5049 "T1 must be the pointee type of the reference type");
5050 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5051
5052 QualType T1 = Context.getCanonicalType(OrigT1);
5053 QualType T2 = Context.getCanonicalType(OrigT2);
5054 Qualifiers T1Quals, T2Quals;
5055 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5056 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5057
5058 ReferenceConversions ConvTmp;
5059 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5060 Conv = ReferenceConversions();
5061
5062 // C++2a [dcl.init.ref]p4:
5063 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5064 // reference-related to "cv2 T2" if T1 is similar to T2, or
5065 // T1 is a base class of T2.
5066 // "cv1 T1" is reference-compatible with "cv2 T2" if
5067 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5068 // "pointer to cv1 T1" via a standard conversion sequence.
5069
5070 // Check for standard conversions we can apply to pointers: derived-to-base
5071 // conversions, ObjC pointer conversions, and function pointer conversions.
5072 // (Qualification conversions are checked last.)
5073 if (UnqualT1 == UnqualT2) {
5074 // Nothing to do.
5075 } else if (isCompleteType(Loc, OrigT2) &&
5076 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5077 Conv |= ReferenceConversions::DerivedToBase;
5078 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5079 UnqualT2->isObjCObjectOrInterfaceType() &&
5080 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5081 Conv |= ReferenceConversions::ObjC;
5082 else if (UnqualT2->isFunctionType() &&
5083 IsFunctionConversion(UnqualT2, UnqualT1)) {
5084 Conv |= ReferenceConversions::Function;
5085 // No need to check qualifiers; function types don't have them.
5086 return Ref_Compatible;
5087 }
5088 bool ConvertedReferent = Conv != 0;
5089
5090 // We can have a qualification conversion. Compute whether the types are
5091 // similar at the same time.
5092 bool PreviousToQualsIncludeConst = true;
5093 bool TopLevel = true;
5094 do {
5095 if (T1 == T2)
5096 break;
5097
5098 // We will need a qualification conversion.
5099 Conv |= ReferenceConversions::Qualification;
5100
5101 // Track whether we performed a qualification conversion anywhere other
5102 // than the top level. This matters for ranking reference bindings in
5103 // overload resolution.
5104 if (!TopLevel)
5105 Conv |= ReferenceConversions::NestedQualification;
5106
5107 // MS compiler ignores __unaligned qualifier for references; do the same.
5108 T1 = withoutUnaligned(Context, T1);
5109 T2 = withoutUnaligned(Context, T2);
5110
5111 // If we find a qualifier mismatch, the types are not reference-compatible,
5112 // but are still be reference-related if they're similar.
5113 bool ObjCLifetimeConversion = false;
5114 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5115 PreviousToQualsIncludeConst,
5116 ObjCLifetimeConversion, getASTContext()))
5117 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5118 ? Ref_Related
5120
5121 // FIXME: Should we track this for any level other than the first?
5122 if (ObjCLifetimeConversion)
5123 Conv |= ReferenceConversions::ObjCLifetime;
5124
5125 TopLevel = false;
5126 } while (Context.UnwrapSimilarTypes(T1, T2));
5127
5128 // At this point, if the types are reference-related, we must either have the
5129 // same inner type (ignoring qualifiers), or must have already worked out how
5130 // to convert the referent.
5131 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5134}
5135
5136/// Look for a user-defined conversion to a value reference-compatible
5137/// with DeclType. Return true if something definite is found.
5138static bool
5140 QualType DeclType, SourceLocation DeclLoc,
5141 Expr *Init, QualType T2, bool AllowRvalues,
5142 bool AllowExplicit) {
5143 assert(T2->isRecordType() && "Can only find conversions of record types.");
5144 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5145 OverloadCandidateSet CandidateSet(
5147 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5148 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5149 NamedDecl *D = *I;
5151 if (isa<UsingShadowDecl>(D))
5152 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5153
5154 FunctionTemplateDecl *ConvTemplate
5155 = dyn_cast<FunctionTemplateDecl>(D);
5156 CXXConversionDecl *Conv;
5157 if (ConvTemplate)
5158 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5159 else
5160 Conv = cast<CXXConversionDecl>(D);
5161
5162 if (AllowRvalues) {
5163 // If we are initializing an rvalue reference, don't permit conversion
5164 // functions that return lvalues.
5165 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5166 const ReferenceType *RefType
5168 if (RefType && !RefType->getPointeeType()->isFunctionType())
5169 continue;
5170 }
5171
5172 if (!ConvTemplate &&
5174 DeclLoc,
5175 Conv->getConversionType()
5180 continue;
5181 } else {
5182 // If the conversion function doesn't return a reference type,
5183 // it can't be considered for this conversion. An rvalue reference
5184 // is only acceptable if its referencee is a function type.
5185
5186 const ReferenceType *RefType =
5188 if (!RefType ||
5189 (!RefType->isLValueReferenceType() &&
5190 !RefType->getPointeeType()->isFunctionType()))
5191 continue;
5192 }
5193
5194 if (ConvTemplate)
5196 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5197 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5198 else
5200 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5201 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5202 }
5203
5204 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5205
5207 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5208 case OR_Success:
5209
5210 assert(Best->HasFinalConversion);
5211
5212 // C++ [over.ics.ref]p1:
5213 //
5214 // [...] If the parameter binds directly to the result of
5215 // applying a conversion function to the argument
5216 // expression, the implicit conversion sequence is a
5217 // user-defined conversion sequence (13.3.3.1.2), with the
5218 // second standard conversion sequence either an identity
5219 // conversion or, if the conversion function returns an
5220 // entity of a type that is a derived class of the parameter
5221 // type, a derived-to-base Conversion.
5222 if (!Best->FinalConversion.DirectBinding)
5223 return false;
5224
5225 ICS.setUserDefined();
5226 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5227 ICS.UserDefined.After = Best->FinalConversion;
5228 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5229 ICS.UserDefined.ConversionFunction = Best->Function;
5230 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5231 ICS.UserDefined.EllipsisConversion = false;
5232 assert(ICS.UserDefined.After.ReferenceBinding &&
5234 "Expected a direct reference binding!");
5235 return true;
5236
5237 case OR_Ambiguous:
5238 ICS.setAmbiguous();
5239 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5240 Cand != CandidateSet.end(); ++Cand)
5241 if (Cand->Best)
5242 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5243 return true;
5244
5246 case OR_Deleted:
5247 // There was no suitable conversion, or we found a deleted
5248 // conversion; continue with other checks.
5249 return false;
5250 }
5251
5252 llvm_unreachable("Invalid OverloadResult!");
5253}
5254
5255/// Compute an implicit conversion sequence for reference
5256/// initialization.
5257static ImplicitConversionSequence
5259 SourceLocation DeclLoc,
5260 bool SuppressUserConversions,
5261 bool AllowExplicit) {
5262 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5263
5264 // Most paths end in a failed conversion.
5267
5268 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5269 QualType T2 = Init->getType();
5270
5271 // If the initializer is the address of an overloaded function, try
5272 // to resolve the overloaded function. If all goes well, T2 is the
5273 // type of the resulting function.
5274 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5277 false, Found))
5278 T2 = Fn->getType();
5279 }
5280
5281 // Compute some basic properties of the types and the initializer.
5282 bool isRValRef = DeclType->isRValueReferenceType();
5283 Expr::Classification InitCategory = Init->Classify(S.Context);
5284
5286 Sema::ReferenceCompareResult RefRelationship =
5287 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5288
5289 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5290 ICS.setStandard();
5292 // FIXME: A reference binding can be a function conversion too. We should
5293 // consider that when ordering reference-to-function bindings.
5294 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5296 : (RefConv & Sema::ReferenceConversions::ObjC)
5298 : ICK_Identity;
5300 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5301 // a reference binding that performs a non-top-level qualification
5302 // conversion as a qualification conversion, not as an identity conversion.
5303 ICS.Standard.Third = (RefConv &
5304 Sema::ReferenceConversions::NestedQualification)
5306 : ICK_Identity;
5307 ICS.Standard.setFromType(T2);
5308 ICS.Standard.setToType(0, T2);
5309 ICS.Standard.setToType(1, T1);
5310 ICS.Standard.setToType(2, T1);
5311 ICS.Standard.ReferenceBinding = true;
5312 ICS.Standard.DirectBinding = BindsDirectly;
5313 ICS.Standard.IsLvalueReference = !isRValRef;
5315 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5318 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5319 ICS.Standard.FromBracedInitList = false;
5320 ICS.Standard.CopyConstructor = nullptr;
5322 };
5323
5324 // C++0x [dcl.init.ref]p5:
5325 // A reference to type "cv1 T1" is initialized by an expression
5326 // of type "cv2 T2" as follows:
5327
5328 // -- If reference is an lvalue reference and the initializer expression
5329 if (!isRValRef) {
5330 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5331 // reference-compatible with "cv2 T2," or
5332 //
5333 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5334 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5335 // C++ [over.ics.ref]p1:
5336 // When a parameter of reference type binds directly (8.5.3)
5337 // to an argument expression, the implicit conversion sequence
5338 // is the identity conversion, unless the argument expression
5339 // has a type that is a derived class of the parameter type,
5340 // in which case the implicit conversion sequence is a
5341 // derived-to-base Conversion (13.3.3.1).
5342 SetAsReferenceBinding(/*BindsDirectly=*/true);
5343
5344 // Nothing more to do: the inaccessibility/ambiguity check for
5345 // derived-to-base conversions is suppressed when we're
5346 // computing the implicit conversion sequence (C++
5347 // [over.best.ics]p2).
5348 return ICS;
5349 }
5350
5351 // -- has a class type (i.e., T2 is a class type), where T1 is
5352 // not reference-related to T2, and can be implicitly
5353 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5354 // is reference-compatible with "cv3 T3" 92) (this
5355 // conversion is selected by enumerating the applicable
5356 // conversion functions (13.3.1.6) and choosing the best
5357 // one through overload resolution (13.3)),
5358 if (!SuppressUserConversions && T2->isRecordType() &&
5359 S.isCompleteType(DeclLoc, T2) &&
5360 RefRelationship == Sema::Ref_Incompatible) {
5361 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5362 Init, T2, /*AllowRvalues=*/false,
5363 AllowExplicit))
5364 return ICS;
5365 }
5366 }
5367
5368 // -- Otherwise, the reference shall be an lvalue reference to a
5369 // non-volatile const type (i.e., cv1 shall be const), or the reference
5370 // shall be an rvalue reference.
5371 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5372 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5374 return ICS;
5375 }
5376
5377 // -- If the initializer expression
5378 //
5379 // -- is an xvalue, class prvalue, array prvalue or function
5380 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5381 if (RefRelationship == Sema::Ref_Compatible &&
5382 (InitCategory.isXValue() ||
5383 (InitCategory.isPRValue() &&
5384 (T2->isRecordType() || T2->isArrayType())) ||
5385 (InitCategory.isLValue() && T2->isFunctionType()))) {
5386 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5387 // binding unless we're binding to a class prvalue.
5388 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5389 // allow the use of rvalue references in C++98/03 for the benefit of
5390 // standard library implementors; therefore, we need the xvalue check here.
5391 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5392 !(InitCategory.isPRValue() || T2->isRecordType()));
5393 return ICS;
5394 }
5395
5396 // -- has a class type (i.e., T2 is a class type), where T1 is not
5397 // reference-related to T2, and can be implicitly converted to
5398 // an xvalue, class prvalue, or function lvalue of type
5399 // "cv3 T3", where "cv1 T1" is reference-compatible with
5400 // "cv3 T3",
5401 //
5402 // then the reference is bound to the value of the initializer
5403 // expression in the first case and to the result of the conversion
5404 // in the second case (or, in either case, to an appropriate base
5405 // class subobject).
5406 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5407 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5408 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5409 Init, T2, /*AllowRvalues=*/true,
5410 AllowExplicit)) {
5411 // In the second case, if the reference is an rvalue reference
5412 // and the second standard conversion sequence of the
5413 // user-defined conversion sequence includes an lvalue-to-rvalue
5414 // conversion, the program is ill-formed.
5415 if (ICS.isUserDefined() && isRValRef &&
5418
5419 return ICS;
5420 }
5421
5422 // A temporary of function type cannot be created; don't even try.
5423 if (T1->isFunctionType())
5424 return ICS;
5425
5426 // -- Otherwise, a temporary of type "cv1 T1" is created and
5427 // initialized from the initializer expression using the
5428 // rules for a non-reference copy initialization (8.5). The
5429 // reference is then bound to the temporary. If T1 is
5430 // reference-related to T2, cv1 must be the same
5431 // cv-qualification as, or greater cv-qualification than,
5432 // cv2; otherwise, the program is ill-formed.
5433 if (RefRelationship == Sema::Ref_Related) {
5434 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5435 // we would be reference-compatible or reference-compatible with
5436 // added qualification. But that wasn't the case, so the reference
5437 // initialization fails.
5438 //
5439 // Note that we only want to check address spaces and cvr-qualifiers here.
5440 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5441 Qualifiers T1Quals = T1.getQualifiers();
5442 Qualifiers T2Quals = T2.getQualifiers();
5443 T1Quals.removeObjCGCAttr();
5444 T1Quals.removeObjCLifetime();
5445 T2Quals.removeObjCGCAttr();
5446 T2Quals.removeObjCLifetime();
5447 // MS compiler ignores __unaligned qualifier for references; do the same.
5448 T1Quals.removeUnaligned();
5449 T2Quals.removeUnaligned();
5450 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5451 return ICS;
5452 }
5453
5454 // If at least one of the types is a class type, the types are not
5455 // related, and we aren't allowed any user conversions, the
5456 // reference binding fails. This case is important for breaking
5457 // recursion, since TryImplicitConversion below will attempt to
5458 // create a temporary through the use of a copy constructor.
5459 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5460 (T1->isRecordType() || T2->isRecordType()))
5461 return ICS;
5462
5463 // If T1 is reference-related to T2 and the reference is an rvalue
5464 // reference, the initializer expression shall not be an lvalue.
5465 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5466 Init->Classify(S.Context).isLValue()) {
5468 return ICS;
5469 }
5470
5471 // C++ [over.ics.ref]p2:
5472 // When a parameter of reference type is not bound directly to
5473 // an argument expression, the conversion sequence is the one
5474 // required to convert the argument expression to the
5475 // underlying type of the reference according to
5476 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5477 // to copy-initializing a temporary of the underlying type with
5478 // the argument expression. Any difference in top-level
5479 // cv-qualification is subsumed by the initialization itself
5480 // and does not constitute a conversion.
5481 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5482 AllowedExplicit::None,
5483 /*InOverloadResolution=*/false,
5484 /*CStyle=*/false,
5485 /*AllowObjCWritebackConversion=*/false,
5486 /*AllowObjCConversionOnExplicit=*/false);
5487
5488 // Of course, that's still a reference binding.
5489 if (ICS.isStandard()) {
5490 ICS.Standard.ReferenceBinding = true;
5491 ICS.Standard.IsLvalueReference = !isRValRef;
5492 ICS.Standard.BindsToFunctionLvalue = false;
5493 ICS.Standard.BindsToRvalue = true;
5496 } else if (ICS.isUserDefined()) {
5497 const ReferenceType *LValRefType =
5500
5501 // C++ [over.ics.ref]p3:
5502 // Except for an implicit object parameter, for which see 13.3.1, a
5503 // standard conversion sequence cannot be formed if it requires [...]
5504 // binding an rvalue reference to an lvalue other than a function
5505 // lvalue.
5506 // Note that the function case is not possible here.
5507 if (isRValRef && LValRefType) {
5509 return ICS;
5510 }
5511
5513 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5515 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5519 }
5520
5521 return ICS;
5522}
5523
5524static ImplicitConversionSequence
5525TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5526 bool SuppressUserConversions,
5527 bool InOverloadResolution,
5528 bool AllowObjCWritebackConversion,
5529 bool AllowExplicit = false);
5530
5531/// TryListConversion - Try to copy-initialize a value of type ToType from the
5532/// initializer list From.
5533static ImplicitConversionSequence
5535 bool SuppressUserConversions,
5536 bool InOverloadResolution,
5537 bool AllowObjCWritebackConversion) {
5538 // C++11 [over.ics.list]p1:
5539 // When an argument is an initializer list, it is not an expression and
5540 // special rules apply for converting it to a parameter type.
5541
5543 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5544
5545 // We need a complete type for what follows. With one C++20 exception,
5546 // incomplete types can never be initialized from init lists.
5547 QualType InitTy = ToType;
5548 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5549 if (AT && S.getLangOpts().CPlusPlus20)
5550 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5551 // C++20 allows list initialization of an incomplete array type.
5552 InitTy = IAT->getElementType();
5553 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5554 return Result;
5555
5556 // C++20 [over.ics.list]/2:
5557 // If the initializer list is a designated-initializer-list, a conversion
5558 // is only possible if the parameter has an aggregate type
5559 //
5560 // FIXME: The exception for reference initialization here is not part of the
5561 // language rules, but follow other compilers in adding it as a tentative DR
5562 // resolution.
5563 bool IsDesignatedInit = From->hasDesignatedInit();
5564 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5565 IsDesignatedInit)
5566 return Result;
5567
5568 // Per DR1467 and DR2137:
5569 // If the parameter type is an aggregate class X and the initializer list
5570 // has a single element of type cv U, where U is X or a class derived from
5571 // X, the implicit conversion sequence is the one required to convert the
5572 // element to the parameter type.
5573 //
5574 // Otherwise, if the parameter type is a character array [... ]
5575 // and the initializer list has a single element that is an
5576 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5577 // implicit conversion sequence is the identity conversion.
5578 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5579 if (ToType->isRecordType() && ToType->isAggregateType()) {
5580 QualType InitType = From->getInit(0)->getType();
5581 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5582 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5583 return TryCopyInitialization(S, From->getInit(0), ToType,
5584 SuppressUserConversions,
5585 InOverloadResolution,
5586 AllowObjCWritebackConversion);
5587 }
5588
5589 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5590 InitializedEntity Entity =
5592 /*Consumed=*/false);
5593 if (S.CanPerformCopyInitialization(Entity, From)) {
5594 Result.setStandard();
5595 Result.Standard.setAsIdentityConversion();
5596 Result.Standard.setFromType(ToType);
5597 Result.Standard.setAllToTypes(ToType);
5598 return Result;
5599 }
5600 }
5601 }
5602
5603 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5604 // C++11 [over.ics.list]p2:
5605 // If the parameter type is std::initializer_list<X> or "array of X" and
5606 // all the elements can be implicitly converted to X, the implicit
5607 // conversion sequence is the worst conversion necessary to convert an
5608 // element of the list to X.
5609 //
5610 // C++14 [over.ics.list]p3:
5611 // Otherwise, if the parameter type is "array of N X", if the initializer
5612 // list has exactly N elements or if it has fewer than N elements and X is
5613 // default-constructible, and if all the elements of the initializer list
5614 // can be implicitly converted to X, the implicit conversion sequence is
5615 // the worst conversion necessary to convert an element of the list to X.
5616 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5617 unsigned e = From->getNumInits();
5620 QualType());
5621 QualType ContTy = ToType;
5622 bool IsUnbounded = false;
5623 if (AT) {
5624 InitTy = AT->getElementType();
5625 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5626 if (CT->getSize().ult(e)) {
5627 // Too many inits, fatally bad
5629 ToType);
5630 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5631 return Result;
5632 }
5633 if (CT->getSize().ugt(e)) {
5634 // Need an init from empty {}, is there one?
5635 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5636 From->getEndLoc());
5637 EmptyList.setType(S.Context.VoidTy);
5638 DfltElt = TryListConversion(
5639 S, &EmptyList, InitTy, SuppressUserConversions,
5640 InOverloadResolution, AllowObjCWritebackConversion);
5641 if (DfltElt.isBad()) {
5642 // No {} init, fatally bad
5644 ToType);
5645 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5646 return Result;
5647 }
5648 }
5649 } else {
5650 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5651 IsUnbounded = true;
5652 if (!e) {
5653 // Cannot convert to zero-sized.
5655 ToType);
5656 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5657 return Result;
5658 }
5659 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5660 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5662 }
5663 }
5664
5665 Result.setStandard();
5666 Result.Standard.setAsIdentityConversion();
5667 Result.Standard.setFromType(InitTy);
5668 Result.Standard.setAllToTypes(InitTy);
5669 for (unsigned i = 0; i < e; ++i) {
5670 Expr *Init = From->getInit(i);
5672 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5673 AllowObjCWritebackConversion);
5674
5675 // Keep the worse conversion seen so far.
5676 // FIXME: Sequences are not totally ordered, so 'worse' can be
5677 // ambiguous. CWG has been informed.
5679 Result) ==
5681 Result = ICS;
5682 // Bail as soon as we find something unconvertible.
5683 if (Result.isBad()) {
5684 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5685 return Result;
5686 }
5687 }
5688 }
5689
5690 // If we needed any implicit {} initialization, compare that now.
5691 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5692 // has been informed that this might not be the best thing.
5693 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5694 S, From->getEndLoc(), DfltElt, Result) ==
5696 Result = DfltElt;
5697 // Record the type being initialized so that we may compare sequences
5698 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5699 return Result;
5700 }
5701
5702 // C++14 [over.ics.list]p4:
5703 // C++11 [over.ics.list]p3:
5704 // Otherwise, if the parameter is a non-aggregate class X and overload
5705 // resolution chooses a single best constructor [...] the implicit
5706 // conversion sequence is a user-defined conversion sequence. If multiple
5707 // constructors are viable but none is better than the others, the
5708 // implicit conversion sequence is a user-defined conversion sequence.
5709 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5710 // This function can deal with initializer lists.
5711 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5712 AllowedExplicit::None,
5713 InOverloadResolution, /*CStyle=*/false,
5714 AllowObjCWritebackConversion,
5715 /*AllowObjCConversionOnExplicit=*/false);
5716 }
5717
5718 // C++14 [over.ics.list]p5:
5719 // C++11 [over.ics.list]p4:
5720 // Otherwise, if the parameter has an aggregate type which can be
5721 // initialized from the initializer list [...] the implicit conversion
5722 // sequence is a user-defined conversion sequence.
5723 if (ToType->isAggregateType()) {
5724 // Type is an aggregate, argument is an init list. At this point it comes
5725 // down to checking whether the initialization works.
5726 // FIXME: Find out whether this parameter is consumed or not.
5727 InitializedEntity Entity =
5729 /*Consumed=*/false);
5731 From)) {
5732 Result.setUserDefined();
5733 Result.UserDefined.Before.setAsIdentityConversion();
5734 // Initializer lists don't have a type.
5735 Result.UserDefined.Before.setFromType(QualType());
5736 Result.UserDefined.Before.setAllToTypes(QualType());
5737
5738 Result.UserDefined.After.setAsIdentityConversion();
5739 Result.UserDefined.After.setFromType(ToType);
5740 Result.UserDefined.After.setAllToTypes(ToType);
5741 Result.UserDefined.ConversionFunction = nullptr;
5742 }
5743 return Result;
5744 }
5745
5746 // C++14 [over.ics.list]p6:
5747 // C++11 [over.ics.list]p5:
5748 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5749 if (ToType->isReferenceType()) {
5750 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5751 // mention initializer lists in any way. So we go by what list-
5752 // initialization would do and try to extrapolate from that.
5753
5754 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5755
5756 // If the initializer list has a single element that is reference-related
5757 // to the parameter type, we initialize the reference from that.
5758 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5759 Expr *Init = From->getInit(0);
5760
5761 QualType T2 = Init->getType();
5762
5763 // If the initializer is the address of an overloaded function, try
5764 // to resolve the overloaded function. If all goes well, T2 is the
5765 // type of the resulting function.
5766 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5769 Init, ToType, false, Found))
5770 T2 = Fn->getType();
5771 }
5772
5773 // Compute some basic properties of the types and the initializer.
5774 Sema::ReferenceCompareResult RefRelationship =
5775 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5776
5777 if (RefRelationship >= Sema::Ref_Related) {
5778 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5779 SuppressUserConversions,
5780 /*AllowExplicit=*/false);
5781 }
5782 }
5783
5784 // Otherwise, we bind the reference to a temporary created from the
5785 // initializer list.
5786 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5787 InOverloadResolution,
5788 AllowObjCWritebackConversion);
5789 if (Result.isFailure())
5790 return Result;
5791 assert(!Result.isEllipsis() &&
5792 "Sub-initialization cannot result in ellipsis conversion.");
5793
5794 // Can we even bind to a temporary?
5795 if (ToType->isRValueReferenceType() ||
5796 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5797 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5798 Result.UserDefined.After;
5799 SCS.ReferenceBinding = true;
5801 SCS.BindsToRvalue = true;
5802 SCS.BindsToFunctionLvalue = false;
5805 SCS.FromBracedInitList = false;
5806
5807 } else
5809 From, ToType);
5810 return Result;
5811 }
5812
5813 // C++14 [over.ics.list]p7:
5814 // C++11 [over.ics.list]p6:
5815 // Otherwise, if the parameter type is not a class:
5816 if (!ToType->isRecordType()) {
5817 // - if the initializer list has one element that is not itself an
5818 // initializer list, the implicit conversion sequence is the one
5819 // required to convert the element to the parameter type.
5820 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5821 // single integer.
5822 unsigned NumInits = From->getNumInits();
5823 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5824 !isa<EmbedExpr>(From->getInit(0))) {
5825 Result = TryCopyInitialization(
5826 S, From->getInit(0), ToType, SuppressUserConversions,
5827 InOverloadResolution, AllowObjCWritebackConversion);
5828 if (Result.isStandard())
5829 Result.Standard.FromBracedInitList = true;
5830 }
5831 // - if the initializer list has no elements, the implicit conversion
5832 // sequence is the identity conversion.
5833 else if (NumInits == 0) {
5834 Result.setStandard();
5835 Result.Standard.setAsIdentityConversion();
5836 Result.Standard.setFromType(ToType);
5837 Result.Standard.setAllToTypes(ToType);
5838 }
5839 return Result;
5840 }
5841
5842 // C++14 [over.ics.list]p8:
5843 // C++11 [over.ics.list]p7:
5844 // In all cases other than those enumerated above, no conversion is possible
5845 return Result;
5846}
5847
5848/// TryCopyInitialization - Try to copy-initialize a value of type
5849/// ToType from the expression From. Return the implicit conversion
5850/// sequence required to pass this argument, which may be a bad
5851/// conversion sequence (meaning that the argument cannot be passed to
5852/// a parameter of this type). If @p SuppressUserConversions, then we
5853/// do not permit any user-defined conversion sequences.
5854static ImplicitConversionSequence
5856 bool SuppressUserConversions,
5857 bool InOverloadResolution,
5858 bool AllowObjCWritebackConversion,
5859 bool AllowExplicit) {
5860 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5861 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5862 InOverloadResolution,AllowObjCWritebackConversion);
5863
5864 if (ToType->isReferenceType())
5865 return TryReferenceInit(S, From, ToType,
5866 /*FIXME:*/ From->getBeginLoc(),
5867 SuppressUserConversions, AllowExplicit);
5868
5869 return TryImplicitConversion(S, From, ToType,
5870 SuppressUserConversions,
5871 AllowedExplicit::None,
5872 InOverloadResolution,
5873 /*CStyle=*/false,
5874 AllowObjCWritebackConversion,
5875 /*AllowObjCConversionOnExplicit=*/false);
5876}
5877
5878static bool TryCopyInitialization(const CanQualType FromQTy,
5879 const CanQualType ToQTy,
5880 Sema &S,
5881 SourceLocation Loc,
5882 ExprValueKind FromVK) {
5883 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5885 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5886
5887 return !ICS.isBad();
5888}
5889
5890/// TryObjectArgumentInitialization - Try to initialize the object
5891/// parameter of the given member function (@c Method) from the
5892/// expression @p From.
5894 Sema &S, SourceLocation Loc, QualType FromType,
5895 Expr::Classification FromClassification, CXXMethodDecl *Method,
5896 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5897 QualType ExplicitParameterType = QualType(),
5898 bool SuppressUserConversion = false) {
5899
5900 // We need to have an object of class type.
5901 if (const auto *PT = FromType->getAs<PointerType>()) {
5902 FromType = PT->getPointeeType();
5903
5904 // When we had a pointer, it's implicitly dereferenced, so we
5905 // better have an lvalue.
5906 assert(FromClassification.isLValue());
5907 }
5908
5909 auto ValueKindFromClassification = [](Expr::Classification C) {
5910 if (C.isPRValue())
5911 return clang::VK_PRValue;
5912 if (C.isXValue())
5913 return VK_XValue;
5914 return clang::VK_LValue;
5915 };
5916
5917 if (Method->isExplicitObjectMemberFunction()) {
5918 if (ExplicitParameterType.isNull())
5919 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5920 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5921 ValueKindFromClassification(FromClassification));
5923 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5924 /*InOverloadResolution=*/true, false);
5925 if (ICS.isBad())
5926 ICS.Bad.FromExpr = nullptr;
5927 return ICS;
5928 }
5929
5930 assert(FromType->isRecordType());
5931
5932 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5933 // C++98 [class.dtor]p2:
5934 // A destructor can be invoked for a const, volatile or const volatile
5935 // object.
5936 // C++98 [over.match.funcs]p4:
5937 // For static member functions, the implicit object parameter is considered
5938 // to match any object (since if the function is selected, the object is
5939 // discarded).
5940 Qualifiers Quals = Method->getMethodQualifiers();
5941 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5942 Quals.addConst();
5943 Quals.addVolatile();
5944 }
5945
5946 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5947
5948 // Set up the conversion sequence as a "bad" conversion, to allow us
5949 // to exit early.
5951
5952 // C++0x [over.match.funcs]p4:
5953 // For non-static member functions, the type of the implicit object
5954 // parameter is
5955 //
5956 // - "lvalue reference to cv X" for functions declared without a
5957 // ref-qualifier or with the & ref-qualifier
5958 // - "rvalue reference to cv X" for functions declared with the &&
5959 // ref-qualifier
5960 //
5961 // where X is the class of which the function is a member and cv is the
5962 // cv-qualification on the member function declaration.
5963 //
5964 // However, when finding an implicit conversion sequence for the argument, we
5965 // are not allowed to perform user-defined conversions
5966 // (C++ [over.match.funcs]p5). We perform a simplified version of
5967 // reference binding here, that allows class rvalues to bind to
5968 // non-constant references.
5969
5970 // First check the qualifiers.
5971 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5972 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5973 if (ImplicitParamType.getCVRQualifiers() !=
5974 FromTypeCanon.getLocalCVRQualifiers() &&
5975 !ImplicitParamType.isAtLeastAsQualifiedAs(
5976 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5978 FromType, ImplicitParamType);
5979 return ICS;
5980 }
5981
5982 if (FromTypeCanon.hasAddressSpace()) {
5983 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5984 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5985 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5986 S.getASTContext())) {
5988 FromType, ImplicitParamType);
5989 return ICS;
5990 }
5991 }
5992
5993 // Check that we have either the same type or a derived type. It
5994 // affects the conversion rank.
5995 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5996 ImplicitConversionKind SecondKind;
5997 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5998 SecondKind = ICK_Identity;
5999 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6000 SecondKind = ICK_Derived_To_Base;
6001 } else if (!Method->isExplicitObjectMemberFunction()) {
6003 FromType, ImplicitParamType);
6004 return ICS;
6005 }
6006
6007 // Check the ref-qualifier.
6008 switch (Method->getRefQualifier()) {
6009 case RQ_None:
6010 // Do nothing; we don't care about lvalueness or rvalueness.
6011 break;
6012
6013 case RQ_LValue:
6014 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6015 // non-const lvalue reference cannot bind to an rvalue
6017 ImplicitParamType);
6018 return ICS;
6019 }
6020 break;
6021
6022 case RQ_RValue:
6023 if (!FromClassification.isRValue()) {
6024 // rvalue reference cannot bind to an lvalue
6026 ImplicitParamType);
6027 return ICS;
6028 }
6029 break;
6030 }
6031
6032 // Success. Mark this as a reference binding.
6033 ICS.setStandard();
6035 ICS.Standard.Second = SecondKind;
6036 ICS.Standard.setFromType(FromType);
6037 ICS.Standard.setAllToTypes(ImplicitParamType);
6038 ICS.Standard.ReferenceBinding = true;
6039 ICS.Standard.DirectBinding = true;
6040 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6041 ICS.Standard.BindsToFunctionLvalue = false;
6042 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6043 ICS.Standard.FromBracedInitList = false;
6045 = (Method->getRefQualifier() == RQ_None);
6046 return ICS;
6047}
6048
6049/// PerformObjectArgumentInitialization - Perform initialization of
6050/// the implicit object parameter for the given Method with the given
6051/// expression.
6053 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6055 QualType FromRecordType, DestType;
6056 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6057
6058 Expr::Classification FromClassification;
6059 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6060 FromRecordType = PT->getPointeeType();
6061 DestType = Method->getThisType();
6062 FromClassification = Expr::Classification::makeSimpleLValue();
6063 } else {
6064 FromRecordType = From->getType();
6065 DestType = ImplicitParamRecordType;
6066 FromClassification = From->Classify(Context);
6067
6068 // CWG2813 [expr.call]p6:
6069 // If the function is an implicit object member function, the object
6070 // expression of the class member access shall be a glvalue [...]
6071 if (From->isPRValue()) {
6072 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6073 Method->getRefQualifier() !=
6075 }
6076 }
6077
6078 // Note that we always use the true parent context when performing
6079 // the actual argument initialization.
6081 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6082 Method->getParent());
6083 if (ICS.isBad()) {
6084 switch (ICS.Bad.Kind) {
6086 Qualifiers FromQs = FromRecordType.getQualifiers();
6087 Qualifiers ToQs = DestType.getQualifiers();
6088 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6089 if (CVR) {
6090 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6091 << Method->getDeclName() << FromRecordType << (CVR - 1)
6092 << From->getSourceRange();
6093 Diag(Method->getLocation(), diag::note_previous_decl)
6094 << Method->getDeclName();
6095 return ExprError();
6096 }
6097 break;
6098 }
6099
6102 bool IsRValueQualified =
6103 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6104 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6105 << Method->getDeclName() << FromClassification.isRValue()
6106 << IsRValueQualified;
6107 Diag(Method->getLocation(), diag::note_previous_decl)
6108 << Method->getDeclName();
6109 return ExprError();
6110 }
6111
6114 break;
6115
6118 llvm_unreachable("Lists are not objects");
6119 }
6120
6121 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6122 << ImplicitParamRecordType << FromRecordType
6123 << From->getSourceRange();
6124 }
6125
6126 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6127 ExprResult FromRes =
6128 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6129 if (FromRes.isInvalid())
6130 return ExprError();
6131 From = FromRes.get();
6132 }
6133
6134 if (!Context.hasSameType(From->getType(), DestType)) {
6135 CastKind CK;
6136 QualType PteeTy = DestType->getPointeeType();
6137 LangAS DestAS =
6138 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6139 if (FromRecordType.getAddressSpace() != DestAS)
6140 CK = CK_AddressSpaceConversion;
6141 else
6142 CK = CK_NoOp;
6143 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6144 }
6145 return From;
6146}
6147
6148/// TryContextuallyConvertToBool - Attempt to contextually convert the
6149/// expression From to bool (C++0x [conv]p3).
6152 // C++ [dcl.init]/17.8:
6153 // - Otherwise, if the initialization is direct-initialization, the source
6154 // type is std::nullptr_t, and the destination type is bool, the initial
6155 // value of the object being initialized is false.
6156 if (From->getType()->isNullPtrType())
6158 S.Context.BoolTy,
6159 From->isGLValue());
6160
6161 // All other direct-initialization of bool is equivalent to an implicit
6162 // conversion to bool in which explicit conversions are permitted.
6163 return TryImplicitConversion(S, From, S.Context.BoolTy,
6164 /*SuppressUserConversions=*/false,
6165 AllowedExplicit::Conversions,
6166 /*InOverloadResolution=*/false,
6167 /*CStyle=*/false,
6168 /*AllowObjCWritebackConversion=*/false,
6169 /*AllowObjCConversionOnExplicit=*/false);
6170}
6171
6173 if (checkPlaceholderForOverload(*this, From))
6174 return ExprError();
6175
6177 if (!ICS.isBad())
6178 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6180
6182 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6183 << From->getType() << From->getSourceRange();
6184 return ExprError();
6185}
6186
6187/// Check that the specified conversion is permitted in a converted constant
6188/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6189/// is acceptable.
6192 // Since we know that the target type is an integral or unscoped enumeration
6193 // type, most conversion kinds are impossible. All possible First and Third
6194 // conversions are fine.
6195 switch (SCS.Second) {
6196 case ICK_Identity:
6198 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6200 return true;
6201
6203 // Conversion from an integral or unscoped enumeration type to bool is
6204 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6205 // conversion, so we allow it in a converted constant expression.
6206 //
6207 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6208 // a lot of popular code. We should at least add a warning for this
6209 // (non-conforming) extension.
6211 SCS.getToType(2)->isBooleanType();
6212
6214 case ICK_Pointer_Member:
6215 // C++1z: null pointer conversions and null member pointer conversions are
6216 // only permitted if the source type is std::nullptr_t.
6217 return SCS.getFromType()->isNullPtrType();
6218
6230 case ICK_Vector_Splat:
6231 case ICK_Complex_Real:
6240 return false;
6241
6246 llvm_unreachable("found a first conversion kind in Second");
6247
6249 case ICK_Qualification:
6250 llvm_unreachable("found a third conversion kind in Second");
6251
6253 break;
6254 }
6255
6256 llvm_unreachable("unknown conversion kind");
6257}
6258
6259/// BuildConvertedConstantExpression - Check that the expression From is a
6260/// converted constant expression of type T, perform the conversion but
6261/// does not evaluate the expression
6263 QualType T, CCEKind CCE,
6264 NamedDecl *Dest,
6265 APValue &PreNarrowingValue) {
6266 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6268 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6269 "converted constant expression outside C++11 or TTP matching");
6270
6271 if (checkPlaceholderForOverload(S, From))
6272 return ExprError();
6273
6274 // C++1z [expr.const]p3:
6275 // A converted constant expression of type T is an expression,
6276 // implicitly converted to type T, where the converted
6277 // expression is a constant expression and the implicit conversion
6278 // sequence contains only [... list of conversions ...].
6280 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6282 : TryCopyInitialization(S, From, T,
6283 /*SuppressUserConversions=*/false,
6284 /*InOverloadResolution=*/false,
6285 /*AllowObjCWritebackConversion=*/false,
6286 /*AllowExplicit=*/false);
6287 StandardConversionSequence *SCS = nullptr;
6288 switch (ICS.getKind()) {
6290 SCS = &ICS.Standard;
6291 break;
6293 if (T->isRecordType())
6294 SCS = &ICS.UserDefined.Before;
6295 else
6296 SCS = &ICS.UserDefined.After;
6297 break;
6301 return S.Diag(From->getBeginLoc(),
6302 diag::err_typecheck_converted_constant_expression)
6303 << From->getType() << From->getSourceRange() << T;
6304 return ExprError();
6305
6308 llvm_unreachable("bad conversion in converted constant expression");
6309 }
6310
6311 // Check that we would only use permitted conversions.
6312 if (!CheckConvertedConstantConversions(S, *SCS)) {
6313 return S.Diag(From->getBeginLoc(),
6314 diag::err_typecheck_converted_constant_expression_disallowed)
6315 << From->getType() << From->getSourceRange() << T;
6316 }
6317 // [...] and where the reference binding (if any) binds directly.
6318 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6319 return S.Diag(From->getBeginLoc(),
6320 diag::err_typecheck_converted_constant_expression_indirect)
6321 << From->getType() << From->getSourceRange() << T;
6322 }
6323 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6324 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6325 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6326 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6327 // case explicitly.
6328 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6329 return S.Diag(From->getBeginLoc(),
6330 diag::err_reference_bind_to_bitfield_in_cce)
6331 << From->getSourceRange();
6332 }
6333
6334 // Usually we can simply apply the ImplicitConversionSequence we formed
6335 // earlier, but that's not guaranteed to work when initializing an object of
6336 // class type.
6337 ExprResult Result;
6338 bool IsTemplateArgument =
6340 if (T->isRecordType()) {
6341 assert(IsTemplateArgument &&
6342 "unexpected class type converted constant expr");
6343 Result = S.PerformCopyInitialization(
6346 SourceLocation(), From);
6347 } else {
6348 Result =
6350 }
6351 if (Result.isInvalid())
6352 return Result;
6353
6354 // C++2a [intro.execution]p5:
6355 // A full-expression is [...] a constant-expression [...]
6356 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6357 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6358 IsTemplateArgument);
6359 if (Result.isInvalid())
6360 return Result;
6361
6362 // Check for a narrowing implicit conversion.
6363 bool ReturnPreNarrowingValue = false;
6364 QualType PreNarrowingType;
6365 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6366 PreNarrowingType)) {
6368 // Implicit conversion to a narrower type, and the value is not a constant
6369 // expression. We'll diagnose this in a moment.
6370 case NK_Not_Narrowing:
6371 break;
6372
6374 if (CCE == CCEKind::ArrayBound &&
6375 PreNarrowingType->isIntegralOrEnumerationType() &&
6376 PreNarrowingValue.isInt()) {
6377 // Don't diagnose array bound narrowing here; we produce more precise
6378 // errors by allowing the un-narrowed value through.
6379 ReturnPreNarrowingValue = true;
6380 break;
6381 }
6382 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6383 << CCE << /*Constant*/ 1
6384 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6385 break;
6386
6388 // Implicit conversion to a narrower type, but the expression is
6389 // value-dependent so we can't tell whether it's actually narrowing.
6390 // For matching the parameters of a TTP, the conversion is ill-formed
6391 // if it may narrow.
6392 if (CCE != CCEKind::TempArgStrict)
6393 break;
6394 [[fallthrough]];
6395 case NK_Type_Narrowing:
6396 // FIXME: It would be better to diagnose that the expression is not a
6397 // constant expression.
6398 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6399 << CCE << /*Constant*/ 0 << From->getType() << T;
6400 break;
6401 }
6402 if (!ReturnPreNarrowingValue)
6403 PreNarrowingValue = {};
6404
6405 return Result;
6406}
6407
6408/// CheckConvertedConstantExpression - Check that the expression From is a
6409/// converted constant expression of type T, perform the conversion and produce
6410/// the converted expression, per C++11 [expr.const]p3.
6413 CCEKind CCE, bool RequireInt,
6414 NamedDecl *Dest) {
6415
6416 APValue PreNarrowingValue;
6417 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6418 PreNarrowingValue);
6419 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6420 Value = APValue();
6421 return Result;
6422 }
6423 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6424 RequireInt, PreNarrowingValue);
6425}
6426
6428 CCEKind CCE,
6429 NamedDecl *Dest) {
6430 APValue PreNarrowingValue;
6431 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6432 PreNarrowingValue);
6433}
6434
6436 APValue &Value, CCEKind CCE,
6437 NamedDecl *Dest) {
6438 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6439 Dest);
6440}
6441
6443 llvm::APSInt &Value,
6444 CCEKind CCE) {
6445 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6446
6447 APValue V;
6448 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6449 /*Dest=*/nullptr);
6450 if (!R.isInvalid() && !R.get()->isValueDependent())
6451 Value = V.getInt();
6452 return R;
6453}
6454
6457 CCEKind CCE, bool RequireInt,
6458 const APValue &PreNarrowingValue) {
6459
6460 ExprResult Result = E;
6461 // Check the expression is a constant expression.
6463 Expr::EvalResult Eval;
6464 Eval.Diag = &Notes;
6465
6466 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6467
6468 ConstantExprKind Kind;
6469 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6470 Kind = ConstantExprKind::ClassTemplateArgument;
6471 else if (CCE == CCEKind::TemplateArg)
6472 Kind = ConstantExprKind::NonClassTemplateArgument;
6473 else
6474 Kind = ConstantExprKind::Normal;
6475
6476 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6477 (RequireInt && !Eval.Val.isInt())) {
6478 // The expression can't be folded, so we can't keep it at this position in
6479 // the AST.
6480 Result = ExprError();
6481 } else {
6482 Value = Eval.Val;
6483
6484 if (Notes.empty()) {
6485 // It's a constant expression.
6486 Expr *E = Result.get();
6487 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6488 // We expect a ConstantExpr to have a value associated with it
6489 // by this point.
6490 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6491 "ConstantExpr has no value associated with it");
6492 (void)CE;
6493 } else {
6495 }
6496 if (!PreNarrowingValue.isAbsent())
6497 Value = std::move(PreNarrowingValue);
6498 return E;
6499 }
6500 }
6501
6502 // It's not a constant expression. Produce an appropriate diagnostic.
6503 if (Notes.size() == 1 &&
6504 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6505 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6506 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6507 diag::note_constexpr_invalid_template_arg) {
6508 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6509 for (unsigned I = 0; I < Notes.size(); ++I)
6510 Diag(Notes[I].first, Notes[I].second);
6511 } else {
6512 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6513 << CCE << E->getSourceRange();
6514 for (unsigned I = 0; I < Notes.size(); ++I)
6515 Diag(Notes[I].first, Notes[I].second);
6516 }
6517 return ExprError();
6518}
6519
6520/// dropPointerConversions - If the given standard conversion sequence
6521/// involves any pointer conversions, remove them. This may change
6522/// the result type of the conversion sequence.
6524 if (SCS.Second == ICK_Pointer_Conversion) {
6525 SCS.Second = ICK_Identity;
6526 SCS.Dimension = ICK_Identity;
6527 SCS.Third = ICK_Identity;
6528 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6529 }
6530}
6531
6532/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6533/// convert the expression From to an Objective-C pointer type.
6534static ImplicitConversionSequence
6536 // Do an implicit conversion to 'id'.
6539 = TryImplicitConversion(S, From, Ty,
6540 // FIXME: Are these flags correct?
6541 /*SuppressUserConversions=*/false,
6542 AllowedExplicit::Conversions,
6543 /*InOverloadResolution=*/false,
6544 /*CStyle=*/false,
6545 /*AllowObjCWritebackConversion=*/false,
6546 /*AllowObjCConversionOnExplicit=*/true);
6547
6548 // Strip off any final conversions to 'id'.
6549 switch (ICS.getKind()) {
6554 break;
6555
6558 break;
6559
6562 break;
6563 }
6564
6565 return ICS;
6566}
6567
6569 if (checkPlaceholderForOverload(*this, From))
6570 return ExprError();
6571
6572 QualType Ty = Context.getObjCIdType();
6575 if (!ICS.isBad())
6576 return PerformImplicitConversion(From, Ty, ICS,
6578 return ExprResult();
6579}
6580
6581static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6582 const Expr *Base = nullptr;
6583 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6584 "expected a member expression");
6585
6586 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6587 M && !M->isImplicitAccess())
6588 Base = M->getBase();
6589 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6590 M && !M->isImplicitAccess())
6591 Base = M->getBase();
6592
6593 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6594
6595 if (T->isPointerType())
6596 T = T->getPointeeType();
6597
6598 return T;
6599}
6600
6602 const FunctionDecl *Fun) {
6603 QualType ObjType = Obj->getType();
6604 if (ObjType->isPointerType()) {
6605 ObjType = ObjType->getPointeeType();
6606 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6608 /*CanOverflow=*/false, FPOptionsOverride());
6609 }
6610 return Obj;
6611}
6612
6620
6622 Expr *Object, MultiExprArg &Args,
6623 SmallVectorImpl<Expr *> &NewArgs) {
6624 assert(Method->isExplicitObjectMemberFunction() &&
6625 "Method is not an explicit member function");
6626 assert(NewArgs.empty() && "NewArgs should be empty");
6627
6628 NewArgs.reserve(Args.size() + 1);
6629 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6630 NewArgs.push_back(This);
6631 NewArgs.append(Args.begin(), Args.end());
6632 Args = NewArgs;
6634 Method, Object->getBeginLoc());
6635}
6636
6637/// Determine whether the provided type is an integral type, or an enumeration
6638/// type of a permitted flavor.
6640 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6641 : T->isIntegralOrUnscopedEnumerationType();
6642}
6643
6644static ExprResult
6647 QualType T, UnresolvedSetImpl &ViableConversions) {
6648
6649 if (Converter.Suppress)
6650 return ExprError();
6651
6652 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6653 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6654 CXXConversionDecl *Conv =
6655 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6657 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6658 }
6659 return From;
6660}
6661
6662static bool
6665 QualType T, bool HadMultipleCandidates,
6666 UnresolvedSetImpl &ExplicitConversions) {
6667 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6668 DeclAccessPair Found = ExplicitConversions[0];
6669 CXXConversionDecl *Conversion =
6670 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6671
6672 // The user probably meant to invoke the given explicit
6673 // conversion; use it.
6674 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6675 std::string TypeStr;
6676 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6677
6678 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6680 "static_cast<" + TypeStr + ">(")
6682 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6683 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6684
6685 // If we aren't in a SFINAE context, build a call to the
6686 // explicit conversion function.
6687 if (SemaRef.isSFINAEContext())
6688 return true;
6689
6690 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6691 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6692 HadMultipleCandidates);
6693 if (Result.isInvalid())
6694 return true;
6695
6696 // Replace the conversion with a RecoveryExpr, so we don't try to
6697 // instantiate it later, but can further diagnose here.
6698 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6699 From, Result.get()->getType());
6700 if (Result.isInvalid())
6701 return true;
6702 From = Result.get();
6703 }
6704 return false;
6705}
6706
6707static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6709 QualType T, bool HadMultipleCandidates,
6711 CXXConversionDecl *Conversion =
6712 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6713 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6714
6715 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6716 if (!Converter.SuppressConversion) {
6717 if (SemaRef.isSFINAEContext())
6718 return true;
6719
6720 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6721 << From->getSourceRange();
6722 }
6723
6724 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6725 HadMultipleCandidates);
6726 if (Result.isInvalid())
6727 return true;
6728 // Record usage of conversion in an implicit cast.
6729 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6730 CK_UserDefinedConversion, Result.get(),
6731 nullptr, Result.get()->getValueKind(),
6732 SemaRef.CurFPFeatureOverrides());
6733 return false;
6734}
6735
6737 Sema &SemaRef, SourceLocation Loc, Expr *From,
6739 if (!Converter.match(From->getType()) && !Converter.Suppress)
6740 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6741 << From->getSourceRange();
6742
6743 return SemaRef.DefaultLvalueConversion(From);
6744}
6745
6746static void
6748 UnresolvedSetImpl &ViableConversions,
6749 OverloadCandidateSet &CandidateSet) {
6750 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6751 NamedDecl *D = FoundDecl.getDecl();
6752 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6753 if (isa<UsingShadowDecl>(D))
6754 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6755
6756 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6758 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6759 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6760 continue;
6761 }
6763 SemaRef.AddConversionCandidate(
6764 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6765 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6766 }
6767}
6768
6769/// Attempt to convert the given expression to a type which is accepted
6770/// by the given converter.
6771///
6772/// This routine will attempt to convert an expression of class type to a
6773/// type accepted by the specified converter. In C++11 and before, the class
6774/// must have a single non-explicit conversion function converting to a matching
6775/// type. In C++1y, there can be multiple such conversion functions, but only
6776/// one target type.
6777///
6778/// \param Loc The source location of the construct that requires the
6779/// conversion.
6780///
6781/// \param From The expression we're converting from.
6782///
6783/// \param Converter Used to control and diagnose the conversion process.
6784///
6785/// \returns The expression, converted to an integral or enumeration type if
6786/// successful.
6788 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6789 // We can't perform any more checking for type-dependent expressions.
6790 if (From->isTypeDependent())
6791 return From;
6792
6793 // Process placeholders immediately.
6794 if (From->hasPlaceholderType()) {
6795 ExprResult result = CheckPlaceholderExpr(From);
6796 if (result.isInvalid())
6797 return result;
6798 From = result.get();
6799 }
6800
6801 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6802 ExprResult Converted = DefaultLvalueConversion(From);
6803 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6804 // If the expression already has a matching type, we're golden.
6805 if (Converter.match(T))
6806 return Converted;
6807
6808 // FIXME: Check for missing '()' if T is a function type?
6809
6810 // We can only perform contextual implicit conversions on objects of class
6811 // type.
6812 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6813 if (!RecordTy || !getLangOpts().CPlusPlus) {
6814 if (!Converter.Suppress)
6815 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6816 return From;
6817 }
6818
6819 // We must have a complete class type.
6820 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6821 ContextualImplicitConverter &Converter;
6822 Expr *From;
6823
6824 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6825 : Converter(Converter), From(From) {}
6826
6827 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6828 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6829 }
6830 } IncompleteDiagnoser(Converter, From);
6831
6832 if (Converter.Suppress ? !isCompleteType(Loc, T)
6833 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6834 return From;
6835
6836 // Look for a conversion to an integral or enumeration type.
6838 ViableConversions; // These are *potentially* viable in C++1y.
6839 UnresolvedSet<4> ExplicitConversions;
6840 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6841 ->getDefinitionOrSelf()
6842 ->getVisibleConversionFunctions();
6843
6844 bool HadMultipleCandidates =
6845 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6846
6847 // To check that there is only one target type, in C++1y:
6848 QualType ToType;
6849 bool HasUniqueTargetType = true;
6850
6851 // Collect explicit or viable (potentially in C++1y) conversions.
6852 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6853 NamedDecl *D = (*I)->getUnderlyingDecl();
6854 CXXConversionDecl *Conversion;
6855 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6856 if (ConvTemplate) {
6858 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6859 else
6860 continue; // C++11 does not consider conversion operator templates(?).
6861 } else
6862 Conversion = cast<CXXConversionDecl>(D);
6863
6864 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6865 "Conversion operator templates are considered potentially "
6866 "viable in C++1y");
6867
6868 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6869 if (Converter.match(CurToType) || ConvTemplate) {
6870
6871 if (Conversion->isExplicit()) {
6872 // FIXME: For C++1y, do we need this restriction?
6873 // cf. diagnoseNoViableConversion()
6874 if (!ConvTemplate)
6875 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6876 } else {
6877 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6878 if (ToType.isNull())
6879 ToType = CurToType.getUnqualifiedType();
6880 else if (HasUniqueTargetType &&
6881 (CurToType.getUnqualifiedType() != ToType))
6882 HasUniqueTargetType = false;
6883 }
6884 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6885 }
6886 }
6887 }
6888
6889 if (getLangOpts().CPlusPlus14) {
6890 // C++1y [conv]p6:
6891 // ... An expression e of class type E appearing in such a context
6892 // is said to be contextually implicitly converted to a specified
6893 // type T and is well-formed if and only if e can be implicitly
6894 // converted to a type T that is determined as follows: E is searched
6895 // for conversion functions whose return type is cv T or reference to
6896 // cv T such that T is allowed by the context. There shall be
6897 // exactly one such T.
6898
6899 // If no unique T is found:
6900 if (ToType.isNull()) {
6901 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6902 HadMultipleCandidates,
6903 ExplicitConversions))
6904 return ExprError();
6905 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6906 }
6907
6908 // If more than one unique Ts are found:
6909 if (!HasUniqueTargetType)
6910 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6911 ViableConversions);
6912
6913 // If one unique T is found:
6914 // First, build a candidate set from the previously recorded
6915 // potentially viable conversions.
6917 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6918 CandidateSet);
6919
6920 // Then, perform overload resolution over the candidate set.
6922 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6923 case OR_Success: {
6924 // Apply this conversion.
6926 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6927 if (recordConversion(*this, Loc, From, Converter, T,
6928 HadMultipleCandidates, Found))
6929 return ExprError();
6930 break;
6931 }
6932 case OR_Ambiguous:
6933 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6934 ViableConversions);
6936 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6937 HadMultipleCandidates,
6938 ExplicitConversions))
6939 return ExprError();
6940 [[fallthrough]];
6941 case OR_Deleted:
6942 // We'll complain below about a non-integral condition type.
6943 break;
6944 }
6945 } else {
6946 switch (ViableConversions.size()) {
6947 case 0: {
6948 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6949 HadMultipleCandidates,
6950 ExplicitConversions))
6951 return ExprError();
6952
6953 // We'll complain below about a non-integral condition type.
6954 break;
6955 }
6956 case 1: {
6957 // Apply this conversion.
6958 DeclAccessPair Found = ViableConversions[0];
6959 if (recordConversion(*this, Loc, From, Converter, T,
6960 HadMultipleCandidates, Found))
6961 return ExprError();
6962 break;
6963 }
6964 default:
6965 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6966 ViableConversions);
6967 }
6968 }
6969
6970 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6971}
6972
6973/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6974/// an acceptable non-member overloaded operator for a call whose
6975/// arguments have types T1 (and, if non-empty, T2). This routine
6976/// implements the check in C++ [over.match.oper]p3b2 concerning
6977/// enumeration types.
6979 FunctionDecl *Fn,
6980 ArrayRef<Expr *> Args) {
6981 QualType T1 = Args[0]->getType();
6982 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6983
6984 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6985 return true;
6986
6987 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6988 return true;
6989
6990 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6991 if (Proto->getNumParams() < 1)
6992 return false;
6993
6994 if (T1->isEnumeralType()) {
6995 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6996 if (Context.hasSameUnqualifiedType(T1, ArgType))
6997 return true;
6998 }
6999
7000 if (Proto->getNumParams() < 2)
7001 return false;
7002
7003 if (!T2.isNull() && T2->isEnumeralType()) {
7004 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7005 if (Context.hasSameUnqualifiedType(T2, ArgType))
7006 return true;
7007 }
7008
7009 return false;
7010}
7011
7014 return false;
7015
7016 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7017 return FD->isTargetMultiVersion();
7018
7019 if (!FD->isMultiVersion())
7020 return false;
7021
7022 // Among multiple target versions consider either the default,
7023 // or the first non-default in the absence of default version.
7024 unsigned SeenAt = 0;
7025 unsigned I = 0;
7026 bool HasDefault = false;
7028 FD, [&](const FunctionDecl *CurFD) {
7029 if (FD == CurFD)
7030 SeenAt = I;
7031 else if (CurFD->isTargetMultiVersionDefault())
7032 HasDefault = true;
7033 ++I;
7034 });
7035 return HasDefault || SeenAt != 0;
7036}
7037
7040 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7041 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7042 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7043 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7044 bool StrictPackMatch) {
7045 const FunctionProtoType *Proto
7046 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7047 assert(Proto && "Functions without a prototype cannot be overloaded");
7048 assert(!Function->getDescribedFunctionTemplate() &&
7049 "Use AddTemplateOverloadCandidate for function templates");
7050
7051 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7053 // If we get here, it's because we're calling a member function
7054 // that is named without a member access expression (e.g.,
7055 // "this->f") that was either written explicitly or created
7056 // implicitly. This can happen with a qualified call to a member
7057 // function, e.g., X::f(). We use an empty type for the implied
7058 // object argument (C++ [over.call.func]p3), and the acting context
7059 // is irrelevant.
7060 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7062 CandidateSet, SuppressUserConversions,
7063 PartialOverloading, EarlyConversions, PO,
7064 StrictPackMatch);
7065 return;
7066 }
7067 // We treat a constructor like a non-member function, since its object
7068 // argument doesn't participate in overload resolution.
7069 }
7070
7071 if (!CandidateSet.isNewCandidate(Function, PO))
7072 return;
7073
7074 // C++11 [class.copy]p11: [DR1402]
7075 // A defaulted move constructor that is defined as deleted is ignored by
7076 // overload resolution.
7077 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7078 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7079 Constructor->isMoveConstructor())
7080 return;
7081
7082 // Overload resolution is always an unevaluated context.
7085
7086 // C++ [over.match.oper]p3:
7087 // if no operand has a class type, only those non-member functions in the
7088 // lookup set that have a first parameter of type T1 or "reference to
7089 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7090 // is a right operand) a second parameter of type T2 or "reference to
7091 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7092 // candidate functions.
7093 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7095 return;
7096
7097 // Add this candidate
7098 OverloadCandidate &Candidate =
7099 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7100 Candidate.FoundDecl = FoundDecl;
7101 Candidate.Function = Function;
7102 Candidate.Viable = true;
7103 Candidate.RewriteKind =
7104 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7105 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7106 Candidate.ExplicitCallArguments = Args.size();
7107 Candidate.StrictPackMatch = StrictPackMatch;
7108
7109 // Explicit functions are not actually candidates at all if we're not
7110 // allowing them in this context, but keep them around so we can point
7111 // to them in diagnostics.
7112 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7113 Candidate.Viable = false;
7114 Candidate.FailureKind = ovl_fail_explicit;
7115 return;
7116 }
7117
7118 // Functions with internal linkage are only viable in the same module unit.
7119 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7120 /// FIXME: Currently, the semantics of linkage in clang is slightly
7121 /// different from the semantics in C++ spec. In C++ spec, only names
7122 /// have linkage. So that all entities of the same should share one
7123 /// linkage. But in clang, different entities of the same could have
7124 /// different linkage.
7125 const NamedDecl *ND = Function;
7126 bool IsImplicitlyInstantiated = false;
7127 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7128 ND = SpecInfo->getTemplate();
7129 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7131 }
7132
7133 /// Don't remove inline functions with internal linkage from the overload
7134 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7135 /// However:
7136 /// - Inline functions with internal linkage are a common pattern in
7137 /// headers to avoid ODR issues.
7138 /// - The global module is meant to be a transition mechanism for C and C++
7139 /// headers, and the current rules as written work against that goal.
7140 const bool IsInlineFunctionInGMF =
7141 Function->isFromGlobalModule() &&
7142 (IsImplicitlyInstantiated || Function->isInlined());
7143
7144 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7145 Candidate.Viable = false;
7147 return;
7148 }
7149 }
7150
7152 Candidate.Viable = false;
7154 return;
7155 }
7156
7157 if (Constructor) {
7158 // C++ [class.copy]p3:
7159 // A member function template is never instantiated to perform the copy
7160 // of a class object to an object of its class type.
7161 CanQualType ClassType =
7162 Context.getCanonicalTagType(Constructor->getParent());
7163 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7164 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7165 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7166 ClassType))) {
7167 Candidate.Viable = false;
7169 return;
7170 }
7171
7172 // C++ [over.match.funcs]p8: (proposed DR resolution)
7173 // A constructor inherited from class type C that has a first parameter
7174 // of type "reference to P" (including such a constructor instantiated
7175 // from a template) is excluded from the set of candidate functions when
7176 // constructing an object of type cv D if the argument list has exactly
7177 // one argument and D is reference-related to P and P is reference-related
7178 // to C.
7179 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7180 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7181 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7182 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7183 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7184 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7185 SourceLocation Loc = Args.front()->getExprLoc();
7186 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7187 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7188 Candidate.Viable = false;
7190 return;
7191 }
7192 }
7193
7194 // Check that the constructor is capable of constructing an object in the
7195 // destination address space.
7197 Constructor->getMethodQualifiers().getAddressSpace(),
7198 CandidateSet.getDestAS(), getASTContext())) {
7199 Candidate.Viable = false;
7201 }
7202 }
7203
7204 unsigned NumParams = Proto->getNumParams();
7205
7206 // (C++ 13.3.2p2): A candidate function having fewer than m
7207 // parameters is viable only if it has an ellipsis in its parameter
7208 // list (8.3.5).
7209 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7210 !Proto->isVariadic() &&
7211 shouldEnforceArgLimit(PartialOverloading, Function)) {
7212 Candidate.Viable = false;
7214 return;
7215 }
7216
7217 // (C++ 13.3.2p2): A candidate function having more than m parameters
7218 // is viable only if the (m+1)st parameter has a default argument
7219 // (8.3.6). For the purposes of overload resolution, the
7220 // parameter list is truncated on the right, so that there are
7221 // exactly m parameters.
7222 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7223 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7224 !PartialOverloading) {
7225 // Not enough arguments.
7226 Candidate.Viable = false;
7228 return;
7229 }
7230
7231 // (CUDA B.1): Check for invalid calls between targets.
7232 if (getLangOpts().CUDA) {
7233 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7234 // Skip the check for callers that are implicit members, because in this
7235 // case we may not yet know what the member's target is; the target is
7236 // inferred for the member automatically, based on the bases and fields of
7237 // the class.
7238 if (!(Caller && Caller->isImplicit()) &&
7239 !CUDA().IsAllowedCall(Caller, Function)) {
7240 Candidate.Viable = false;
7241 Candidate.FailureKind = ovl_fail_bad_target;
7242 return;
7243 }
7244 }
7245
7246 if (Function->getTrailingRequiresClause()) {
7247 ConstraintSatisfaction Satisfaction;
7248 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7249 /*ForOverloadResolution*/ true) ||
7250 !Satisfaction.IsSatisfied) {
7251 Candidate.Viable = false;
7253 return;
7254 }
7255 }
7256
7257 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7258 // Determine the implicit conversion sequences for each of the
7259 // arguments.
7260 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7261 unsigned ConvIdx =
7262 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7263 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7264 // We already formed a conversion sequence for this parameter during
7265 // template argument deduction.
7266 } else if (ArgIdx < NumParams) {
7267 // (C++ 13.3.2p3): for F to be a viable function, there shall
7268 // exist for each argument an implicit conversion sequence
7269 // (13.3.3.1) that converts that argument to the corresponding
7270 // parameter of F.
7271 QualType ParamType = Proto->getParamType(ArgIdx);
7272 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7273 if (ParamABI == ParameterABI::HLSLOut ||
7274 ParamABI == ParameterABI::HLSLInOut)
7275 ParamType = ParamType.getNonReferenceType();
7276 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7277 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7278 /*InOverloadResolution=*/true,
7279 /*AllowObjCWritebackConversion=*/
7280 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7281 if (Candidate.Conversions[ConvIdx].isBad()) {
7282 Candidate.Viable = false;
7284 return;
7285 }
7286 } else {
7287 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7288 // argument for which there is no corresponding parameter is
7289 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7290 Candidate.Conversions[ConvIdx].setEllipsis();
7291 }
7292 }
7293
7294 if (EnableIfAttr *FailedAttr =
7295 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7296 Candidate.Viable = false;
7297 Candidate.FailureKind = ovl_fail_enable_if;
7298 Candidate.DeductionFailure.Data = FailedAttr;
7299 return;
7300 }
7301}
7302
7306 if (Methods.size() <= 1)
7307 return nullptr;
7308
7309 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7310 bool Match = true;
7311 ObjCMethodDecl *Method = Methods[b];
7312 unsigned NumNamedArgs = Sel.getNumArgs();
7313 // Method might have more arguments than selector indicates. This is due
7314 // to addition of c-style arguments in method.
7315 if (Method->param_size() > NumNamedArgs)
7316 NumNamedArgs = Method->param_size();
7317 if (Args.size() < NumNamedArgs)
7318 continue;
7319
7320 for (unsigned i = 0; i < NumNamedArgs; i++) {
7321 // We can't do any type-checking on a type-dependent argument.
7322 if (Args[i]->isTypeDependent()) {
7323 Match = false;
7324 break;
7325 }
7326
7327 ParmVarDecl *param = Method->parameters()[i];
7328 Expr *argExpr = Args[i];
7329 assert(argExpr && "SelectBestMethod(): missing expression");
7330
7331 // Strip the unbridged-cast placeholder expression off unless it's
7332 // a consumed argument.
7333 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7334 !param->hasAttr<CFConsumedAttr>())
7335 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7336
7337 // If the parameter is __unknown_anytype, move on to the next method.
7338 if (param->getType() == Context.UnknownAnyTy) {
7339 Match = false;
7340 break;
7341 }
7342
7343 ImplicitConversionSequence ConversionState
7344 = TryCopyInitialization(*this, argExpr, param->getType(),
7345 /*SuppressUserConversions*/false,
7346 /*InOverloadResolution=*/true,
7347 /*AllowObjCWritebackConversion=*/
7348 getLangOpts().ObjCAutoRefCount,
7349 /*AllowExplicit*/false);
7350 // This function looks for a reasonably-exact match, so we consider
7351 // incompatible pointer conversions to be a failure here.
7352 if (ConversionState.isBad() ||
7353 (ConversionState.isStandard() &&
7354 ConversionState.Standard.Second ==
7356 Match = false;
7357 break;
7358 }
7359 }
7360 // Promote additional arguments to variadic methods.
7361 if (Match && Method->isVariadic()) {
7362 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7363 if (Args[i]->isTypeDependent()) {
7364 Match = false;
7365 break;
7366 }
7368 Args[i], VariadicCallType::Method, nullptr);
7369 if (Arg.isInvalid()) {
7370 Match = false;
7371 break;
7372 }
7373 }
7374 } else {
7375 // Check for extra arguments to non-variadic methods.
7376 if (Args.size() != NumNamedArgs)
7377 Match = false;
7378 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7379 // Special case when selectors have no argument. In this case, select
7380 // one with the most general result type of 'id'.
7381 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7382 QualType ReturnT = Methods[b]->getReturnType();
7383 if (ReturnT->isObjCIdType())
7384 return Methods[b];
7385 }
7386 }
7387 }
7388
7389 if (Match)
7390 return Method;
7391 }
7392 return nullptr;
7393}
7394
7396 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7397 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7398 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7399 if (ThisArg) {
7400 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7401 assert(!isa<CXXConstructorDecl>(Method) &&
7402 "Shouldn't have `this` for ctors!");
7403 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7405 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7406 if (R.isInvalid())
7407 return false;
7408 ConvertedThis = R.get();
7409 } else {
7410 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7411 (void)MD;
7412 assert((MissingImplicitThis || MD->isStatic() ||
7414 "Expected `this` for non-ctor instance methods");
7415 }
7416 ConvertedThis = nullptr;
7417 }
7418
7419 // Ignore any variadic arguments. Converting them is pointless, since the
7420 // user can't refer to them in the function condition.
7421 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7422
7423 // Convert the arguments.
7424 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7425 ExprResult R;
7427 S.Context, Function->getParamDecl(I)),
7428 SourceLocation(), Args[I]);
7429
7430 if (R.isInvalid())
7431 return false;
7432
7433 ConvertedArgs.push_back(R.get());
7434 }
7435
7436 if (Trap.hasErrorOccurred())
7437 return false;
7438
7439 // Push default arguments if needed.
7440 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7441 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7442 ParmVarDecl *P = Function->getParamDecl(i);
7443 if (!P->hasDefaultArg())
7444 return false;
7445 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7446 if (R.isInvalid())
7447 return false;
7448 ConvertedArgs.push_back(R.get());
7449 }
7450
7451 if (Trap.hasErrorOccurred())
7452 return false;
7453 }
7454 return true;
7455}
7456
7458 SourceLocation CallLoc,
7459 ArrayRef<Expr *> Args,
7460 bool MissingImplicitThis) {
7461 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7462 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7463 return nullptr;
7464
7465 SFINAETrap Trap(*this);
7466 SmallVector<Expr *, 16> ConvertedArgs;
7467 // FIXME: We should look into making enable_if late-parsed.
7468 Expr *DiscardedThis;
7470 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7471 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7472 return *EnableIfAttrs.begin();
7473
7474 for (auto *EIA : EnableIfAttrs) {
7476 // FIXME: This doesn't consider value-dependent cases, because doing so is
7477 // very difficult. Ideally, we should handle them more gracefully.
7478 if (EIA->getCond()->isValueDependent() ||
7479 !EIA->getCond()->EvaluateWithSubstitution(
7480 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7481 return EIA;
7482
7483 if (!Result.isInt() || !Result.getInt().getBoolValue())
7484 return EIA;
7485 }
7486 return nullptr;
7487}
7488
7489template <typename CheckFn>
7491 bool ArgDependent, SourceLocation Loc,
7492 CheckFn &&IsSuccessful) {
7494 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7495 if (ArgDependent == DIA->getArgDependent())
7496 Attrs.push_back(DIA);
7497 }
7498
7499 // Common case: No diagnose_if attributes, so we can quit early.
7500 if (Attrs.empty())
7501 return false;
7502
7503 auto WarningBegin = std::stable_partition(
7504 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7505 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7506 DIA->getWarningGroup().empty();
7507 });
7508
7509 // Note that diagnose_if attributes are late-parsed, so they appear in the
7510 // correct order (unlike enable_if attributes).
7511 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7512 IsSuccessful);
7513 if (ErrAttr != WarningBegin) {
7514 const DiagnoseIfAttr *DIA = *ErrAttr;
7515 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7516 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7517 << DIA->getParent() << DIA->getCond()->getSourceRange();
7518 return true;
7519 }
7520
7521 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7522 switch (Sev) {
7523 case DiagnoseIfAttr::DS_warning:
7525 case DiagnoseIfAttr::DS_error:
7526 return diag::Severity::Error;
7527 }
7528 llvm_unreachable("Fully covered switch above!");
7529 };
7530
7531 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7532 if (IsSuccessful(DIA)) {
7533 if (DIA->getWarningGroup().empty() &&
7534 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7535 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7536 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7537 << DIA->getParent() << DIA->getCond()->getSourceRange();
7538 } else {
7539 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7540 DIA->getWarningGroup());
7541 assert(DiagGroup);
7542 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7543 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7544 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7545 S.Diag(Loc, DiagID) << DIA->getMessage();
7546 }
7547 }
7548
7549 return false;
7550}
7551
7553 const Expr *ThisArg,
7555 SourceLocation Loc) {
7557 *this, Function, /*ArgDependent=*/true, Loc,
7558 [&](const DiagnoseIfAttr *DIA) {
7560 // It's sane to use the same Args for any redecl of this function, since
7561 // EvaluateWithSubstitution only cares about the position of each
7562 // argument in the arg list, not the ParmVarDecl* it maps to.
7563 if (!DIA->getCond()->EvaluateWithSubstitution(
7564 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7565 return false;
7566 return Result.isInt() && Result.getInt().getBoolValue();
7567 });
7568}
7569
7571 SourceLocation Loc) {
7573 *this, ND, /*ArgDependent=*/false, Loc,
7574 [&](const DiagnoseIfAttr *DIA) {
7575 bool Result;
7576 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7577 Result;
7578 });
7579}
7580
7582 ArrayRef<Expr *> Args,
7583 OverloadCandidateSet &CandidateSet,
7584 TemplateArgumentListInfo *ExplicitTemplateArgs,
7585 bool SuppressUserConversions,
7586 bool PartialOverloading,
7587 bool FirstArgumentIsBase) {
7588 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7589 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7590 ArrayRef<Expr *> FunctionArgs = Args;
7591
7592 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7593 FunctionDecl *FD =
7594 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7595
7596 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7597 QualType ObjectType;
7598 Expr::Classification ObjectClassification;
7599 if (Args.size() > 0) {
7600 if (Expr *E = Args[0]) {
7601 // Use the explicit base to restrict the lookup:
7602 ObjectType = E->getType();
7603 // Pointers in the object arguments are implicitly dereferenced, so we
7604 // always classify them as l-values.
7605 if (!ObjectType.isNull() && ObjectType->isPointerType())
7606 ObjectClassification = Expr::Classification::makeSimpleLValue();
7607 else
7608 ObjectClassification = E->Classify(Context);
7609 } // .. else there is an implicit base.
7610 FunctionArgs = Args.slice(1);
7611 }
7612 if (FunTmpl) {
7614 FunTmpl, F.getPair(),
7616 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7617 FunctionArgs, CandidateSet, SuppressUserConversions,
7618 PartialOverloading);
7619 } else {
7620 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7621 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7622 ObjectClassification, FunctionArgs, CandidateSet,
7623 SuppressUserConversions, PartialOverloading);
7624 }
7625 } else {
7626 // This branch handles both standalone functions and static methods.
7627
7628 // Slice the first argument (which is the base) when we access
7629 // static method as non-static.
7630 if (Args.size() > 0 &&
7631 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7632 !isa<CXXConstructorDecl>(FD)))) {
7633 assert(cast<CXXMethodDecl>(FD)->isStatic());
7634 FunctionArgs = Args.slice(1);
7635 }
7636 if (FunTmpl) {
7637 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7638 ExplicitTemplateArgs, FunctionArgs,
7639 CandidateSet, SuppressUserConversions,
7640 PartialOverloading);
7641 } else {
7642 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7643 SuppressUserConversions, PartialOverloading);
7644 }
7645 }
7646 }
7647}
7648
7650 Expr::Classification ObjectClassification,
7651 ArrayRef<Expr *> Args,
7652 OverloadCandidateSet &CandidateSet,
7653 bool SuppressUserConversions,
7655 NamedDecl *Decl = FoundDecl.getDecl();
7657
7659 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7660
7661 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7662 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7663 "Expected a member function template");
7664 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7665 /*ExplicitArgs*/ nullptr, ObjectType,
7666 ObjectClassification, Args, CandidateSet,
7667 SuppressUserConversions, false, PO);
7668 } else {
7669 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7670 ObjectType, ObjectClassification, Args, CandidateSet,
7671 SuppressUserConversions, false, {}, PO);
7672 }
7673}
7674
7677 CXXRecordDecl *ActingContext, QualType ObjectType,
7678 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7679 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7680 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7681 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7682 const FunctionProtoType *Proto
7683 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7684 assert(Proto && "Methods without a prototype cannot be overloaded");
7686 "Use AddOverloadCandidate for constructors");
7687
7688 if (!CandidateSet.isNewCandidate(Method, PO))
7689 return;
7690
7691 // C++11 [class.copy]p23: [DR1402]
7692 // A defaulted move assignment operator that is defined as deleted is
7693 // ignored by overload resolution.
7694 if (Method->isDefaulted() && Method->isDeleted() &&
7695 Method->isMoveAssignmentOperator())
7696 return;
7697
7698 // Overload resolution is always an unevaluated context.
7701
7702 bool IgnoreExplicitObject =
7703 (Method->isExplicitObjectMemberFunction() &&
7704 CandidateSet.getKind() ==
7706 bool ImplicitObjectMethodTreatedAsStatic =
7707 CandidateSet.getKind() ==
7709 Method->isImplicitObjectMemberFunction();
7710
7711 unsigned ExplicitOffset =
7712 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7713
7714 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7715 int(ImplicitObjectMethodTreatedAsStatic);
7716
7717 unsigned ExtraArgs =
7719 ? 0
7720 : 1;
7721
7722 // Add this candidate
7723 OverloadCandidate &Candidate =
7724 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7725 Candidate.FoundDecl = FoundDecl;
7726 Candidate.Function = Method;
7727 Candidate.RewriteKind =
7728 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7729 Candidate.TookAddressOfOverload =
7731 Candidate.ExplicitCallArguments = Args.size();
7732 Candidate.StrictPackMatch = StrictPackMatch;
7733
7734 // (C++ 13.3.2p2): A candidate function having fewer than m
7735 // parameters is viable only if it has an ellipsis in its parameter
7736 // list (8.3.5).
7737 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7738 !Proto->isVariadic() &&
7739 shouldEnforceArgLimit(PartialOverloading, Method)) {
7740 Candidate.Viable = false;
7742 return;
7743 }
7744
7745 // (C++ 13.3.2p2): A candidate function having more than m parameters
7746 // is viable only if the (m+1)st parameter has a default argument
7747 // (8.3.6). For the purposes of overload resolution, the
7748 // parameter list is truncated on the right, so that there are
7749 // exactly m parameters.
7750 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7751 ExplicitOffset +
7752 int(ImplicitObjectMethodTreatedAsStatic);
7753
7754 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7755 // Not enough arguments.
7756 Candidate.Viable = false;
7758 return;
7759 }
7760
7761 Candidate.Viable = true;
7762
7763 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7764 if (!IgnoreExplicitObject) {
7765 if (ObjectType.isNull())
7766 Candidate.IgnoreObjectArgument = true;
7767 else if (Method->isStatic()) {
7768 // [over.best.ics.general]p8
7769 // When the parameter is the implicit object parameter of a static member
7770 // function, the implicit conversion sequence is a standard conversion
7771 // sequence that is neither better nor worse than any other standard
7772 // conversion sequence.
7773 //
7774 // This is a rule that was introduced in C++23 to support static lambdas.
7775 // We apply it retroactively because we want to support static lambdas as
7776 // an extension and it doesn't hurt previous code.
7777 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7778 } else {
7779 // Determine the implicit conversion sequence for the object
7780 // parameter.
7781 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7782 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7783 Method, ActingContext, /*InOverloadResolution=*/true);
7784 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7785 Candidate.Viable = false;
7787 return;
7788 }
7789 }
7790 }
7791
7792 // (CUDA B.1): Check for invalid calls between targets.
7793 if (getLangOpts().CUDA)
7794 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7795 Method)) {
7796 Candidate.Viable = false;
7797 Candidate.FailureKind = ovl_fail_bad_target;
7798 return;
7799 }
7800
7801 if (Method->getTrailingRequiresClause()) {
7802 ConstraintSatisfaction Satisfaction;
7803 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7804 /*ForOverloadResolution*/ true) ||
7805 !Satisfaction.IsSatisfied) {
7806 Candidate.Viable = false;
7808 return;
7809 }
7810 }
7811
7812 // Determine the implicit conversion sequences for each of the
7813 // arguments.
7814 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7815 unsigned ConvIdx =
7816 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7817 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7818 // We already formed a conversion sequence for this parameter during
7819 // template argument deduction.
7820 } else if (ArgIdx < NumParams) {
7821 // (C++ 13.3.2p3): for F to be a viable function, there shall
7822 // exist for each argument an implicit conversion sequence
7823 // (13.3.3.1) that converts that argument to the corresponding
7824 // parameter of F.
7825 QualType ParamType;
7826 if (ImplicitObjectMethodTreatedAsStatic) {
7827 ParamType = ArgIdx == 0
7828 ? Method->getFunctionObjectParameterReferenceType()
7829 : Proto->getParamType(ArgIdx - 1);
7830 } else {
7831 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7832 }
7833 Candidate.Conversions[ConvIdx]
7834 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7835 SuppressUserConversions,
7836 /*InOverloadResolution=*/true,
7837 /*AllowObjCWritebackConversion=*/
7838 getLangOpts().ObjCAutoRefCount);
7839 if (Candidate.Conversions[ConvIdx].isBad()) {
7840 Candidate.Viable = false;
7842 return;
7843 }
7844 } else {
7845 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7846 // argument for which there is no corresponding parameter is
7847 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7848 Candidate.Conversions[ConvIdx].setEllipsis();
7849 }
7850 }
7851
7852 if (EnableIfAttr *FailedAttr =
7853 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7854 Candidate.Viable = false;
7855 Candidate.FailureKind = ovl_fail_enable_if;
7856 Candidate.DeductionFailure.Data = FailedAttr;
7857 return;
7858 }
7859
7861 Candidate.Viable = false;
7863 }
7864}
7865
7867 Sema &S, OverloadCandidateSet &CandidateSet,
7868 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7869 CXXRecordDecl *ActingContext,
7870 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7871 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7872 bool SuppressUserConversions, bool PartialOverloading,
7874
7875 // C++ [over.match.funcs]p7:
7876 // In each case where a candidate is a function template, candidate
7877 // function template specializations are generated using template argument
7878 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7879 // candidate functions in the usual way.113) A given name can refer to one
7880 // or more function templates and also to a set of overloaded non-template
7881 // functions. In such a case, the candidate functions generated from each
7882 // function template are combined with the set of non-template candidate
7883 // functions.
7884 TemplateDeductionInfo Info(CandidateSet.getLocation());
7885 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7886 FunctionDecl *Specialization = nullptr;
7887 ConversionSequenceList Conversions;
7889 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7890 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7891 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7892 CandidateSet.getKind() ==
7894 [&](ArrayRef<QualType> ParamTypes,
7895 bool OnlyInitializeNonUserDefinedConversions) {
7896 return S.CheckNonDependentConversions(
7897 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7898 Sema::CheckNonDependentConversionsFlag(
7899 SuppressUserConversions,
7900 OnlyInitializeNonUserDefinedConversions),
7901 ActingContext, ObjectType, ObjectClassification, PO);
7902 });
7904 OverloadCandidate &Candidate =
7905 CandidateSet.addCandidate(Conversions.size(), Conversions);
7906 Candidate.FoundDecl = FoundDecl;
7907 Candidate.Function = Method;
7908 Candidate.Viable = false;
7909 Candidate.RewriteKind =
7910 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7911 Candidate.IsSurrogate = false;
7912 Candidate.TookAddressOfOverload =
7913 CandidateSet.getKind() ==
7915
7916 Candidate.IgnoreObjectArgument =
7917 Method->isStatic() ||
7918 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7919 Candidate.ExplicitCallArguments = Args.size();
7922 else {
7924 Candidate.DeductionFailure =
7925 MakeDeductionFailureInfo(S.Context, Result, Info);
7926 }
7927 return;
7928 }
7929
7930 // Add the function template specialization produced by template argument
7931 // deduction as a candidate.
7932 assert(Specialization && "Missing member function template specialization?");
7934 "Specialization is not a member function?");
7936 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7937 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7938 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7939}
7940
7942 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7943 CXXRecordDecl *ActingContext,
7944 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7945 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7946 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7947 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7948 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7949 return;
7950
7951 if (ExplicitTemplateArgs ||
7954 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7955 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7956 SuppressUserConversions, PartialOverloading, PO);
7957 return;
7958 }
7959
7961 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7962 Args, SuppressUserConversions, PartialOverloading, PO);
7963}
7964
7965/// Determine whether a given function template has a simple explicit specifier
7966/// or a non-value-dependent explicit-specification that evaluates to true.
7970
7975
7977 Sema &S, OverloadCandidateSet &CandidateSet,
7979 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7980 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7982 bool AggregateCandidateDeduction) {
7983
7984 // If the function template has a non-dependent explicit specification,
7985 // exclude it now if appropriate; we are not permitted to perform deduction
7986 // and substitution in this case.
7987 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7988 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7989 Candidate.FoundDecl = FoundDecl;
7990 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7991 Candidate.Viable = false;
7992 Candidate.FailureKind = ovl_fail_explicit;
7993 return;
7994 }
7995
7996 // C++ [over.match.funcs]p7:
7997 // In each case where a candidate is a function template, candidate
7998 // function template specializations are generated using template argument
7999 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8000 // candidate functions in the usual way.113) A given name can refer to one
8001 // or more function templates and also to a set of overloaded non-template
8002 // functions. In such a case, the candidate functions generated from each
8003 // function template are combined with the set of non-template candidate
8004 // functions.
8005 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8006 FunctionTemplate->getTemplateDepth());
8007 FunctionDecl *Specialization = nullptr;
8008 ConversionSequenceList Conversions;
8010 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8011 PartialOverloading, AggregateCandidateDeduction,
8012 /*PartialOrdering=*/false,
8013 /*ObjectType=*/QualType(),
8014 /*ObjectClassification=*/Expr::Classification(),
8015 CandidateSet.getKind() ==
8017 [&](ArrayRef<QualType> ParamTypes,
8018 bool OnlyInitializeNonUserDefinedConversions) {
8019 return S.CheckNonDependentConversions(
8020 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8021 Sema::CheckNonDependentConversionsFlag(
8022 SuppressUserConversions,
8023 OnlyInitializeNonUserDefinedConversions),
8024 nullptr, QualType(), {}, PO);
8025 });
8027 OverloadCandidate &Candidate =
8028 CandidateSet.addCandidate(Conversions.size(), Conversions);
8029 Candidate.FoundDecl = FoundDecl;
8030 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8031 Candidate.Viable = false;
8032 Candidate.RewriteKind =
8033 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8034 Candidate.IsSurrogate = false;
8035 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8036 // Ignore the object argument if there is one, since we don't have an object
8037 // type.
8038 Candidate.TookAddressOfOverload =
8039 CandidateSet.getKind() ==
8041
8042 Candidate.IgnoreObjectArgument =
8043 isa<CXXMethodDecl>(Candidate.Function) &&
8044 !cast<CXXMethodDecl>(Candidate.Function)
8045 ->isExplicitObjectMemberFunction() &&
8047
8048 Candidate.ExplicitCallArguments = Args.size();
8051 else {
8053 Candidate.DeductionFailure =
8055 }
8056 return;
8057 }
8058
8059 // Add the function template specialization produced by template argument
8060 // deduction as a candidate.
8061 assert(Specialization && "Missing function template specialization?");
8063 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8064 PartialOverloading, AllowExplicit,
8065 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8066 Info.AggregateDeductionCandidateHasMismatchedArity,
8067 Info.hasStrictPackMatch());
8068}
8069
8072 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8073 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8074 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8075 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8076 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8077 return;
8078
8079 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8080
8081 if (ExplicitTemplateArgs ||
8083 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8084 DependentExplicitSpecifier)) {
8085
8087 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8088 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8089 IsADLCandidate, PO, AggregateCandidateDeduction);
8090
8091 if (DependentExplicitSpecifier)
8093 return;
8094 }
8095
8096 CandidateSet.AddDeferredTemplateCandidate(
8097 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8098 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8099 AggregateCandidateDeduction);
8100}
8101
8104 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8106 CheckNonDependentConversionsFlag UserConversionFlag,
8107 CXXRecordDecl *ActingContext, QualType ObjectType,
8108 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8109 // FIXME: The cases in which we allow explicit conversions for constructor
8110 // arguments never consider calling a constructor template. It's not clear
8111 // that is correct.
8112 const bool AllowExplicit = false;
8113
8114 bool ForOverloadSetAddressResolution =
8116 auto *FD = FunctionTemplate->getTemplatedDecl();
8117 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8118 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8120 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8121
8122 if (Conversions.empty())
8123 Conversions =
8124 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8125
8126 // Overload resolution is always an unevaluated context.
8129
8130 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8131 // require that, but this check should never result in a hard error, and
8132 // overload resolution is permitted to sidestep instantiations.
8133 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8134 !ObjectType.isNull()) {
8135 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8136 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8137 !ParamTypes[0]->isDependentType()) {
8139 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8140 Method, ActingContext, /*InOverloadResolution=*/true,
8141 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8142 : QualType());
8143 if (Conversions[ConvIdx].isBad())
8144 return true;
8145 }
8146 }
8147
8148 // A speculative workaround for self-dependent constraint bugs that manifest
8149 // after CWG2369.
8150 // FIXME: Add references to the standard once P3606 is adopted.
8151 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8152 QualType ArgType) {
8153 ParamType = ParamType.getNonReferenceType();
8154 ArgType = ArgType.getNonReferenceType();
8155 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8156 if (PointerConv) {
8157 ParamType = ParamType->getPointeeType();
8158 ArgType = ArgType->getPointeeType();
8159 }
8160
8161 if (auto *RD = ParamType->getAsCXXRecordDecl();
8162 RD && RD->hasDefinition() &&
8163 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8164 auto Info = getConstructorInfo(ND);
8165 if (!Info)
8166 return false;
8167 CXXConstructorDecl *Ctor = Info.Constructor;
8168 /// isConvertingConstructor takes copy/move constructors into
8169 /// account!
8170 return !Ctor->isCopyOrMoveConstructor() &&
8172 /*AllowExplicit=*/true);
8173 }))
8174 return true;
8175 if (auto *RD = ArgType->getAsCXXRecordDecl();
8176 RD && RD->hasDefinition() &&
8177 !RD->getVisibleConversionFunctions().empty())
8178 return true;
8179
8180 return false;
8181 };
8182
8183 unsigned Offset =
8184 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8185 : 0;
8186
8187 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8188 I != N; ++I) {
8189 QualType ParamType = ParamTypes[I + Offset];
8190 if (!ParamType->isDependentType()) {
8191 unsigned ConvIdx;
8193 ConvIdx = Args.size() - 1 - I;
8194 assert(Args.size() + ThisConversions == 2 &&
8195 "number of args (including 'this') must be exactly 2 for "
8196 "reversed order");
8197 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8198 // would also be 0. 'this' got ConvIdx = 1 previously.
8199 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8200 } else {
8201 // For members, 'this' got ConvIdx = 0 previously.
8202 ConvIdx = ThisConversions + I;
8203 }
8204 if (Conversions[ConvIdx].isInitialized())
8205 continue;
8206 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8207 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8208 continue;
8210 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8211 /*InOverloadResolution=*/true,
8212 /*AllowObjCWritebackConversion=*/
8213 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8214 if (Conversions[ConvIdx].isBad())
8215 return true;
8216 }
8217 }
8218
8219 return false;
8220}
8221
8222/// Determine whether this is an allowable conversion from the result
8223/// of an explicit conversion operator to the expected type, per C++
8224/// [over.match.conv]p1 and [over.match.ref]p1.
8225///
8226/// \param ConvType The return type of the conversion function.
8227///
8228/// \param ToType The type we are converting to.
8229///
8230/// \param AllowObjCPointerConversion Allow a conversion from one
8231/// Objective-C pointer to another.
8232///
8233/// \returns true if the conversion is allowable, false otherwise.
8235 QualType ConvType, QualType ToType,
8236 bool AllowObjCPointerConversion) {
8237 QualType ToNonRefType = ToType.getNonReferenceType();
8238
8239 // Easy case: the types are the same.
8240 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8241 return true;
8242
8243 // Allow qualification conversions.
8244 bool ObjCLifetimeConversion;
8245 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8246 ObjCLifetimeConversion))
8247 return true;
8248
8249 // If we're not allowed to consider Objective-C pointer conversions,
8250 // we're done.
8251 if (!AllowObjCPointerConversion)
8252 return false;
8253
8254 // Is this an Objective-C pointer conversion?
8255 bool IncompatibleObjC = false;
8256 QualType ConvertedType;
8257 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8258 IncompatibleObjC);
8259}
8260
8262 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8263 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8264 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8265 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8266 assert(!Conversion->getDescribedFunctionTemplate() &&
8267 "Conversion function templates use AddTemplateConversionCandidate");
8268 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8269 if (!CandidateSet.isNewCandidate(Conversion))
8270 return;
8271
8272 // If the conversion function has an undeduced return type, trigger its
8273 // deduction now.
8274 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8275 if (DeduceReturnType(Conversion, From->getExprLoc()))
8276 return;
8277 ConvType = Conversion->getConversionType().getNonReferenceType();
8278 }
8279
8280 // If we don't allow any conversion of the result type, ignore conversion
8281 // functions that don't convert to exactly (possibly cv-qualified) T.
8282 if (!AllowResultConversion &&
8283 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8284 return;
8285
8286 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8287 // operator is only a candidate if its return type is the target type or
8288 // can be converted to the target type with a qualification conversion.
8289 //
8290 // FIXME: Include such functions in the candidate list and explain why we
8291 // can't select them.
8292 if (Conversion->isExplicit() &&
8293 !isAllowableExplicitConversion(*this, ConvType, ToType,
8294 AllowObjCConversionOnExplicit))
8295 return;
8296
8297 // Overload resolution is always an unevaluated context.
8300
8301 // Add this candidate
8302 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8303 Candidate.FoundDecl = FoundDecl;
8304 Candidate.Function = Conversion;
8306 Candidate.FinalConversion.setFromType(ConvType);
8307 Candidate.FinalConversion.setAllToTypes(ToType);
8308 Candidate.HasFinalConversion = true;
8309 Candidate.Viable = true;
8310 Candidate.ExplicitCallArguments = 1;
8311 Candidate.StrictPackMatch = StrictPackMatch;
8312
8313 // Explicit functions are not actually candidates at all if we're not
8314 // allowing them in this context, but keep them around so we can point
8315 // to them in diagnostics.
8316 if (!AllowExplicit && Conversion->isExplicit()) {
8317 Candidate.Viable = false;
8318 Candidate.FailureKind = ovl_fail_explicit;
8319 return;
8320 }
8321
8322 // C++ [over.match.funcs]p4:
8323 // For conversion functions, the function is considered to be a member of
8324 // the class of the implicit implied object argument for the purpose of
8325 // defining the type of the implicit object parameter.
8326 //
8327 // Determine the implicit conversion sequence for the implicit
8328 // object parameter.
8329 QualType ObjectType = From->getType();
8330 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8331 ObjectType = FromPtrType->getPointeeType();
8332 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8333 // C++23 [over.best.ics.general]
8334 // However, if the target is [...]
8335 // - the object parameter of a user-defined conversion function
8336 // [...] user-defined conversion sequences are not considered.
8338 *this, CandidateSet.getLocation(), From->getType(),
8339 From->Classify(Context), Conversion, ConversionContext,
8340 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8341 /*SuppressUserConversion*/ true);
8342
8343 if (Candidate.Conversions[0].isBad()) {
8344 Candidate.Viable = false;
8346 return;
8347 }
8348
8349 if (Conversion->getTrailingRequiresClause()) {
8350 ConstraintSatisfaction Satisfaction;
8351 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8352 !Satisfaction.IsSatisfied) {
8353 Candidate.Viable = false;
8355 return;
8356 }
8357 }
8358
8359 // We won't go through a user-defined type conversion function to convert a
8360 // derived to base as such conversions are given Conversion Rank. They only
8361 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8362 QualType FromCanon
8363 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8364 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8365 if (FromCanon == ToCanon ||
8366 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8367 Candidate.Viable = false;
8369 return;
8370 }
8371
8372 // To determine what the conversion from the result of calling the
8373 // conversion function to the type we're eventually trying to
8374 // convert to (ToType), we need to synthesize a call to the
8375 // conversion function and attempt copy initialization from it. This
8376 // makes sure that we get the right semantics with respect to
8377 // lvalues/rvalues and the type. Fortunately, we can allocate this
8378 // call on the stack and we don't need its arguments to be
8379 // well-formed.
8380 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8381 VK_LValue, From->getBeginLoc());
8383 Context.getPointerType(Conversion->getType()),
8384 CK_FunctionToPointerDecay, &ConversionRef,
8386
8387 QualType ConversionType = Conversion->getConversionType();
8388 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8389 Candidate.Viable = false;
8391 return;
8392 }
8393
8394 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8395
8396 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8397
8398 // Introduce a temporary expression with the right type and value category
8399 // that we can use for deduction purposes.
8400 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8401
8403 TryCopyInitialization(*this, &FakeCall, ToType,
8404 /*SuppressUserConversions=*/true,
8405 /*InOverloadResolution=*/false,
8406 /*AllowObjCWritebackConversion=*/false);
8407
8408 switch (ICS.getKind()) {
8410 Candidate.FinalConversion = ICS.Standard;
8411 Candidate.HasFinalConversion = true;
8412
8413 // C++ [over.ics.user]p3:
8414 // If the user-defined conversion is specified by a specialization of a
8415 // conversion function template, the second standard conversion sequence
8416 // shall have exact match rank.
8417 if (Conversion->getPrimaryTemplate() &&
8419 Candidate.Viable = false;
8421 return;
8422 }
8423
8424 // C++0x [dcl.init.ref]p5:
8425 // In the second case, if the reference is an rvalue reference and
8426 // the second standard conversion sequence of the user-defined
8427 // conversion sequence includes an lvalue-to-rvalue conversion, the
8428 // program is ill-formed.
8429 if (ToType->isRValueReferenceType() &&
8431 Candidate.Viable = false;
8433 return;
8434 }
8435 break;
8436
8438 Candidate.Viable = false;
8440 return;
8441
8442 default:
8443 llvm_unreachable(
8444 "Can only end up with a standard conversion sequence or failure");
8445 }
8446
8447 if (EnableIfAttr *FailedAttr =
8448 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8449 Candidate.Viable = false;
8450 Candidate.FailureKind = ovl_fail_enable_if;
8451 Candidate.DeductionFailure.Data = FailedAttr;
8452 return;
8453 }
8454
8455 if (isNonViableMultiVersionOverload(Conversion)) {
8456 Candidate.Viable = false;
8458 }
8459}
8460
8462 Sema &S, OverloadCandidateSet &CandidateSet,
8464 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8465 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8466 bool AllowResultConversion) {
8467
8468 // If the function template has a non-dependent explicit specification,
8469 // exclude it now if appropriate; we are not permitted to perform deduction
8470 // and substitution in this case.
8471 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8472 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8473 Candidate.FoundDecl = FoundDecl;
8474 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8475 Candidate.Viable = false;
8476 Candidate.FailureKind = ovl_fail_explicit;
8477 return;
8478 }
8479
8480 QualType ObjectType = From->getType();
8481 Expr::Classification ObjectClassification = From->Classify(S.Context);
8482
8483 TemplateDeductionInfo Info(CandidateSet.getLocation());
8486 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8487 Specialization, Info);
8489 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8490 Candidate.FoundDecl = FoundDecl;
8491 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8492 Candidate.Viable = false;
8494 Candidate.ExplicitCallArguments = 1;
8495 Candidate.DeductionFailure =
8496 MakeDeductionFailureInfo(S.Context, Result, Info);
8497 return;
8498 }
8499
8500 // Add the conversion function template specialization produced by
8501 // template argument deduction as a candidate.
8502 assert(Specialization && "Missing function template specialization?");
8503 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8504 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8505 AllowExplicit, AllowResultConversion,
8506 Info.hasStrictPackMatch());
8507}
8508
8511 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8512 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8513 bool AllowExplicit, bool AllowResultConversion) {
8514 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8515 "Only conversion function templates permitted here");
8516
8517 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8518 return;
8519
8521 CandidateSet.getKind() ==
8525 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8526 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8527 AllowResultConversion);
8528
8530 return;
8531 }
8532
8534 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8535 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8536}
8537
8539 DeclAccessPair FoundDecl,
8540 CXXRecordDecl *ActingContext,
8541 const FunctionProtoType *Proto,
8542 Expr *Object,
8543 ArrayRef<Expr *> Args,
8544 OverloadCandidateSet& CandidateSet) {
8545 if (!CandidateSet.isNewCandidate(Conversion))
8546 return;
8547
8548 // Overload resolution is always an unevaluated context.
8551
8552 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8553 Candidate.FoundDecl = FoundDecl;
8554 Candidate.Function = nullptr;
8555 Candidate.Surrogate = Conversion;
8556 Candidate.IsSurrogate = true;
8557 Candidate.Viable = true;
8558 Candidate.ExplicitCallArguments = Args.size();
8559
8560 // Determine the implicit conversion sequence for the implicit
8561 // object parameter.
8562 ImplicitConversionSequence ObjectInit;
8563 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8564 ObjectInit = TryCopyInitialization(*this, Object,
8565 Conversion->getParamDecl(0)->getType(),
8566 /*SuppressUserConversions=*/false,
8567 /*InOverloadResolution=*/true, false);
8568 } else {
8570 *this, CandidateSet.getLocation(), Object->getType(),
8571 Object->Classify(Context), Conversion, ActingContext);
8572 }
8573
8574 if (ObjectInit.isBad()) {
8575 Candidate.Viable = false;
8577 Candidate.Conversions[0] = ObjectInit;
8578 return;
8579 }
8580
8581 // The first conversion is actually a user-defined conversion whose
8582 // first conversion is ObjectInit's standard conversion (which is
8583 // effectively a reference binding). Record it as such.
8584 Candidate.Conversions[0].setUserDefined();
8585 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8586 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8587 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8588 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8589 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8590 Candidate.Conversions[0].UserDefined.After
8591 = Candidate.Conversions[0].UserDefined.Before;
8592 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8593
8594 // Find the
8595 unsigned NumParams = Proto->getNumParams();
8596
8597 // (C++ 13.3.2p2): A candidate function having fewer than m
8598 // parameters is viable only if it has an ellipsis in its parameter
8599 // list (8.3.5).
8600 if (Args.size() > NumParams && !Proto->isVariadic()) {
8601 Candidate.Viable = false;
8603 return;
8604 }
8605
8606 // Function types don't have any default arguments, so just check if
8607 // we have enough arguments.
8608 if (Args.size() < NumParams) {
8609 // Not enough arguments.
8610 Candidate.Viable = false;
8612 return;
8613 }
8614
8615 // Determine the implicit conversion sequences for each of the
8616 // arguments.
8617 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8618 if (ArgIdx < NumParams) {
8619 // (C++ 13.3.2p3): for F to be a viable function, there shall
8620 // exist for each argument an implicit conversion sequence
8621 // (13.3.3.1) that converts that argument to the corresponding
8622 // parameter of F.
8623 QualType ParamType = Proto->getParamType(ArgIdx);
8624 Candidate.Conversions[ArgIdx + 1]
8625 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8626 /*SuppressUserConversions=*/false,
8627 /*InOverloadResolution=*/false,
8628 /*AllowObjCWritebackConversion=*/
8629 getLangOpts().ObjCAutoRefCount);
8630 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8631 Candidate.Viable = false;
8633 return;
8634 }
8635 } else {
8636 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8637 // argument for which there is no corresponding parameter is
8638 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8639 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8640 }
8641 }
8642
8643 if (Conversion->getTrailingRequiresClause()) {
8644 ConstraintSatisfaction Satisfaction;
8645 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8646 /*ForOverloadResolution*/ true) ||
8647 !Satisfaction.IsSatisfied) {
8648 Candidate.Viable = false;
8650 return;
8651 }
8652 }
8653
8654 if (EnableIfAttr *FailedAttr =
8655 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8656 Candidate.Viable = false;
8657 Candidate.FailureKind = ovl_fail_enable_if;
8658 Candidate.DeductionFailure.Data = FailedAttr;
8659 return;
8660 }
8661}
8662
8664 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8665 OverloadCandidateSet &CandidateSet,
8666 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8667 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8668 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8669 ArrayRef<Expr *> FunctionArgs = Args;
8670
8671 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8672 FunctionDecl *FD =
8673 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8674
8675 // Don't consider rewritten functions if we're not rewriting.
8676 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8677 continue;
8678
8679 assert(!isa<CXXMethodDecl>(FD) &&
8680 "unqualified operator lookup found a member function");
8681
8682 if (FunTmpl) {
8683 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8684 FunctionArgs, CandidateSet);
8685 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8686
8687 // As template candidates are not deduced immediately,
8688 // persist the array in the overload set.
8690 FunctionArgs[1], FunctionArgs[0]);
8691 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8692 Reversed, CandidateSet, false, false, true,
8693 ADLCallKind::NotADL,
8695 }
8696 } else {
8697 if (ExplicitTemplateArgs)
8698 continue;
8699 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8700 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8701 AddOverloadCandidate(FD, F.getPair(),
8702 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8703 false, false, true, false, ADLCallKind::NotADL, {},
8705 }
8706 }
8707}
8708
8710 SourceLocation OpLoc,
8711 ArrayRef<Expr *> Args,
8712 OverloadCandidateSet &CandidateSet,
8714 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8715
8716 // C++ [over.match.oper]p3:
8717 // For a unary operator @ with an operand of a type whose
8718 // cv-unqualified version is T1, and for a binary operator @ with
8719 // a left operand of a type whose cv-unqualified version is T1 and
8720 // a right operand of a type whose cv-unqualified version is T2,
8721 // three sets of candidate functions, designated member
8722 // candidates, non-member candidates and built-in candidates, are
8723 // constructed as follows:
8724 QualType T1 = Args[0]->getType();
8725
8726 // -- If T1 is a complete class type or a class currently being
8727 // defined, the set of member candidates is the result of the
8728 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8729 // the set of member candidates is empty.
8730 if (T1->isRecordType()) {
8731 bool IsComplete = isCompleteType(OpLoc, T1);
8732 auto *T1RD = T1->getAsCXXRecordDecl();
8733 // Complete the type if it can be completed.
8734 // If the type is neither complete nor being defined, bail out now.
8735 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8736 return;
8737
8738 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8739 LookupQualifiedName(Operators, T1RD);
8740 Operators.suppressAccessDiagnostics();
8741
8742 for (LookupResult::iterator Oper = Operators.begin(),
8743 OperEnd = Operators.end();
8744 Oper != OperEnd; ++Oper) {
8745 if (Oper->getAsFunction() &&
8747 !CandidateSet.getRewriteInfo().shouldAddReversed(
8748 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8749 continue;
8750 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8751 Args[0]->Classify(Context), Args.slice(1),
8752 CandidateSet, /*SuppressUserConversion=*/false, PO);
8753 }
8754 }
8755}
8756
8758 OverloadCandidateSet& CandidateSet,
8759 bool IsAssignmentOperator,
8760 unsigned NumContextualBoolArguments) {
8761 // Overload resolution is always an unevaluated context.
8764
8765 // Add this candidate
8766 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8767 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8768 Candidate.Function = nullptr;
8769 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8770
8771 // Determine the implicit conversion sequences for each of the
8772 // arguments.
8773 Candidate.Viable = true;
8774 Candidate.ExplicitCallArguments = Args.size();
8775 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8776 // C++ [over.match.oper]p4:
8777 // For the built-in assignment operators, conversions of the
8778 // left operand are restricted as follows:
8779 // -- no temporaries are introduced to hold the left operand, and
8780 // -- no user-defined conversions are applied to the left
8781 // operand to achieve a type match with the left-most
8782 // parameter of a built-in candidate.
8783 //
8784 // We block these conversions by turning off user-defined
8785 // conversions, since that is the only way that initialization of
8786 // a reference to a non-class type can occur from something that
8787 // is not of the same type.
8788 if (ArgIdx < NumContextualBoolArguments) {
8789 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8790 "Contextual conversion to bool requires bool type");
8791 Candidate.Conversions[ArgIdx]
8792 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8793 } else {
8794 Candidate.Conversions[ArgIdx]
8795 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8796 ArgIdx == 0 && IsAssignmentOperator,
8797 /*InOverloadResolution=*/false,
8798 /*AllowObjCWritebackConversion=*/
8799 getLangOpts().ObjCAutoRefCount);
8800 }
8801 if (Candidate.Conversions[ArgIdx].isBad()) {
8802 Candidate.Viable = false;
8804 break;
8805 }
8806 }
8807}
8808
8809namespace {
8810
8811/// BuiltinCandidateTypeSet - A set of types that will be used for the
8812/// candidate operator functions for built-in operators (C++
8813/// [over.built]). The types are separated into pointer types and
8814/// enumeration types.
8815class BuiltinCandidateTypeSet {
8816 /// TypeSet - A set of types.
8817 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8818
8819 /// PointerTypes - The set of pointer types that will be used in the
8820 /// built-in candidates.
8821 TypeSet PointerTypes;
8822
8823 /// MemberPointerTypes - The set of member pointer types that will be
8824 /// used in the built-in candidates.
8825 TypeSet MemberPointerTypes;
8826
8827 /// EnumerationTypes - The set of enumeration types that will be
8828 /// used in the built-in candidates.
8829 TypeSet EnumerationTypes;
8830
8831 /// The set of vector types that will be used in the built-in
8832 /// candidates.
8833 TypeSet VectorTypes;
8834
8835 /// The set of matrix types that will be used in the built-in
8836 /// candidates.
8837 TypeSet MatrixTypes;
8838
8839 /// The set of _BitInt types that will be used in the built-in candidates.
8840 TypeSet BitIntTypes;
8841
8842 /// A flag indicating non-record types are viable candidates
8843 bool HasNonRecordTypes;
8844
8845 /// A flag indicating whether either arithmetic or enumeration types
8846 /// were present in the candidate set.
8847 bool HasArithmeticOrEnumeralTypes;
8848
8849 /// A flag indicating whether the nullptr type was present in the
8850 /// candidate set.
8851 bool HasNullPtrType;
8852
8853 /// Sema - The semantic analysis instance where we are building the
8854 /// candidate type set.
8855 Sema &SemaRef;
8856
8857 /// Context - The AST context in which we will build the type sets.
8858 ASTContext &Context;
8859
8860 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8861 const Qualifiers &VisibleQuals);
8862 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8863
8864public:
8865 /// iterator - Iterates through the types that are part of the set.
8866 typedef TypeSet::iterator iterator;
8867
8868 BuiltinCandidateTypeSet(Sema &SemaRef)
8869 : HasNonRecordTypes(false),
8870 HasArithmeticOrEnumeralTypes(false),
8871 HasNullPtrType(false),
8872 SemaRef(SemaRef),
8873 Context(SemaRef.Context) { }
8874
8875 void AddTypesConvertedFrom(QualType Ty,
8876 SourceLocation Loc,
8877 bool AllowUserConversions,
8878 bool AllowExplicitConversions,
8879 const Qualifiers &VisibleTypeConversionsQuals);
8880
8881 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8882 llvm::iterator_range<iterator> member_pointer_types() {
8883 return MemberPointerTypes;
8884 }
8885 llvm::iterator_range<iterator> enumeration_types() {
8886 return EnumerationTypes;
8887 }
8888 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8889 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8890 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8891
8892 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8893 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8894 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8895 bool hasNullPtrType() const { return HasNullPtrType; }
8896};
8897
8898} // end anonymous namespace
8899
8900/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8901/// the set of pointer types along with any more-qualified variants of
8902/// that type. For example, if @p Ty is "int const *", this routine
8903/// will add "int const *", "int const volatile *", "int const
8904/// restrict *", and "int const volatile restrict *" to the set of
8905/// pointer types. Returns true if the add of @p Ty itself succeeded,
8906/// false otherwise.
8907///
8908/// FIXME: what to do about extended qualifiers?
8909bool
8910BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8911 const Qualifiers &VisibleQuals) {
8912
8913 // Insert this type.
8914 if (!PointerTypes.insert(Ty))
8915 return false;
8916
8917 QualType PointeeTy;
8918 const PointerType *PointerTy = Ty->getAs<PointerType>();
8919 bool buildObjCPtr = false;
8920 if (!PointerTy) {
8921 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8922 PointeeTy = PTy->getPointeeType();
8923 buildObjCPtr = true;
8924 } else {
8925 PointeeTy = PointerTy->getPointeeType();
8926 }
8927
8928 // Don't add qualified variants of arrays. For one, they're not allowed
8929 // (the qualifier would sink to the element type), and for another, the
8930 // only overload situation where it matters is subscript or pointer +- int,
8931 // and those shouldn't have qualifier variants anyway.
8932 if (PointeeTy->isArrayType())
8933 return true;
8934
8935 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8936 bool hasVolatile = VisibleQuals.hasVolatile();
8937 bool hasRestrict = VisibleQuals.hasRestrict();
8938
8939 // Iterate through all strict supersets of BaseCVR.
8940 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8941 if ((CVR | BaseCVR) != CVR) continue;
8942 // Skip over volatile if no volatile found anywhere in the types.
8943 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8944
8945 // Skip over restrict if no restrict found anywhere in the types, or if
8946 // the type cannot be restrict-qualified.
8947 if ((CVR & Qualifiers::Restrict) &&
8948 (!hasRestrict ||
8949 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8950 continue;
8951
8952 // Build qualified pointee type.
8953 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8954
8955 // Build qualified pointer type.
8956 QualType QPointerTy;
8957 if (!buildObjCPtr)
8958 QPointerTy = Context.getPointerType(QPointeeTy);
8959 else
8960 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8961
8962 // Insert qualified pointer type.
8963 PointerTypes.insert(QPointerTy);
8964 }
8965
8966 return true;
8967}
8968
8969/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8970/// to the set of pointer types along with any more-qualified variants of
8971/// that type. For example, if @p Ty is "int const *", this routine
8972/// will add "int const *", "int const volatile *", "int const
8973/// restrict *", and "int const volatile restrict *" to the set of
8974/// pointer types. Returns true if the add of @p Ty itself succeeded,
8975/// false otherwise.
8976///
8977/// FIXME: what to do about extended qualifiers?
8978bool
8979BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8980 QualType Ty) {
8981 // Insert this type.
8982 if (!MemberPointerTypes.insert(Ty))
8983 return false;
8984
8985 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8986 assert(PointerTy && "type was not a member pointer type!");
8987
8988 QualType PointeeTy = PointerTy->getPointeeType();
8989 // Don't add qualified variants of arrays. For one, they're not allowed
8990 // (the qualifier would sink to the element type), and for another, the
8991 // only overload situation where it matters is subscript or pointer +- int,
8992 // and those shouldn't have qualifier variants anyway.
8993 if (PointeeTy->isArrayType())
8994 return true;
8995 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
8996
8997 // Iterate through all strict supersets of the pointee type's CVR
8998 // qualifiers.
8999 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9000 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9001 if ((CVR | BaseCVR) != CVR) continue;
9002
9003 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9004 MemberPointerTypes.insert(Context.getMemberPointerType(
9005 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9006 }
9007
9008 return true;
9009}
9010
9011/// AddTypesConvertedFrom - Add each of the types to which the type @p
9012/// Ty can be implicit converted to the given set of @p Types. We're
9013/// primarily interested in pointer types and enumeration types. We also
9014/// take member pointer types, for the conditional operator.
9015/// AllowUserConversions is true if we should look at the conversion
9016/// functions of a class type, and AllowExplicitConversions if we
9017/// should also include the explicit conversion functions of a class
9018/// type.
9019void
9020BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9021 SourceLocation Loc,
9022 bool AllowUserConversions,
9023 bool AllowExplicitConversions,
9024 const Qualifiers &VisibleQuals) {
9025 // Only deal with canonical types.
9026 Ty = Context.getCanonicalType(Ty);
9027
9028 // Look through reference types; they aren't part of the type of an
9029 // expression for the purposes of conversions.
9030 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9031 Ty = RefTy->getPointeeType();
9032
9033 // If we're dealing with an array type, decay to the pointer.
9034 if (Ty->isArrayType())
9035 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9036
9037 // Otherwise, we don't care about qualifiers on the type.
9038 Ty = Ty.getLocalUnqualifiedType();
9039
9040 // Flag if we ever add a non-record type.
9041 bool TyIsRec = Ty->isRecordType();
9042 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9043
9044 // Flag if we encounter an arithmetic type.
9045 HasArithmeticOrEnumeralTypes =
9046 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9047
9048 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9049 PointerTypes.insert(Ty);
9050 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9051 // Insert our type, and its more-qualified variants, into the set
9052 // of types.
9053 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9054 return;
9055 } else if (Ty->isMemberPointerType()) {
9056 // Member pointers are far easier, since the pointee can't be converted.
9057 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9058 return;
9059 } else if (Ty->isEnumeralType()) {
9060 HasArithmeticOrEnumeralTypes = true;
9061 EnumerationTypes.insert(Ty);
9062 } else if (Ty->isBitIntType()) {
9063 HasArithmeticOrEnumeralTypes = true;
9064 BitIntTypes.insert(Ty);
9065 } else if (Ty->isVectorType()) {
9066 // We treat vector types as arithmetic types in many contexts as an
9067 // extension.
9068 HasArithmeticOrEnumeralTypes = true;
9069 VectorTypes.insert(Ty);
9070 } else if (Ty->isMatrixType()) {
9071 // Similar to vector types, we treat vector types as arithmetic types in
9072 // many contexts as an extension.
9073 HasArithmeticOrEnumeralTypes = true;
9074 MatrixTypes.insert(Ty);
9075 } else if (Ty->isNullPtrType()) {
9076 HasNullPtrType = true;
9077 } else if (AllowUserConversions && TyIsRec) {
9078 // No conversion functions in incomplete types.
9079 if (!SemaRef.isCompleteType(Loc, Ty))
9080 return;
9081
9082 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9083 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9084 if (isa<UsingShadowDecl>(D))
9085 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9086
9087 // Skip conversion function templates; they don't tell us anything
9088 // about which builtin types we can convert to.
9090 continue;
9091
9092 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9093 if (AllowExplicitConversions || !Conv->isExplicit()) {
9094 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9095 VisibleQuals);
9096 }
9097 }
9098 }
9099}
9100/// Helper function for adjusting address spaces for the pointer or reference
9101/// operands of builtin operators depending on the argument.
9106
9107/// Helper function for AddBuiltinOperatorCandidates() that adds
9108/// the volatile- and non-volatile-qualified assignment operators for the
9109/// given type to the candidate set.
9111 QualType T,
9112 ArrayRef<Expr *> Args,
9113 OverloadCandidateSet &CandidateSet) {
9114 QualType ParamTypes[2];
9115
9116 // T& operator=(T&, T)
9117 ParamTypes[0] = S.Context.getLValueReferenceType(
9119 ParamTypes[1] = T;
9120 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9121 /*IsAssignmentOperator=*/true);
9122
9124 // volatile T& operator=(volatile T&, T)
9125 ParamTypes[0] = S.Context.getLValueReferenceType(
9127 Args[0]));
9128 ParamTypes[1] = T;
9129 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9130 /*IsAssignmentOperator=*/true);
9131 }
9132}
9133
9134/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9135/// if any, found in visible type conversion functions found in ArgExpr's type.
9136static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9137 Qualifiers VRQuals;
9138 CXXRecordDecl *ClassDecl;
9139 if (const MemberPointerType *RHSMPType =
9140 ArgExpr->getType()->getAs<MemberPointerType>())
9141 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9142 else
9143 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9144 if (!ClassDecl) {
9145 // Just to be safe, assume the worst case.
9146 VRQuals.addVolatile();
9147 VRQuals.addRestrict();
9148 return VRQuals;
9149 }
9150 if (!ClassDecl->hasDefinition())
9151 return VRQuals;
9152
9153 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9154 if (isa<UsingShadowDecl>(D))
9155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9156 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9157 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9158 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9159 CanTy = ResTypeRef->getPointeeType();
9160 // Need to go down the pointer/mempointer chain and add qualifiers
9161 // as see them.
9162 bool done = false;
9163 while (!done) {
9164 if (CanTy.isRestrictQualified())
9165 VRQuals.addRestrict();
9166 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9167 CanTy = ResTypePtr->getPointeeType();
9168 else if (const MemberPointerType *ResTypeMPtr =
9169 CanTy->getAs<MemberPointerType>())
9170 CanTy = ResTypeMPtr->getPointeeType();
9171 else
9172 done = true;
9173 if (CanTy.isVolatileQualified())
9174 VRQuals.addVolatile();
9175 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9176 return VRQuals;
9177 }
9178 }
9179 }
9180 return VRQuals;
9181}
9182
9183// Note: We're currently only handling qualifiers that are meaningful for the
9184// LHS of compound assignment overloading.
9186 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9187 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9188 // _Atomic
9189 if (Available.hasAtomic()) {
9190 Available.removeAtomic();
9191 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9192 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9193 return;
9194 }
9195
9196 // volatile
9197 if (Available.hasVolatile()) {
9198 Available.removeVolatile();
9199 assert(!Applied.hasVolatile());
9200 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9201 Callback);
9202 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9203 return;
9204 }
9205
9206 Callback(Applied);
9207}
9208
9210 QualifiersAndAtomic Quals,
9211 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9213 Callback);
9214}
9215
9217 QualifiersAndAtomic Quals,
9218 Sema &S) {
9219 if (Quals.hasAtomic())
9221 if (Quals.hasVolatile())
9224}
9225
9226namespace {
9227
9228/// Helper class to manage the addition of builtin operator overload
9229/// candidates. It provides shared state and utility methods used throughout
9230/// the process, as well as a helper method to add each group of builtin
9231/// operator overloads from the standard to a candidate set.
9232class BuiltinOperatorOverloadBuilder {
9233 // Common instance state available to all overload candidate addition methods.
9234 Sema &S;
9235 ArrayRef<Expr *> Args;
9236 QualifiersAndAtomic VisibleTypeConversionsQuals;
9237 bool HasArithmeticOrEnumeralCandidateType;
9238 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9239 OverloadCandidateSet &CandidateSet;
9240
9241 static constexpr int ArithmeticTypesCap = 26;
9242 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9243
9244 // Define some indices used to iterate over the arithmetic types in
9245 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9246 // types are that preserved by promotion (C++ [over.built]p2).
9247 unsigned FirstIntegralType,
9248 LastIntegralType;
9249 unsigned FirstPromotedIntegralType,
9250 LastPromotedIntegralType;
9251 unsigned FirstPromotedArithmeticType,
9252 LastPromotedArithmeticType;
9253 unsigned NumArithmeticTypes;
9254
9255 void InitArithmeticTypes() {
9256 // Start of promoted types.
9257 FirstPromotedArithmeticType = 0;
9258 ArithmeticTypes.push_back(S.Context.FloatTy);
9259 ArithmeticTypes.push_back(S.Context.DoubleTy);
9260 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9262 ArithmeticTypes.push_back(S.Context.Float128Ty);
9264 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9265
9266 // Start of integral types.
9267 FirstIntegralType = ArithmeticTypes.size();
9268 FirstPromotedIntegralType = ArithmeticTypes.size();
9269 ArithmeticTypes.push_back(S.Context.IntTy);
9270 ArithmeticTypes.push_back(S.Context.LongTy);
9271 ArithmeticTypes.push_back(S.Context.LongLongTy);
9275 ArithmeticTypes.push_back(S.Context.Int128Ty);
9276 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9277 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9278 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9282 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9283
9284 /// We add candidates for the unique, unqualified _BitInt types present in
9285 /// the candidate type set. The candidate set already handled ensuring the
9286 /// type is unqualified and canonical, but because we're adding from N
9287 /// different sets, we need to do some extra work to unique things. Insert
9288 /// the candidates into a unique set, then move from that set into the list
9289 /// of arithmetic types.
9290 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9291 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9292 for (QualType BitTy : Candidate.bitint_types())
9293 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9294 }
9295 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9296 LastPromotedIntegralType = ArithmeticTypes.size();
9297 LastPromotedArithmeticType = ArithmeticTypes.size();
9298 // End of promoted types.
9299
9300 ArithmeticTypes.push_back(S.Context.BoolTy);
9301 ArithmeticTypes.push_back(S.Context.CharTy);
9302 ArithmeticTypes.push_back(S.Context.WCharTy);
9303 if (S.Context.getLangOpts().Char8)
9304 ArithmeticTypes.push_back(S.Context.Char8Ty);
9305 ArithmeticTypes.push_back(S.Context.Char16Ty);
9306 ArithmeticTypes.push_back(S.Context.Char32Ty);
9307 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9308 ArithmeticTypes.push_back(S.Context.ShortTy);
9309 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9310 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9311 LastIntegralType = ArithmeticTypes.size();
9312 NumArithmeticTypes = ArithmeticTypes.size();
9313 // End of integral types.
9314 // FIXME: What about complex? What about half?
9315
9316 // We don't know for sure how many bit-precise candidates were involved, so
9317 // we subtract those from the total when testing whether we're under the
9318 // cap or not.
9319 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9320 ArithmeticTypesCap &&
9321 "Enough inline storage for all arithmetic types.");
9322 }
9323
9324 /// Helper method to factor out the common pattern of adding overloads
9325 /// for '++' and '--' builtin operators.
9326 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9327 bool HasVolatile,
9328 bool HasRestrict) {
9329 QualType ParamTypes[2] = {
9330 S.Context.getLValueReferenceType(CandidateTy),
9331 S.Context.IntTy
9332 };
9333
9334 // Non-volatile version.
9335 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9336
9337 // Use a heuristic to reduce number of builtin candidates in the set:
9338 // add volatile version only if there are conversions to a volatile type.
9339 if (HasVolatile) {
9340 ParamTypes[0] =
9342 S.Context.getVolatileType(CandidateTy));
9343 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9344 }
9345
9346 // Add restrict version only if there are conversions to a restrict type
9347 // and our candidate type is a non-restrict-qualified pointer.
9348 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9349 !CandidateTy.isRestrictQualified()) {
9350 ParamTypes[0]
9353 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9354
9355 if (HasVolatile) {
9356 ParamTypes[0]
9358 S.Context.getCVRQualifiedType(CandidateTy,
9361 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9362 }
9363 }
9364
9365 }
9366
9367 /// Helper to add an overload candidate for a binary builtin with types \p L
9368 /// and \p R.
9369 void AddCandidate(QualType L, QualType R) {
9370 QualType LandR[2] = {L, R};
9371 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9372 }
9373
9374public:
9375 BuiltinOperatorOverloadBuilder(
9376 Sema &S, ArrayRef<Expr *> Args,
9377 QualifiersAndAtomic VisibleTypeConversionsQuals,
9378 bool HasArithmeticOrEnumeralCandidateType,
9379 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9380 OverloadCandidateSet &CandidateSet)
9381 : S(S), Args(Args),
9382 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9383 HasArithmeticOrEnumeralCandidateType(
9384 HasArithmeticOrEnumeralCandidateType),
9385 CandidateTypes(CandidateTypes),
9386 CandidateSet(CandidateSet) {
9387
9388 InitArithmeticTypes();
9389 }
9390
9391 // Increment is deprecated for bool since C++17.
9392 //
9393 // C++ [over.built]p3:
9394 //
9395 // For every pair (T, VQ), where T is an arithmetic type other
9396 // than bool, and VQ is either volatile or empty, there exist
9397 // candidate operator functions of the form
9398 //
9399 // VQ T& operator++(VQ T&);
9400 // T operator++(VQ T&, int);
9401 //
9402 // C++ [over.built]p4:
9403 //
9404 // For every pair (T, VQ), where T is an arithmetic type other
9405 // than bool, and VQ is either volatile or empty, there exist
9406 // candidate operator functions of the form
9407 //
9408 // VQ T& operator--(VQ T&);
9409 // T operator--(VQ T&, int);
9410 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9411 if (!HasArithmeticOrEnumeralCandidateType)
9412 return;
9413
9414 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9415 const auto TypeOfT = ArithmeticTypes[Arith];
9416 if (TypeOfT == S.Context.BoolTy) {
9417 if (Op == OO_MinusMinus)
9418 continue;
9419 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9420 continue;
9421 }
9422 addPlusPlusMinusMinusStyleOverloads(
9423 TypeOfT,
9424 VisibleTypeConversionsQuals.hasVolatile(),
9425 VisibleTypeConversionsQuals.hasRestrict());
9426 }
9427 }
9428
9429 // C++ [over.built]p5:
9430 //
9431 // For every pair (T, VQ), where T is a cv-qualified or
9432 // cv-unqualified object type, and VQ is either volatile or
9433 // empty, there exist candidate operator functions of the form
9434 //
9435 // T*VQ& operator++(T*VQ&);
9436 // T*VQ& operator--(T*VQ&);
9437 // T* operator++(T*VQ&, int);
9438 // T* operator--(T*VQ&, int);
9439 void addPlusPlusMinusMinusPointerOverloads() {
9440 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9441 // Skip pointer types that aren't pointers to object types.
9442 if (!PtrTy->getPointeeType()->isObjectType())
9443 continue;
9444
9445 addPlusPlusMinusMinusStyleOverloads(
9446 PtrTy,
9447 (!PtrTy.isVolatileQualified() &&
9448 VisibleTypeConversionsQuals.hasVolatile()),
9449 (!PtrTy.isRestrictQualified() &&
9450 VisibleTypeConversionsQuals.hasRestrict()));
9451 }
9452 }
9453
9454 // C++ [over.built]p6:
9455 // For every cv-qualified or cv-unqualified object type T, there
9456 // exist candidate operator functions of the form
9457 //
9458 // T& operator*(T*);
9459 //
9460 // C++ [over.built]p7:
9461 // For every function type T that does not have cv-qualifiers or a
9462 // ref-qualifier, there exist candidate operator functions of the form
9463 // T& operator*(T*);
9464 void addUnaryStarPointerOverloads() {
9465 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9466 QualType PointeeTy = ParamTy->getPointeeType();
9467 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9468 continue;
9469
9470 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9471 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9472 continue;
9473
9474 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9475 }
9476 }
9477
9478 // C++ [over.built]p9:
9479 // For every promoted arithmetic type T, there exist candidate
9480 // operator functions of the form
9481 //
9482 // T operator+(T);
9483 // T operator-(T);
9484 void addUnaryPlusOrMinusArithmeticOverloads() {
9485 if (!HasArithmeticOrEnumeralCandidateType)
9486 return;
9487
9488 for (unsigned Arith = FirstPromotedArithmeticType;
9489 Arith < LastPromotedArithmeticType; ++Arith) {
9490 QualType ArithTy = ArithmeticTypes[Arith];
9491 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9492 }
9493
9494 // Extension: We also add these operators for vector types.
9495 for (QualType VecTy : CandidateTypes[0].vector_types())
9496 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9497 }
9498
9499 // C++ [over.built]p8:
9500 // For every type T, there exist candidate operator functions of
9501 // the form
9502 //
9503 // T* operator+(T*);
9504 void addUnaryPlusPointerOverloads() {
9505 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9506 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9507 }
9508
9509 // C++ [over.built]p10:
9510 // For every promoted integral type T, there exist candidate
9511 // operator functions of the form
9512 //
9513 // T operator~(T);
9514 void addUnaryTildePromotedIntegralOverloads() {
9515 if (!HasArithmeticOrEnumeralCandidateType)
9516 return;
9517
9518 for (unsigned Int = FirstPromotedIntegralType;
9519 Int < LastPromotedIntegralType; ++Int) {
9520 QualType IntTy = ArithmeticTypes[Int];
9521 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9522 }
9523
9524 // Extension: We also add this operator for vector types.
9525 for (QualType VecTy : CandidateTypes[0].vector_types())
9526 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9527 }
9528
9529 // C++ [over.match.oper]p16:
9530 // For every pointer to member type T or type std::nullptr_t, there
9531 // exist candidate operator functions of the form
9532 //
9533 // bool operator==(T,T);
9534 // bool operator!=(T,T);
9535 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9536 /// Set of (canonical) types that we've already handled.
9537 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9538
9539 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9540 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9541 // Don't add the same builtin candidate twice.
9542 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9543 continue;
9544
9545 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9546 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9547 }
9548
9549 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9551 if (AddedTypes.insert(NullPtrTy).second) {
9552 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9553 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9554 }
9555 }
9556 }
9557 }
9558
9559 // C++ [over.built]p15:
9560 //
9561 // For every T, where T is an enumeration type or a pointer type,
9562 // there exist candidate operator functions of the form
9563 //
9564 // bool operator<(T, T);
9565 // bool operator>(T, T);
9566 // bool operator<=(T, T);
9567 // bool operator>=(T, T);
9568 // bool operator==(T, T);
9569 // bool operator!=(T, T);
9570 // R operator<=>(T, T)
9571 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9572 // C++ [over.match.oper]p3:
9573 // [...]the built-in candidates include all of the candidate operator
9574 // functions defined in 13.6 that, compared to the given operator, [...]
9575 // do not have the same parameter-type-list as any non-template non-member
9576 // candidate.
9577 //
9578 // Note that in practice, this only affects enumeration types because there
9579 // aren't any built-in candidates of record type, and a user-defined operator
9580 // must have an operand of record or enumeration type. Also, the only other
9581 // overloaded operator with enumeration arguments, operator=,
9582 // cannot be overloaded for enumeration types, so this is the only place
9583 // where we must suppress candidates like this.
9584 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9585 UserDefinedBinaryOperators;
9586
9587 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9588 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9589 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9590 CEnd = CandidateSet.end();
9591 C != CEnd; ++C) {
9592 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9593 continue;
9594
9595 if (C->Function->isFunctionTemplateSpecialization())
9596 continue;
9597
9598 // We interpret "same parameter-type-list" as applying to the
9599 // "synthesized candidate, with the order of the two parameters
9600 // reversed", not to the original function.
9601 bool Reversed = C->isReversed();
9602 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9603 ->getType()
9604 .getUnqualifiedType();
9605 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9606 ->getType()
9607 .getUnqualifiedType();
9608
9609 // Skip if either parameter isn't of enumeral type.
9610 if (!FirstParamType->isEnumeralType() ||
9611 !SecondParamType->isEnumeralType())
9612 continue;
9613
9614 // Add this operator to the set of known user-defined operators.
9615 UserDefinedBinaryOperators.insert(
9616 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9617 S.Context.getCanonicalType(SecondParamType)));
9618 }
9619 }
9620 }
9621
9622 /// Set of (canonical) types that we've already handled.
9623 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9624
9625 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9626 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9627 // Don't add the same builtin candidate twice.
9628 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9629 continue;
9630 if (IsSpaceship && PtrTy->isFunctionPointerType())
9631 continue;
9632
9633 QualType ParamTypes[2] = {PtrTy, PtrTy};
9634 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9635 }
9636 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9637 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9638
9639 // Don't add the same builtin candidate twice, or if a user defined
9640 // candidate exists.
9641 if (!AddedTypes.insert(CanonType).second ||
9642 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9643 CanonType)))
9644 continue;
9645 QualType ParamTypes[2] = {EnumTy, EnumTy};
9646 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9647 }
9648 }
9649 }
9650
9651 // C++ [over.built]p13:
9652 //
9653 // For every cv-qualified or cv-unqualified object type T
9654 // there exist candidate operator functions of the form
9655 //
9656 // T* operator+(T*, ptrdiff_t);
9657 // T& operator[](T*, ptrdiff_t); [BELOW]
9658 // T* operator-(T*, ptrdiff_t);
9659 // T* operator+(ptrdiff_t, T*);
9660 // T& operator[](ptrdiff_t, T*); [BELOW]
9661 //
9662 // C++ [over.built]p14:
9663 //
9664 // For every T, where T is a pointer to object type, there
9665 // exist candidate operator functions of the form
9666 //
9667 // ptrdiff_t operator-(T, T);
9668 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9669 /// Set of (canonical) types that we've already handled.
9670 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9671
9672 for (int Arg = 0; Arg < 2; ++Arg) {
9673 QualType AsymmetricParamTypes[2] = {
9676 };
9677 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9678 QualType PointeeTy = PtrTy->getPointeeType();
9679 if (!PointeeTy->isObjectType())
9680 continue;
9681
9682 AsymmetricParamTypes[Arg] = PtrTy;
9683 if (Arg == 0 || Op == OO_Plus) {
9684 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9685 // T* operator+(ptrdiff_t, T*);
9686 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9687 }
9688 if (Op == OO_Minus) {
9689 // ptrdiff_t operator-(T, T);
9690 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9691 continue;
9692
9693 QualType ParamTypes[2] = {PtrTy, PtrTy};
9694 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9695 }
9696 }
9697 }
9698 }
9699
9700 // C++ [over.built]p12:
9701 //
9702 // For every pair of promoted arithmetic types L and R, there
9703 // exist candidate operator functions of the form
9704 //
9705 // LR operator*(L, R);
9706 // LR operator/(L, R);
9707 // LR operator+(L, R);
9708 // LR operator-(L, R);
9709 // bool operator<(L, R);
9710 // bool operator>(L, R);
9711 // bool operator<=(L, R);
9712 // bool operator>=(L, R);
9713 // bool operator==(L, R);
9714 // bool operator!=(L, R);
9715 //
9716 // where LR is the result of the usual arithmetic conversions
9717 // between types L and R.
9718 //
9719 // C++ [over.built]p24:
9720 //
9721 // For every pair of promoted arithmetic types L and R, there exist
9722 // candidate operator functions of the form
9723 //
9724 // LR operator?(bool, L, R);
9725 //
9726 // where LR is the result of the usual arithmetic conversions
9727 // between types L and R.
9728 // Our candidates ignore the first parameter.
9729 void addGenericBinaryArithmeticOverloads() {
9730 if (!HasArithmeticOrEnumeralCandidateType)
9731 return;
9732
9733 for (unsigned Left = FirstPromotedArithmeticType;
9734 Left < LastPromotedArithmeticType; ++Left) {
9735 for (unsigned Right = FirstPromotedArithmeticType;
9736 Right < LastPromotedArithmeticType; ++Right) {
9737 QualType LandR[2] = { ArithmeticTypes[Left],
9738 ArithmeticTypes[Right] };
9739 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9740 }
9741 }
9742
9743 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9744 // conditional operator for vector types.
9745 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9746 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9747 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9748 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9749 }
9750 }
9751
9752 /// Add binary operator overloads for each candidate matrix type M1, M2:
9753 /// * (M1, M1) -> M1
9754 /// * (M1, M1.getElementType()) -> M1
9755 /// * (M2.getElementType(), M2) -> M2
9756 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9757 void addMatrixBinaryArithmeticOverloads() {
9758 if (!HasArithmeticOrEnumeralCandidateType)
9759 return;
9760
9761 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9762 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9763 AddCandidate(M1, M1);
9764 }
9765
9766 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9767 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9768 if (!CandidateTypes[0].containsMatrixType(M2))
9769 AddCandidate(M2, M2);
9770 }
9771 }
9772
9773 // C++2a [over.built]p14:
9774 //
9775 // For every integral type T there exists a candidate operator function
9776 // of the form
9777 //
9778 // std::strong_ordering operator<=>(T, T)
9779 //
9780 // C++2a [over.built]p15:
9781 //
9782 // For every pair of floating-point types L and R, there exists a candidate
9783 // operator function of the form
9784 //
9785 // std::partial_ordering operator<=>(L, R);
9786 //
9787 // FIXME: The current specification for integral types doesn't play nice with
9788 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9789 // comparisons. Under the current spec this can lead to ambiguity during
9790 // overload resolution. For example:
9791 //
9792 // enum A : int {a};
9793 // auto x = (a <=> (long)42);
9794 //
9795 // error: call is ambiguous for arguments 'A' and 'long'.
9796 // note: candidate operator<=>(int, int)
9797 // note: candidate operator<=>(long, long)
9798 //
9799 // To avoid this error, this function deviates from the specification and adds
9800 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9801 // arithmetic types (the same as the generic relational overloads).
9802 //
9803 // For now this function acts as a placeholder.
9804 void addThreeWayArithmeticOverloads() {
9805 addGenericBinaryArithmeticOverloads();
9806 }
9807
9808 // C++ [over.built]p17:
9809 //
9810 // For every pair of promoted integral types L and R, there
9811 // exist candidate operator functions of the form
9812 //
9813 // LR operator%(L, R);
9814 // LR operator&(L, R);
9815 // LR operator^(L, R);
9816 // LR operator|(L, R);
9817 // L operator<<(L, R);
9818 // L operator>>(L, R);
9819 //
9820 // where LR is the result of the usual arithmetic conversions
9821 // between types L and R.
9822 void addBinaryBitwiseArithmeticOverloads() {
9823 if (!HasArithmeticOrEnumeralCandidateType)
9824 return;
9825
9826 for (unsigned Left = FirstPromotedIntegralType;
9827 Left < LastPromotedIntegralType; ++Left) {
9828 for (unsigned Right = FirstPromotedIntegralType;
9829 Right < LastPromotedIntegralType; ++Right) {
9830 QualType LandR[2] = { ArithmeticTypes[Left],
9831 ArithmeticTypes[Right] };
9832 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9833 }
9834 }
9835 }
9836
9837 // C++ [over.built]p20:
9838 //
9839 // For every pair (T, VQ), where T is an enumeration or
9840 // pointer to member type and VQ is either volatile or
9841 // empty, there exist candidate operator functions of the form
9842 //
9843 // VQ T& operator=(VQ T&, T);
9844 void addAssignmentMemberPointerOrEnumeralOverloads() {
9845 /// Set of (canonical) types that we've already handled.
9846 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9847
9848 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9849 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9850 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9851 continue;
9852
9853 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9854 }
9855
9856 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9857 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9858 continue;
9859
9860 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9861 }
9862 }
9863 }
9864
9865 // C++ [over.built]p19:
9866 //
9867 // For every pair (T, VQ), where T is any type and VQ is either
9868 // volatile or empty, there exist candidate operator functions
9869 // of the form
9870 //
9871 // T*VQ& operator=(T*VQ&, T*);
9872 //
9873 // C++ [over.built]p21:
9874 //
9875 // For every pair (T, VQ), where T is a cv-qualified or
9876 // cv-unqualified object type and VQ is either volatile or
9877 // empty, there exist candidate operator functions of the form
9878 //
9879 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9880 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9881 void addAssignmentPointerOverloads(bool isEqualOp) {
9882 /// Set of (canonical) types that we've already handled.
9883 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9884
9885 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9886 // If this is operator=, keep track of the builtin candidates we added.
9887 if (isEqualOp)
9888 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9889 else if (!PtrTy->getPointeeType()->isObjectType())
9890 continue;
9891
9892 // non-volatile version
9893 QualType ParamTypes[2] = {
9895 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9896 };
9897 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9898 /*IsAssignmentOperator=*/ isEqualOp);
9899
9900 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9901 VisibleTypeConversionsQuals.hasVolatile();
9902 if (NeedVolatile) {
9903 // volatile version
9904 ParamTypes[0] =
9906 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9907 /*IsAssignmentOperator=*/isEqualOp);
9908 }
9909
9910 if (!PtrTy.isRestrictQualified() &&
9911 VisibleTypeConversionsQuals.hasRestrict()) {
9912 // restrict version
9913 ParamTypes[0] =
9915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9916 /*IsAssignmentOperator=*/isEqualOp);
9917
9918 if (NeedVolatile) {
9919 // volatile restrict version
9920 ParamTypes[0] =
9923 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9924 /*IsAssignmentOperator=*/isEqualOp);
9925 }
9926 }
9927 }
9928
9929 if (isEqualOp) {
9930 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9931 // Make sure we don't add the same candidate twice.
9932 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9933 continue;
9934
9935 QualType ParamTypes[2] = {
9937 PtrTy,
9938 };
9939
9940 // non-volatile version
9941 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9942 /*IsAssignmentOperator=*/true);
9943
9944 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9945 VisibleTypeConversionsQuals.hasVolatile();
9946 if (NeedVolatile) {
9947 // volatile version
9948 ParamTypes[0] = S.Context.getLValueReferenceType(
9949 S.Context.getVolatileType(PtrTy));
9950 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9951 /*IsAssignmentOperator=*/true);
9952 }
9953
9954 if (!PtrTy.isRestrictQualified() &&
9955 VisibleTypeConversionsQuals.hasRestrict()) {
9956 // restrict version
9957 ParamTypes[0] = S.Context.getLValueReferenceType(
9958 S.Context.getRestrictType(PtrTy));
9959 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9960 /*IsAssignmentOperator=*/true);
9961
9962 if (NeedVolatile) {
9963 // volatile restrict version
9964 ParamTypes[0] =
9967 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9968 /*IsAssignmentOperator=*/true);
9969 }
9970 }
9971 }
9972 }
9973 }
9974
9975 // C++ [over.built]p18:
9976 //
9977 // For every triple (L, VQ, R), where L is an arithmetic type,
9978 // VQ is either volatile or empty, and R is a promoted
9979 // arithmetic type, there exist candidate operator functions of
9980 // the form
9981 //
9982 // VQ L& operator=(VQ L&, R);
9983 // VQ L& operator*=(VQ L&, R);
9984 // VQ L& operator/=(VQ L&, R);
9985 // VQ L& operator+=(VQ L&, R);
9986 // VQ L& operator-=(VQ L&, R);
9987 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9988 if (!HasArithmeticOrEnumeralCandidateType)
9989 return;
9990
9991 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9992 for (unsigned Right = FirstPromotedArithmeticType;
9993 Right < LastPromotedArithmeticType; ++Right) {
9994 QualType ParamTypes[2];
9995 ParamTypes[1] = ArithmeticTypes[Right];
9997 S, ArithmeticTypes[Left], Args[0]);
9998
10000 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10001 ParamTypes[0] =
10002 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10003 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10004 /*IsAssignmentOperator=*/isEqualOp);
10005 });
10006 }
10007 }
10008
10009 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10010 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10011 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10012 QualType ParamTypes[2];
10013 ParamTypes[1] = Vec2Ty;
10014 // Add this built-in operator as a candidate (VQ is empty).
10015 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10016 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10017 /*IsAssignmentOperator=*/isEqualOp);
10018
10019 // Add this built-in operator as a candidate (VQ is 'volatile').
10020 if (VisibleTypeConversionsQuals.hasVolatile()) {
10021 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10022 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10023 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10024 /*IsAssignmentOperator=*/isEqualOp);
10025 }
10026 }
10027 }
10028
10029 // C++ [over.built]p22:
10030 //
10031 // For every triple (L, VQ, R), where L is an integral type, VQ
10032 // is either volatile or empty, and R is a promoted integral
10033 // type, there exist candidate operator functions of the form
10034 //
10035 // VQ L& operator%=(VQ L&, R);
10036 // VQ L& operator<<=(VQ L&, R);
10037 // VQ L& operator>>=(VQ L&, R);
10038 // VQ L& operator&=(VQ L&, R);
10039 // VQ L& operator^=(VQ L&, R);
10040 // VQ L& operator|=(VQ L&, R);
10041 void addAssignmentIntegralOverloads() {
10042 if (!HasArithmeticOrEnumeralCandidateType)
10043 return;
10044
10045 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10046 for (unsigned Right = FirstPromotedIntegralType;
10047 Right < LastPromotedIntegralType; ++Right) {
10048 QualType ParamTypes[2];
10049 ParamTypes[1] = ArithmeticTypes[Right];
10051 S, ArithmeticTypes[Left], Args[0]);
10052
10054 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10055 ParamTypes[0] =
10056 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10057 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10058 });
10059 }
10060 }
10061 }
10062
10063 // C++ [over.operator]p23:
10064 //
10065 // There also exist candidate operator functions of the form
10066 //
10067 // bool operator!(bool);
10068 // bool operator&&(bool, bool);
10069 // bool operator||(bool, bool);
10070 void addExclaimOverload() {
10071 QualType ParamTy = S.Context.BoolTy;
10072 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10073 /*IsAssignmentOperator=*/false,
10074 /*NumContextualBoolArguments=*/1);
10075 }
10076 void addAmpAmpOrPipePipeOverload() {
10077 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10078 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10079 /*IsAssignmentOperator=*/false,
10080 /*NumContextualBoolArguments=*/2);
10081 }
10082
10083 // C++ [over.built]p13:
10084 //
10085 // For every cv-qualified or cv-unqualified object type T there
10086 // exist candidate operator functions of the form
10087 //
10088 // T* operator+(T*, ptrdiff_t); [ABOVE]
10089 // T& operator[](T*, ptrdiff_t);
10090 // T* operator-(T*, ptrdiff_t); [ABOVE]
10091 // T* operator+(ptrdiff_t, T*); [ABOVE]
10092 // T& operator[](ptrdiff_t, T*);
10093 void addSubscriptOverloads() {
10094 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10095 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10096 QualType PointeeType = PtrTy->getPointeeType();
10097 if (!PointeeType->isObjectType())
10098 continue;
10099
10100 // T& operator[](T*, ptrdiff_t)
10101 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10102 }
10103
10104 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10105 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10106 QualType PointeeType = PtrTy->getPointeeType();
10107 if (!PointeeType->isObjectType())
10108 continue;
10109
10110 // T& operator[](ptrdiff_t, T*)
10111 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10112 }
10113 }
10114
10115 // C++ [over.built]p11:
10116 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10117 // C1 is the same type as C2 or is a derived class of C2, T is an object
10118 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10119 // there exist candidate operator functions of the form
10120 //
10121 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10122 //
10123 // where CV12 is the union of CV1 and CV2.
10124 void addArrowStarOverloads() {
10125 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10126 QualType C1Ty = PtrTy;
10127 QualType C1;
10128 QualifierCollector Q1;
10129 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10130 if (!isa<RecordType>(C1))
10131 continue;
10132 // heuristic to reduce number of builtin candidates in the set.
10133 // Add volatile/restrict version only if there are conversions to a
10134 // volatile/restrict type.
10135 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10136 continue;
10137 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10138 continue;
10139 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10140 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10141 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10142 *D2 = mptr->getMostRecentCXXRecordDecl();
10143 if (!declaresSameEntity(D1, D2) &&
10144 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10145 break;
10146 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10147 // build CV12 T&
10148 QualType T = mptr->getPointeeType();
10149 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10150 T.isVolatileQualified())
10151 continue;
10152 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10153 T.isRestrictQualified())
10154 continue;
10155 T = Q1.apply(S.Context, T);
10156 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10157 }
10158 }
10159 }
10160
10161 // Note that we don't consider the first argument, since it has been
10162 // contextually converted to bool long ago. The candidates below are
10163 // therefore added as binary.
10164 //
10165 // C++ [over.built]p25:
10166 // For every type T, where T is a pointer, pointer-to-member, or scoped
10167 // enumeration type, there exist candidate operator functions of the form
10168 //
10169 // T operator?(bool, T, T);
10170 //
10171 void addConditionalOperatorOverloads() {
10172 /// Set of (canonical) types that we've already handled.
10173 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10174
10175 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10176 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10177 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10178 continue;
10179
10180 QualType ParamTypes[2] = {PtrTy, PtrTy};
10181 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10182 }
10183
10184 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10185 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10186 continue;
10187
10188 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10189 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10190 }
10191
10192 if (S.getLangOpts().CPlusPlus11) {
10193 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10194 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10195 continue;
10196
10197 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10198 continue;
10199
10200 QualType ParamTypes[2] = {EnumTy, EnumTy};
10201 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10202 }
10203 }
10204 }
10205 }
10206};
10207
10208} // end anonymous namespace
10209
10211 SourceLocation OpLoc,
10212 ArrayRef<Expr *> Args,
10213 OverloadCandidateSet &CandidateSet) {
10214 // Find all of the types that the arguments can convert to, but only
10215 // if the operator we're looking at has built-in operator candidates
10216 // that make use of these types. Also record whether we encounter non-record
10217 // candidate types or either arithmetic or enumeral candidate types.
10218 QualifiersAndAtomic VisibleTypeConversionsQuals;
10219 VisibleTypeConversionsQuals.addConst();
10220 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10221 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10222 if (Args[ArgIdx]->getType()->isAtomicType())
10223 VisibleTypeConversionsQuals.addAtomic();
10224 }
10225
10226 bool HasNonRecordCandidateType = false;
10227 bool HasArithmeticOrEnumeralCandidateType = false;
10229 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10230 CandidateTypes.emplace_back(*this);
10231 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10232 OpLoc,
10233 true,
10234 (Op == OO_Exclaim ||
10235 Op == OO_AmpAmp ||
10236 Op == OO_PipePipe),
10237 VisibleTypeConversionsQuals);
10238 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10239 CandidateTypes[ArgIdx].hasNonRecordTypes();
10240 HasArithmeticOrEnumeralCandidateType =
10241 HasArithmeticOrEnumeralCandidateType ||
10242 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10243 }
10244
10245 // Exit early when no non-record types have been added to the candidate set
10246 // for any of the arguments to the operator.
10247 //
10248 // We can't exit early for !, ||, or &&, since there we have always have
10249 // 'bool' overloads.
10250 if (!HasNonRecordCandidateType &&
10251 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10252 return;
10253
10254 // Setup an object to manage the common state for building overloads.
10255 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10256 VisibleTypeConversionsQuals,
10257 HasArithmeticOrEnumeralCandidateType,
10258 CandidateTypes, CandidateSet);
10259
10260 // Dispatch over the operation to add in only those overloads which apply.
10261 switch (Op) {
10262 case OO_None:
10264 llvm_unreachable("Expected an overloaded operator");
10265
10266 case OO_New:
10267 case OO_Delete:
10268 case OO_Array_New:
10269 case OO_Array_Delete:
10270 case OO_Call:
10271 llvm_unreachable(
10272 "Special operators don't use AddBuiltinOperatorCandidates");
10273
10274 case OO_Comma:
10275 case OO_Arrow:
10276 case OO_Coawait:
10277 // C++ [over.match.oper]p3:
10278 // -- For the operator ',', the unary operator '&', the
10279 // operator '->', or the operator 'co_await', the
10280 // built-in candidates set is empty.
10281 break;
10282
10283 case OO_Plus: // '+' is either unary or binary
10284 if (Args.size() == 1)
10285 OpBuilder.addUnaryPlusPointerOverloads();
10286 [[fallthrough]];
10287
10288 case OO_Minus: // '-' is either unary or binary
10289 if (Args.size() == 1) {
10290 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10291 } else {
10292 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10293 OpBuilder.addGenericBinaryArithmeticOverloads();
10294 OpBuilder.addMatrixBinaryArithmeticOverloads();
10295 }
10296 break;
10297
10298 case OO_Star: // '*' is either unary or binary
10299 if (Args.size() == 1)
10300 OpBuilder.addUnaryStarPointerOverloads();
10301 else {
10302 OpBuilder.addGenericBinaryArithmeticOverloads();
10303 OpBuilder.addMatrixBinaryArithmeticOverloads();
10304 }
10305 break;
10306
10307 case OO_Slash:
10308 OpBuilder.addGenericBinaryArithmeticOverloads();
10309 break;
10310
10311 case OO_PlusPlus:
10312 case OO_MinusMinus:
10313 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10314 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10315 break;
10316
10317 case OO_EqualEqual:
10318 case OO_ExclaimEqual:
10319 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10320 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10321 OpBuilder.addGenericBinaryArithmeticOverloads();
10322 break;
10323
10324 case OO_Less:
10325 case OO_Greater:
10326 case OO_LessEqual:
10327 case OO_GreaterEqual:
10328 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10329 OpBuilder.addGenericBinaryArithmeticOverloads();
10330 break;
10331
10332 case OO_Spaceship:
10333 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10334 OpBuilder.addThreeWayArithmeticOverloads();
10335 break;
10336
10337 case OO_Percent:
10338 case OO_Caret:
10339 case OO_Pipe:
10340 case OO_LessLess:
10341 case OO_GreaterGreater:
10342 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10343 break;
10344
10345 case OO_Amp: // '&' is either unary or binary
10346 if (Args.size() == 1)
10347 // C++ [over.match.oper]p3:
10348 // -- For the operator ',', the unary operator '&', or the
10349 // operator '->', the built-in candidates set is empty.
10350 break;
10351
10352 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10353 break;
10354
10355 case OO_Tilde:
10356 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10357 break;
10358
10359 case OO_Equal:
10360 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10361 [[fallthrough]];
10362
10363 case OO_PlusEqual:
10364 case OO_MinusEqual:
10365 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10366 [[fallthrough]];
10367
10368 case OO_StarEqual:
10369 case OO_SlashEqual:
10370 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10371 break;
10372
10373 case OO_PercentEqual:
10374 case OO_LessLessEqual:
10375 case OO_GreaterGreaterEqual:
10376 case OO_AmpEqual:
10377 case OO_CaretEqual:
10378 case OO_PipeEqual:
10379 OpBuilder.addAssignmentIntegralOverloads();
10380 break;
10381
10382 case OO_Exclaim:
10383 OpBuilder.addExclaimOverload();
10384 break;
10385
10386 case OO_AmpAmp:
10387 case OO_PipePipe:
10388 OpBuilder.addAmpAmpOrPipePipeOverload();
10389 break;
10390
10391 case OO_Subscript:
10392 if (Args.size() == 2)
10393 OpBuilder.addSubscriptOverloads();
10394 break;
10395
10396 case OO_ArrowStar:
10397 OpBuilder.addArrowStarOverloads();
10398 break;
10399
10400 case OO_Conditional:
10401 OpBuilder.addConditionalOperatorOverloads();
10402 OpBuilder.addGenericBinaryArithmeticOverloads();
10403 break;
10404 }
10405}
10406
10407void
10409 SourceLocation Loc,
10410 ArrayRef<Expr *> Args,
10411 TemplateArgumentListInfo *ExplicitTemplateArgs,
10412 OverloadCandidateSet& CandidateSet,
10413 bool PartialOverloading) {
10414 ADLResult Fns;
10415
10416 // FIXME: This approach for uniquing ADL results (and removing
10417 // redundant candidates from the set) relies on pointer-equality,
10418 // which means we need to key off the canonical decl. However,
10419 // always going back to the canonical decl might not get us the
10420 // right set of default arguments. What default arguments are
10421 // we supposed to consider on ADL candidates, anyway?
10422
10423 // FIXME: Pass in the explicit template arguments?
10424 ArgumentDependentLookup(Name, Loc, Args, Fns);
10425
10426 ArrayRef<Expr *> ReversedArgs;
10427
10428 // Erase all of the candidates we already knew about.
10429 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10430 CandEnd = CandidateSet.end();
10431 Cand != CandEnd; ++Cand)
10432 if (Cand->Function) {
10433 FunctionDecl *Fn = Cand->Function;
10434 Fns.erase(Fn);
10435 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10436 Fns.erase(FunTmpl);
10437 }
10438
10439 // For each of the ADL candidates we found, add it to the overload
10440 // set.
10441 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10443
10444 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10445 if (ExplicitTemplateArgs)
10446 continue;
10447
10449 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10450 PartialOverloading, /*AllowExplicit=*/true,
10451 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10452 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10454 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10455 /*SuppressUserConversions=*/false, PartialOverloading,
10456 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10457 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10458 }
10459 } else {
10460 auto *FTD = cast<FunctionTemplateDecl>(*I);
10462 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10463 /*SuppressUserConversions=*/false, PartialOverloading,
10464 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10465 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10466 *this, Args, FTD->getTemplatedDecl())) {
10467
10468 // As template candidates are not deduced immediately,
10469 // persist the array in the overload set.
10470 if (ReversedArgs.empty())
10471 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10472
10474 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10475 /*SuppressUserConversions=*/false, PartialOverloading,
10476 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10478 }
10479 }
10480 }
10481}
10482
10483namespace {
10484enum class Comparison { Equal, Better, Worse };
10485}
10486
10487/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10488/// overload resolution.
10489///
10490/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10491/// Cand1's first N enable_if attributes have precisely the same conditions as
10492/// Cand2's first N enable_if attributes (where N = the number of enable_if
10493/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10494///
10495/// Note that you can have a pair of candidates such that Cand1's enable_if
10496/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10497/// worse than Cand1's.
10498static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10499 const FunctionDecl *Cand2) {
10500 // Common case: One (or both) decls don't have enable_if attrs.
10501 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10502 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10503 if (!Cand1Attr || !Cand2Attr) {
10504 if (Cand1Attr == Cand2Attr)
10505 return Comparison::Equal;
10506 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10507 }
10508
10509 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10510 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10511
10512 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10513 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10514 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10515 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10516
10517 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10518 // has fewer enable_if attributes than Cand2, and vice versa.
10519 if (!Cand1A)
10520 return Comparison::Worse;
10521 if (!Cand2A)
10522 return Comparison::Better;
10523
10524 Cand1ID.clear();
10525 Cand2ID.clear();
10526
10527 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10528 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10529 if (Cand1ID != Cand2ID)
10530 return Comparison::Worse;
10531 }
10532
10533 return Comparison::Equal;
10534}
10535
10536static Comparison
10538 const OverloadCandidate &Cand2) {
10539 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10540 !Cand2.Function->isMultiVersion())
10541 return Comparison::Equal;
10542
10543 // If both are invalid, they are equal. If one of them is invalid, the other
10544 // is better.
10545 if (Cand1.Function->isInvalidDecl()) {
10546 if (Cand2.Function->isInvalidDecl())
10547 return Comparison::Equal;
10548 return Comparison::Worse;
10549 }
10550 if (Cand2.Function->isInvalidDecl())
10551 return Comparison::Better;
10552
10553 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10554 // cpu_dispatch, else arbitrarily based on the identifiers.
10555 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10556 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10557 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10558 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10559
10560 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10561 return Comparison::Equal;
10562
10563 if (Cand1CPUDisp && !Cand2CPUDisp)
10564 return Comparison::Better;
10565 if (Cand2CPUDisp && !Cand1CPUDisp)
10566 return Comparison::Worse;
10567
10568 if (Cand1CPUSpec && Cand2CPUSpec) {
10569 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10570 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10571 ? Comparison::Better
10572 : Comparison::Worse;
10573
10574 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10575 FirstDiff = std::mismatch(
10576 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10577 Cand2CPUSpec->cpus_begin(),
10578 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10579 return LHS->getName() == RHS->getName();
10580 });
10581
10582 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10583 "Two different cpu-specific versions should not have the same "
10584 "identifier list, otherwise they'd be the same decl!");
10585 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10586 ? Comparison::Better
10587 : Comparison::Worse;
10588 }
10589 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10590}
10591
10592/// Compute the type of the implicit object parameter for the given function,
10593/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10594/// null QualType if there is a 'matches anything' implicit object parameter.
10595static std::optional<QualType>
10598 return std::nullopt;
10599
10600 auto *M = cast<CXXMethodDecl>(F);
10601 // Static member functions' object parameters match all types.
10602 if (M->isStatic())
10603 return QualType();
10604 return M->getFunctionObjectParameterReferenceType();
10605}
10606
10607// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10608// represent the same entity.
10609static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10610 const FunctionDecl *F2) {
10611 if (declaresSameEntity(F1, F2))
10612 return true;
10613 auto PT1 = F1->getPrimaryTemplate();
10614 auto PT2 = F2->getPrimaryTemplate();
10615 if (PT1 && PT2) {
10616 if (declaresSameEntity(PT1, PT2) ||
10617 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10618 PT2->getInstantiatedFromMemberTemplate()))
10619 return true;
10620 }
10621 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10622 // different functions with same params). Consider removing this (as no test
10623 // fail w/o it).
10624 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10625 if (First) {
10626 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10627 return *T;
10628 }
10629 assert(I < F->getNumParams());
10630 return F->getParamDecl(I++)->getType();
10631 };
10632
10633 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10634 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10635
10636 if (F1NumParams != F2NumParams)
10637 return false;
10638
10639 unsigned I1 = 0, I2 = 0;
10640 for (unsigned I = 0; I != F1NumParams; ++I) {
10641 QualType T1 = NextParam(F1, I1, I == 0);
10642 QualType T2 = NextParam(F2, I2, I == 0);
10643 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10644 if (!Context.hasSameUnqualifiedType(T1, T2))
10645 return false;
10646 }
10647 return true;
10648}
10649
10650/// We're allowed to use constraints partial ordering only if the candidates
10651/// have the same parameter types:
10652/// [over.match.best.general]p2.6
10653/// F1 and F2 are non-template functions with the same
10654/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10656 FunctionDecl *Fn2,
10657 bool IsFn1Reversed,
10658 bool IsFn2Reversed) {
10659 assert(Fn1 && Fn2);
10660 if (Fn1->isVariadic() != Fn2->isVariadic())
10661 return false;
10662
10663 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10664 IsFn1Reversed ^ IsFn2Reversed))
10665 return false;
10666
10667 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10668 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10669 if (Mem1 && Mem2) {
10670 // if they are member functions, both are direct members of the same class,
10671 // and
10672 if (Mem1->getParent() != Mem2->getParent())
10673 return false;
10674 // if both are non-static member functions, they have the same types for
10675 // their object parameters
10676 if (Mem1->isInstance() && Mem2->isInstance() &&
10678 Mem1->getFunctionObjectParameterReferenceType(),
10679 Mem1->getFunctionObjectParameterReferenceType()))
10680 return false;
10681 }
10682 return true;
10683}
10684
10685static FunctionDecl *
10687 bool IsFn1Reversed, bool IsFn2Reversed) {
10688 if (!Fn1 || !Fn2)
10689 return nullptr;
10690
10691 // C++ [temp.constr.order]:
10692 // A non-template function F1 is more partial-ordering-constrained than a
10693 // non-template function F2 if:
10694 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10695 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10696
10697 if (Cand1IsSpecialization || Cand2IsSpecialization)
10698 return nullptr;
10699
10700 // - they have the same non-object-parameter-type-lists, and [...]
10701 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10702 IsFn2Reversed))
10703 return nullptr;
10704
10705 // - the declaration of F1 is more constrained than the declaration of F2.
10706 return S.getMoreConstrainedFunction(Fn1, Fn2);
10707}
10708
10709/// isBetterOverloadCandidate - Determines whether the first overload
10710/// candidate is a better candidate than the second (C++ 13.3.3p1).
10712 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10714 bool PartialOverloading) {
10715 // Define viable functions to be better candidates than non-viable
10716 // functions.
10717 if (!Cand2.Viable)
10718 return Cand1.Viable;
10719 else if (!Cand1.Viable)
10720 return false;
10721
10722 // [CUDA] A function with 'never' preference is marked not viable, therefore
10723 // is never shown up here. The worst preference shown up here is 'wrong side',
10724 // e.g. an H function called by a HD function in device compilation. This is
10725 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10726 // function which is called only by an H function. A deferred diagnostic will
10727 // be triggered if it is emitted. However a wrong-sided function is still
10728 // a viable candidate here.
10729 //
10730 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10731 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10732 // can be emitted, Cand1 is not better than Cand2. This rule should have
10733 // precedence over other rules.
10734 //
10735 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10736 // other rules should be used to determine which is better. This is because
10737 // host/device based overloading resolution is mostly for determining
10738 // viability of a function. If two functions are both viable, other factors
10739 // should take precedence in preference, e.g. the standard-defined preferences
10740 // like argument conversion ranks or enable_if partial-ordering. The
10741 // preference for pass-object-size parameters is probably most similar to a
10742 // type-based-overloading decision and so should take priority.
10743 //
10744 // If other rules cannot determine which is better, CUDA preference will be
10745 // used again to determine which is better.
10746 //
10747 // TODO: Currently IdentifyPreference does not return correct values
10748 // for functions called in global variable initializers due to missing
10749 // correct context about device/host. Therefore we can only enforce this
10750 // rule when there is a caller. We should enforce this rule for functions
10751 // in global variable initializers once proper context is added.
10752 //
10753 // TODO: We can only enable the hostness based overloading resolution when
10754 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10755 // overloading resolution diagnostics.
10756 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10757 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10758 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10759 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10760 bool IsCand1ImplicitHD =
10762 bool IsCand2ImplicitHD =
10764 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10765 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10766 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10767 // The implicit HD function may be a function in a system header which
10768 // is forced by pragma. In device compilation, if we prefer HD candidates
10769 // over wrong-sided candidates, overloading resolution may change, which
10770 // may result in non-deferrable diagnostics. As a workaround, we let
10771 // implicit HD candidates take equal preference as wrong-sided candidates.
10772 // This will preserve the overloading resolution.
10773 // TODO: We still need special handling of implicit HD functions since
10774 // they may incur other diagnostics to be deferred. We should make all
10775 // host/device related diagnostics deferrable and remove special handling
10776 // of implicit HD functions.
10777 auto EmitThreshold =
10778 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10779 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10782 auto Cand1Emittable = P1 > EmitThreshold;
10783 auto Cand2Emittable = P2 > EmitThreshold;
10784 if (Cand1Emittable && !Cand2Emittable)
10785 return true;
10786 if (!Cand1Emittable && Cand2Emittable)
10787 return false;
10788 }
10789 }
10790
10791 // C++ [over.match.best]p1: (Changed in C++23)
10792 //
10793 // -- if F is a static member function, ICS1(F) is defined such
10794 // that ICS1(F) is neither better nor worse than ICS1(G) for
10795 // any function G, and, symmetrically, ICS1(G) is neither
10796 // better nor worse than ICS1(F).
10797 unsigned StartArg = 0;
10798 if (!Cand1.TookAddressOfOverload &&
10800 StartArg = 1;
10801
10802 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10803 // We don't allow incompatible pointer conversions in C++.
10804 if (!S.getLangOpts().CPlusPlus)
10805 return ICS.isStandard() &&
10806 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10807
10808 // The only ill-formed conversion we allow in C++ is the string literal to
10809 // char* conversion, which is only considered ill-formed after C++11.
10810 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10812 };
10813
10814 // Define functions that don't require ill-formed conversions for a given
10815 // argument to be better candidates than functions that do.
10816 unsigned NumArgs = Cand1.Conversions.size();
10817 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10818 bool HasBetterConversion = false;
10819 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10820 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10821 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10822 if (Cand1Bad != Cand2Bad) {
10823 if (Cand1Bad)
10824 return false;
10825 HasBetterConversion = true;
10826 }
10827 }
10828
10829 if (HasBetterConversion)
10830 return true;
10831
10832 // C++ [over.match.best]p1:
10833 // A viable function F1 is defined to be a better function than another
10834 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10835 // conversion sequence than ICSi(F2), and then...
10836 bool HasWorseConversion = false;
10837 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10839 Cand1.Conversions[ArgIdx],
10840 Cand2.Conversions[ArgIdx])) {
10842 // Cand1 has a better conversion sequence.
10843 HasBetterConversion = true;
10844 break;
10845
10847 if (Cand1.Function && Cand2.Function &&
10848 Cand1.isReversed() != Cand2.isReversed() &&
10849 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10850 // Work around large-scale breakage caused by considering reversed
10851 // forms of operator== in C++20:
10852 //
10853 // When comparing a function against a reversed function, if we have a
10854 // better conversion for one argument and a worse conversion for the
10855 // other, the implicit conversion sequences are treated as being equally
10856 // good.
10857 //
10858 // This prevents a comparison function from being considered ambiguous
10859 // with a reversed form that is written in the same way.
10860 //
10861 // We diagnose this as an extension from CreateOverloadedBinOp.
10862 HasWorseConversion = true;
10863 break;
10864 }
10865
10866 // Cand1 can't be better than Cand2.
10867 return false;
10868
10870 // Do nothing.
10871 break;
10872 }
10873 }
10874
10875 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10876 // ICSj(F2), or, if not that,
10877 if (HasBetterConversion && !HasWorseConversion)
10878 return true;
10879
10880 // -- the context is an initialization by user-defined conversion
10881 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10882 // from the return type of F1 to the destination type (i.e.,
10883 // the type of the entity being initialized) is a better
10884 // conversion sequence than the standard conversion sequence
10885 // from the return type of F2 to the destination type.
10887 Cand1.Function && Cand2.Function &&
10890
10891 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10892 // First check whether we prefer one of the conversion functions over the
10893 // other. This only distinguishes the results in non-standard, extension
10894 // cases such as the conversion from a lambda closure type to a function
10895 // pointer or block.
10900 Cand1.FinalConversion,
10901 Cand2.FinalConversion);
10902
10905
10906 // FIXME: Compare kind of reference binding if conversion functions
10907 // convert to a reference type used in direct reference binding, per
10908 // C++14 [over.match.best]p1 section 2 bullet 3.
10909 }
10910
10911 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10912 // as combined with the resolution to CWG issue 243.
10913 //
10914 // When the context is initialization by constructor ([over.match.ctor] or
10915 // either phase of [over.match.list]), a constructor is preferred over
10916 // a conversion function.
10917 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10918 Cand1.Function && Cand2.Function &&
10921 return isa<CXXConstructorDecl>(Cand1.Function);
10922
10923 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10924 return Cand2.StrictPackMatch;
10925
10926 // -- F1 is a non-template function and F2 is a function template
10927 // specialization, or, if not that,
10928 bool Cand1IsSpecialization = Cand1.Function &&
10930 bool Cand2IsSpecialization = Cand2.Function &&
10932 if (Cand1IsSpecialization != Cand2IsSpecialization)
10933 return Cand2IsSpecialization;
10934
10935 // -- F1 and F2 are function template specializations, and the function
10936 // template for F1 is more specialized than the template for F2
10937 // according to the partial ordering rules described in 14.5.5.2, or,
10938 // if not that,
10939 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10940 const auto *Obj1Context =
10941 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10942 const auto *Obj2Context =
10943 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10944 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10946 Cand2.Function->getPrimaryTemplate(), Loc,
10948 : TPOC_Call,
10950 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10951 : QualType{},
10952 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10953 : QualType{},
10954 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10955 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10956 }
10957 }
10958
10959 // -— F1 and F2 are non-template functions and F1 is more
10960 // partial-ordering-constrained than F2 [...],
10962 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10963 Cand2.isReversed());
10964 F && F == Cand1.Function)
10965 return true;
10966
10967 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10968 // class B of D, and for all arguments the corresponding parameters of
10969 // F1 and F2 have the same type.
10970 // FIXME: Implement the "all parameters have the same type" check.
10971 bool Cand1IsInherited =
10972 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10973 bool Cand2IsInherited =
10974 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10975 if (Cand1IsInherited != Cand2IsInherited)
10976 return Cand2IsInherited;
10977 else if (Cand1IsInherited) {
10978 assert(Cand2IsInherited);
10979 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10980 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10981 if (Cand1Class->isDerivedFrom(Cand2Class))
10982 return true;
10983 if (Cand2Class->isDerivedFrom(Cand1Class))
10984 return false;
10985 // Inherited from sibling base classes: still ambiguous.
10986 }
10987
10988 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10989 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10990 // with reversed order of parameters and F1 is not
10991 //
10992 // We rank reversed + different operator as worse than just reversed, but
10993 // that comparison can never happen, because we only consider reversing for
10994 // the maximally-rewritten operator (== or <=>).
10995 if (Cand1.RewriteKind != Cand2.RewriteKind)
10996 return Cand1.RewriteKind < Cand2.RewriteKind;
10997
10998 // Check C++17 tie-breakers for deduction guides.
10999 {
11000 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11001 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11002 if (Guide1 && Guide2) {
11003 // -- F1 is generated from a deduction-guide and F2 is not
11004 if (Guide1->isImplicit() != Guide2->isImplicit())
11005 return Guide2->isImplicit();
11006
11007 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11008 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11009 return true;
11010 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11011 return false;
11012
11013 // --F1 is generated from a non-template constructor and F2 is generated
11014 // from a constructor template
11015 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11016 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11017 if (Constructor1 && Constructor2) {
11018 bool isC1Templated = Constructor1->getTemplatedKind() !=
11020 bool isC2Templated = Constructor2->getTemplatedKind() !=
11022 if (isC1Templated != isC2Templated)
11023 return isC2Templated;
11024 }
11025 }
11026 }
11027
11028 // Check for enable_if value-based overload resolution.
11029 if (Cand1.Function && Cand2.Function) {
11030 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11031 if (Cmp != Comparison::Equal)
11032 return Cmp == Comparison::Better;
11033 }
11034
11035 bool HasPS1 = Cand1.Function != nullptr &&
11037 bool HasPS2 = Cand2.Function != nullptr &&
11039 if (HasPS1 != HasPS2 && HasPS1)
11040 return true;
11041
11042 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11043 if (MV == Comparison::Better)
11044 return true;
11045 if (MV == Comparison::Worse)
11046 return false;
11047
11048 // If other rules cannot determine which is better, CUDA preference is used
11049 // to determine which is better.
11050 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11051 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11052 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11053 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11054 }
11055
11056 // General member function overloading is handled above, so this only handles
11057 // constructors with address spaces.
11058 // This only handles address spaces since C++ has no other
11059 // qualifier that can be used with constructors.
11060 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11061 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11062 if (CD1 && CD2) {
11063 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11064 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11065 if (AS1 != AS2) {
11067 return true;
11069 return false;
11070 }
11071 }
11072
11073 return false;
11074}
11075
11076/// Determine whether two declarations are "equivalent" for the purposes of
11077/// name lookup and overload resolution. This applies when the same internal/no
11078/// linkage entity is defined by two modules (probably by textually including
11079/// the same header). In such a case, we don't consider the declarations to
11080/// declare the same entity, but we also don't want lookups with both
11081/// declarations visible to be ambiguous in some cases (this happens when using
11082/// a modularized libstdc++).
11084 const NamedDecl *B) {
11085 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11086 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11087 if (!VA || !VB)
11088 return false;
11089
11090 // The declarations must be declaring the same name as an internal linkage
11091 // entity in different modules.
11092 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11093 VB->getDeclContext()->getRedeclContext()) ||
11094 getOwningModule(VA) == getOwningModule(VB) ||
11095 VA->isExternallyVisible() || VB->isExternallyVisible())
11096 return false;
11097
11098 // Check that the declarations appear to be equivalent.
11099 //
11100 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11101 // For constants and functions, we should check the initializer or body is
11102 // the same. For non-constant variables, we shouldn't allow it at all.
11103 if (Context.hasSameType(VA->getType(), VB->getType()))
11104 return true;
11105
11106 // Enum constants within unnamed enumerations will have different types, but
11107 // may still be similar enough to be interchangeable for our purposes.
11108 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11109 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11110 // Only handle anonymous enums. If the enumerations were named and
11111 // equivalent, they would have been merged to the same type.
11112 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11113 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11114 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11115 !Context.hasSameType(EnumA->getIntegerType(),
11116 EnumB->getIntegerType()))
11117 return false;
11118 // Allow this only if the value is the same for both enumerators.
11119 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11120 }
11121 }
11122
11123 // Nothing else is sufficiently similar.
11124 return false;
11125}
11126
11129 assert(D && "Unknown declaration");
11130 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11131
11132 Module *M = getOwningModule(D);
11133 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11134 << !M << (M ? M->getFullModuleName() : "");
11135
11136 for (auto *E : Equiv) {
11137 Module *M = getOwningModule(E);
11138 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11139 << !M << (M ? M->getFullModuleName() : "");
11140 }
11141}
11142
11145 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11147 static_cast<CNSInfo *>(DeductionFailure.Data)
11148 ->Satisfaction.ContainsErrors;
11149}
11150
11153 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11154 bool PartialOverloading, bool AllowExplicit,
11156 bool AggregateCandidateDeduction) {
11157
11158 auto *C =
11159 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11160
11163 /*AllowObjCConversionOnExplicit=*/false,
11164 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11165 PartialOverloading, AggregateCandidateDeduction},
11167 FoundDecl,
11168 Args,
11169 IsADLCandidate,
11170 PO};
11171
11172 HasDeferredTemplateConstructors |=
11173 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11174}
11175
11177 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11178 CXXRecordDecl *ActingContext, QualType ObjectType,
11179 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11180 bool SuppressUserConversions, bool PartialOverloading,
11182
11183 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11184
11185 auto *C =
11186 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11187
11190 /*AllowObjCConversionOnExplicit=*/false,
11191 /*AllowResultConversion=*/false,
11192 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11193 /*AggregateCandidateDeduction=*/false},
11194 MethodTmpl,
11195 FoundDecl,
11196 Args,
11197 ActingContext,
11198 ObjectClassification,
11199 ObjectType,
11200 PO};
11201}
11202
11205 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11206 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11207 bool AllowResultConversion) {
11208
11209 auto *C =
11210 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11211
11214 AllowObjCConversionOnExplicit, AllowResultConversion,
11215 /*AllowExplicit=*/false,
11216 /*SuppressUserConversions=*/false,
11217 /*PartialOverloading*/ false,
11218 /*AggregateCandidateDeduction=*/false},
11220 FoundDecl,
11221 ActingContext,
11222 From,
11223 ToType};
11224}
11225
11226static void
11229
11231 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11232 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11233 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11234}
11235
11236static void
11240 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11241 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11242 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11243 C.AggregateCandidateDeduction);
11244}
11245
11246static void
11250 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11251 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11252 C.AllowResultConversion);
11253}
11254
11256 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11257 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11258 while (Cand) {
11259 switch (Cand->Kind) {
11262 S, *this,
11263 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11264 break;
11267 S, *this,
11268 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11269 break;
11272 S, *this,
11273 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11274 break;
11275 }
11276 Cand = Cand->Next;
11277 }
11278 FirstDeferredCandidate = nullptr;
11279 DeferredCandidatesCount = 0;
11280}
11281
11283OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11284 Best->Best = true;
11285 if (Best->Function && Best->Function->isDeleted())
11286 return OR_Deleted;
11287 return OR_Success;
11288}
11289
11290void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11292 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11293 // are accepted by both clang and NVCC. However, during a particular
11294 // compilation mode only one call variant is viable. We need to
11295 // exclude non-viable overload candidates from consideration based
11296 // only on their host/device attributes. Specifically, if one
11297 // candidate call is WrongSide and the other is SameSide, we ignore
11298 // the WrongSide candidate.
11299 // We only need to remove wrong-sided candidates here if
11300 // -fgpu-exclude-wrong-side-overloads is off. When
11301 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11302 // uniformly in isBetterOverloadCandidate.
11303 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11304 return;
11305 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11306
11307 bool ContainsSameSideCandidate =
11308 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11309 // Check viable function only.
11310 return Cand->Viable && Cand->Function &&
11311 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11313 });
11314
11315 if (!ContainsSameSideCandidate)
11316 return;
11317
11318 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11319 // Check viable function only to avoid unnecessary data copying/moving.
11320 return Cand->Viable && Cand->Function &&
11321 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11323 };
11324 llvm::erase_if(Candidates, IsWrongSideCandidate);
11325}
11326
11327/// Computes the best viable function (C++ 13.3.3)
11328/// within an overload candidate set.
11329///
11330/// \param Loc The location of the function name (or operator symbol) for
11331/// which overload resolution occurs.
11332///
11333/// \param Best If overload resolution was successful or found a deleted
11334/// function, \p Best points to the candidate function found.
11335///
11336/// \returns The result of overload resolution.
11338 SourceLocation Loc,
11339 iterator &Best) {
11340
11342 DeferredCandidatesCount == 0) &&
11343 "Unexpected deferred template candidates");
11344
11345 bool TwoPhaseResolution =
11346 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11347
11348 if (TwoPhaseResolution) {
11349 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11350 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11351 if (!(HasDeferredTemplateConstructors &&
11352 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11353 return Res;
11354 }
11355 }
11356
11358 return BestViableFunctionImpl(S, Loc, Best);
11359}
11360
11361OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11363
11365 Candidates.reserve(this->Candidates.size());
11366 std::transform(this->Candidates.begin(), this->Candidates.end(),
11367 std::back_inserter(Candidates),
11368 [](OverloadCandidate &Cand) { return &Cand; });
11369
11370 if (S.getLangOpts().CUDA)
11371 CudaExcludeWrongSideCandidates(S, Candidates);
11372
11373 Best = end();
11374 for (auto *Cand : Candidates) {
11375 Cand->Best = false;
11376 if (Cand->Viable) {
11377 if (Best == end() ||
11378 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11379 Best = Cand;
11380 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11381 // This candidate has constraint that we were unable to evaluate because
11382 // it referenced an expression that contained an error. Rather than fall
11383 // back onto a potentially unintended candidate (made worse by
11384 // subsuming constraints), treat this as 'no viable candidate'.
11385 Best = end();
11386 return OR_No_Viable_Function;
11387 }
11388 }
11389
11390 // If we didn't find any viable functions, abort.
11391 if (Best == end())
11392 return OR_No_Viable_Function;
11393
11394 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11395 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11396 PendingBest.push_back(&*Best);
11397 Best->Best = true;
11398
11399 // Make sure that this function is better than every other viable
11400 // function. If not, we have an ambiguity.
11401 while (!PendingBest.empty()) {
11402 auto *Curr = PendingBest.pop_back_val();
11403 for (auto *Cand : Candidates) {
11404 if (Cand->Viable && !Cand->Best &&
11405 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11406 PendingBest.push_back(Cand);
11407 Cand->Best = true;
11408
11410 Curr->Function))
11411 EquivalentCands.push_back(Cand->Function);
11412 else
11413 Best = end();
11414 }
11415 }
11416 }
11417
11418 if (Best == end())
11419 return OR_Ambiguous;
11420
11421 OverloadingResult R = ResultForBestCandidate(Best);
11422
11423 if (!EquivalentCands.empty())
11425 EquivalentCands);
11426 return R;
11427}
11428
11429namespace {
11430
11431enum OverloadCandidateKind {
11432 oc_function,
11433 oc_method,
11434 oc_reversed_binary_operator,
11435 oc_constructor,
11436 oc_implicit_default_constructor,
11437 oc_implicit_copy_constructor,
11438 oc_implicit_move_constructor,
11439 oc_implicit_copy_assignment,
11440 oc_implicit_move_assignment,
11441 oc_implicit_equality_comparison,
11442 oc_inherited_constructor
11443};
11444
11445enum OverloadCandidateSelect {
11446 ocs_non_template,
11447 ocs_template,
11448 ocs_described_template,
11449};
11450
11451static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11452ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11453 const FunctionDecl *Fn,
11455 std::string &Description) {
11456
11457 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11458 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11459 isTemplate = true;
11460 Description = S.getTemplateArgumentBindingsText(
11461 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11462 }
11463
11464 OverloadCandidateSelect Select = [&]() {
11465 if (!Description.empty())
11466 return ocs_described_template;
11467 return isTemplate ? ocs_template : ocs_non_template;
11468 }();
11469
11470 OverloadCandidateKind Kind = [&]() {
11471 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11472 return oc_implicit_equality_comparison;
11473
11474 if (CRK & CRK_Reversed)
11475 return oc_reversed_binary_operator;
11476
11477 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11478 if (!Ctor->isImplicit()) {
11480 return oc_inherited_constructor;
11481 else
11482 return oc_constructor;
11483 }
11484
11485 if (Ctor->isDefaultConstructor())
11486 return oc_implicit_default_constructor;
11487
11488 if (Ctor->isMoveConstructor())
11489 return oc_implicit_move_constructor;
11490
11491 assert(Ctor->isCopyConstructor() &&
11492 "unexpected sort of implicit constructor");
11493 return oc_implicit_copy_constructor;
11494 }
11495
11496 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11497 // This actually gets spelled 'candidate function' for now, but
11498 // it doesn't hurt to split it out.
11499 if (!Meth->isImplicit())
11500 return oc_method;
11501
11502 if (Meth->isMoveAssignmentOperator())
11503 return oc_implicit_move_assignment;
11504
11505 if (Meth->isCopyAssignmentOperator())
11506 return oc_implicit_copy_assignment;
11507
11508 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11509 return oc_method;
11510 }
11511
11512 return oc_function;
11513 }();
11514
11515 return std::make_pair(Kind, Select);
11516}
11517
11518void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11519 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11520 // set.
11521 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11522 S.Diag(FoundDecl->getLocation(),
11523 diag::note_ovl_candidate_inherited_constructor)
11524 << Shadow->getNominatedBaseClass();
11525}
11526
11527} // end anonymous namespace
11528
11530 const FunctionDecl *FD) {
11531 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11532 bool AlwaysTrue;
11533 if (EnableIf->getCond()->isValueDependent() ||
11534 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11535 return false;
11536 if (!AlwaysTrue)
11537 return false;
11538 }
11539 return true;
11540}
11541
11542/// Returns true if we can take the address of the function.
11543///
11544/// \param Complain - If true, we'll emit a diagnostic
11545/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11546/// we in overload resolution?
11547/// \param Loc - The location of the statement we're complaining about. Ignored
11548/// if we're not complaining, or if we're in overload resolution.
11550 bool Complain,
11551 bool InOverloadResolution,
11552 SourceLocation Loc) {
11553 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11554 if (Complain) {
11555 if (InOverloadResolution)
11556 S.Diag(FD->getBeginLoc(),
11557 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11558 else
11559 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11560 }
11561 return false;
11562 }
11563
11564 if (FD->getTrailingRequiresClause()) {
11565 ConstraintSatisfaction Satisfaction;
11566 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11567 return false;
11568 if (!Satisfaction.IsSatisfied) {
11569 if (Complain) {
11570 if (InOverloadResolution) {
11571 SmallString<128> TemplateArgString;
11572 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11573 TemplateArgString += " ";
11574 TemplateArgString += S.getTemplateArgumentBindingsText(
11575 FunTmpl->getTemplateParameters(),
11577 }
11578
11579 S.Diag(FD->getBeginLoc(),
11580 diag::note_ovl_candidate_unsatisfied_constraints)
11581 << TemplateArgString;
11582 } else
11583 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11584 << FD;
11585 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11586 }
11587 return false;
11588 }
11589 }
11590
11591 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11592 return P->hasAttr<PassObjectSizeAttr>();
11593 });
11594 if (I == FD->param_end())
11595 return true;
11596
11597 if (Complain) {
11598 // Add one to ParamNo because it's user-facing
11599 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11600 if (InOverloadResolution)
11601 S.Diag(FD->getLocation(),
11602 diag::note_ovl_candidate_has_pass_object_size_params)
11603 << ParamNo;
11604 else
11605 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11606 << FD << ParamNo;
11607 }
11608 return false;
11609}
11610
11612 const FunctionDecl *FD) {
11613 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11614 /*InOverloadResolution=*/true,
11615 /*Loc=*/SourceLocation());
11616}
11617
11619 bool Complain,
11620 SourceLocation Loc) {
11621 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11622 /*InOverloadResolution=*/false,
11623 Loc);
11624}
11625
11626// Don't print candidates other than the one that matches the calling
11627// convention of the call operator, since that is guaranteed to exist.
11629 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11630
11631 if (!ConvD)
11632 return false;
11633 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11634 if (!RD->isLambda())
11635 return false;
11636
11637 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11638 CallingConv CallOpCC =
11639 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11640 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11641 CallingConv ConvToCC =
11642 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11643
11644 return ConvToCC != CallOpCC;
11645}
11646
11647// Notes the location of an overload candidate.
11649 OverloadCandidateRewriteKind RewriteKind,
11650 QualType DestType, bool TakingAddress) {
11651 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11652 return;
11653 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11654 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11655 return;
11656 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11657 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11658 return;
11660 return;
11661
11662 std::string FnDesc;
11663 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11664 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11665 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11666 << (unsigned)KSPair.first << (unsigned)KSPair.second
11667 << Fn << FnDesc;
11668
11669 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11670 Diag(Fn->getLocation(), PD);
11671 MaybeEmitInheritedConstructorNote(*this, Found);
11672}
11673
11674static void
11676 // Perhaps the ambiguity was caused by two atomic constraints that are
11677 // 'identical' but not equivalent:
11678 //
11679 // void foo() requires (sizeof(T) > 4) { } // #1
11680 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11681 //
11682 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11683 // #2 to subsume #1, but these constraint are not considered equivalent
11684 // according to the subsumption rules because they are not the same
11685 // source-level construct. This behavior is quite confusing and we should try
11686 // to help the user figure out what happened.
11687
11688 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11689 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11690 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11691 if (!I->Function)
11692 continue;
11694 if (auto *Template = I->Function->getPrimaryTemplate())
11695 Template->getAssociatedConstraints(AC);
11696 else
11697 I->Function->getAssociatedConstraints(AC);
11698 if (AC.empty())
11699 continue;
11700 if (FirstCand == nullptr) {
11701 FirstCand = I->Function;
11702 FirstAC = AC;
11703 } else if (SecondCand == nullptr) {
11704 SecondCand = I->Function;
11705 SecondAC = AC;
11706 } else {
11707 // We have more than one pair of constrained functions - this check is
11708 // expensive and we'd rather not try to diagnose it.
11709 return;
11710 }
11711 }
11712 if (!SecondCand)
11713 return;
11714 // The diagnostic can only happen if there are associated constraints on
11715 // both sides (there needs to be some identical atomic constraint).
11716 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11717 SecondCand, SecondAC))
11718 // Just show the user one diagnostic, they'll probably figure it out
11719 // from here.
11720 return;
11721}
11722
11723// Notes the location of all overload candidates designated through
11724// OverloadedExpr
11725void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11726 bool TakingAddress) {
11727 assert(OverloadedExpr->getType() == Context.OverloadTy);
11728
11729 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11730 OverloadExpr *OvlExpr = Ovl.Expression;
11731
11732 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11733 IEnd = OvlExpr->decls_end();
11734 I != IEnd; ++I) {
11735 if (FunctionTemplateDecl *FunTmpl =
11736 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11737 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11738 TakingAddress);
11739 } else if (FunctionDecl *Fun
11740 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11741 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11742 }
11743 }
11744}
11745
11746/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11747/// "lead" diagnostic; it will be given two arguments, the source and
11748/// target types of the conversion.
11750 Sema &S,
11751 SourceLocation CaretLoc,
11752 const PartialDiagnostic &PDiag) const {
11753 S.Diag(CaretLoc, PDiag)
11754 << Ambiguous.getFromType() << Ambiguous.getToType();
11755 unsigned CandsShown = 0;
11757 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11758 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11759 break;
11760 ++CandsShown;
11761 S.NoteOverloadCandidate(I->first, I->second);
11762 }
11763 S.Diags.overloadCandidatesShown(CandsShown);
11764 if (I != E)
11765 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11766}
11767
11769 unsigned I, bool TakingCandidateAddress) {
11770 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11771 assert(Conv.isBad());
11772 assert(Cand->Function && "for now, candidate must be a function");
11773 FunctionDecl *Fn = Cand->Function;
11774
11775 // There's a conversion slot for the object argument if this is a
11776 // non-constructor method. Note that 'I' corresponds the
11777 // conversion-slot index.
11778 bool isObjectArgument = false;
11779 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11781 if (I == 0)
11782 isObjectArgument = true;
11783 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11784 I--;
11785 }
11786
11787 std::string FnDesc;
11788 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11789 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11790 FnDesc);
11791
11792 Expr *FromExpr = Conv.Bad.FromExpr;
11793 QualType FromTy = Conv.Bad.getFromType();
11794 QualType ToTy = Conv.Bad.getToType();
11795 SourceRange ToParamRange;
11796
11797 // FIXME: In presence of parameter packs we can't determine parameter range
11798 // reliably, as we don't have access to instantiation.
11799 bool HasParamPack =
11800 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11801 return Parm->isParameterPack();
11802 });
11803 if (!isObjectArgument && !HasParamPack)
11804 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11805
11806 if (FromTy == S.Context.OverloadTy) {
11807 assert(FromExpr && "overload set argument came from implicit argument?");
11808 Expr *E = FromExpr->IgnoreParens();
11809 if (isa<UnaryOperator>(E))
11810 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11811 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11812
11813 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11814 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11815 << ToParamRange << ToTy << Name << I + 1;
11816 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11817 return;
11818 }
11819
11820 // Do some hand-waving analysis to see if the non-viability is due
11821 // to a qualifier mismatch.
11822 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11823 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11824 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11825 CToTy = RT->getPointeeType();
11826 else {
11827 // TODO: detect and diagnose the full richness of const mismatches.
11828 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11829 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11830 CFromTy = FromPT->getPointeeType();
11831 CToTy = ToPT->getPointeeType();
11832 }
11833 }
11834
11835 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11836 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11837 Qualifiers FromQs = CFromTy.getQualifiers();
11838 Qualifiers ToQs = CToTy.getQualifiers();
11839
11840 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11841 if (isObjectArgument)
11842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11843 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11844 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11845 else
11846 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11847 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11848 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11849 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11850 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11851 return;
11852 }
11853
11854 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11855 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11856 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11857 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11858 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11859 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11860 return;
11861 }
11862
11863 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11865 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11866 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11867 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11868 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11869 return;
11870 }
11871
11872 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11873 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11874 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11875 << FromTy << !!FromQs.getPointerAuth()
11876 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11877 << ToQs.getPointerAuth().getAsString() << I + 1
11878 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11879 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11880 return;
11881 }
11882
11883 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11884 assert(CVR && "expected qualifiers mismatch");
11885
11886 if (isObjectArgument) {
11887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11888 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11889 << FromTy << (CVR - 1);
11890 } else {
11891 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11892 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11893 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11894 }
11895 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11896 return;
11897 }
11898
11901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11902 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11903 << (unsigned)isObjectArgument << I + 1
11905 << ToParamRange;
11906 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11907 return;
11908 }
11909
11910 // Special diagnostic for failure to convert an initializer list, since
11911 // telling the user that it has type void is not useful.
11912 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11913 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11914 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11915 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11918 ? 2
11919 : 0);
11920 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11921 return;
11922 }
11923
11924 // Diagnose references or pointers to incomplete types differently,
11925 // since it's far from impossible that the incompleteness triggered
11926 // the failure.
11927 QualType TempFromTy = FromTy.getNonReferenceType();
11928 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11929 TempFromTy = PTy->getPointeeType();
11930 if (TempFromTy->isIncompleteType()) {
11931 // Emit the generic diagnostic and, optionally, add the hints to it.
11932 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11933 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11934 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11935 << (unsigned)(Cand->Fix.Kind);
11936
11937 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11938 return;
11939 }
11940
11941 // Diagnose base -> derived pointer conversions.
11942 unsigned BaseToDerivedConversion = 0;
11943 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11944 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11945 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11946 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11947 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11948 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11949 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11950 FromPtrTy->getPointeeType()))
11951 BaseToDerivedConversion = 1;
11952 }
11953 } else if (const ObjCObjectPointerType *FromPtrTy
11954 = FromTy->getAs<ObjCObjectPointerType>()) {
11955 if (const ObjCObjectPointerType *ToPtrTy
11956 = ToTy->getAs<ObjCObjectPointerType>())
11957 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11958 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11959 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11960 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11961 FromIface->isSuperClassOf(ToIface))
11962 BaseToDerivedConversion = 2;
11963 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11964 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11965 S.getASTContext()) &&
11966 !FromTy->isIncompleteType() &&
11967 !ToRefTy->getPointeeType()->isIncompleteType() &&
11968 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11969 BaseToDerivedConversion = 3;
11970 }
11971 }
11972
11973 if (BaseToDerivedConversion) {
11974 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11975 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11976 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11977 << I + 1;
11978 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11979 return;
11980 }
11981
11982 if (isa<ObjCObjectPointerType>(CFromTy) &&
11983 isa<PointerType>(CToTy)) {
11984 Qualifiers FromQs = CFromTy.getQualifiers();
11985 Qualifiers ToQs = CToTy.getQualifiers();
11986 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11987 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11988 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11989 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11990 << I + 1;
11991 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11992 return;
11993 }
11994 }
11995
11996 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11997 return;
11998
11999 // Emit the generic diagnostic and, optionally, add the hints to it.
12000 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12001 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12002 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12003 << (unsigned)(Cand->Fix.Kind);
12004
12005 // Check that location of Fn is not in system header.
12006 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12007 // If we can fix the conversion, suggest the FixIts.
12008 for (const FixItHint &HI : Cand->Fix.Hints)
12009 FDiag << HI;
12010 }
12011
12012 S.Diag(Fn->getLocation(), FDiag);
12013
12014 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12015}
12016
12017/// Additional arity mismatch diagnosis specific to a function overload
12018/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12019/// over a candidate in any candidate set.
12021 unsigned NumArgs, bool IsAddressOf = false) {
12022 assert(Cand->Function && "Candidate is required to be a function.");
12023 FunctionDecl *Fn = Cand->Function;
12024 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12025 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12026
12027 // With invalid overloaded operators, it's possible that we think we
12028 // have an arity mismatch when in fact it looks like we have the
12029 // right number of arguments, because only overloaded operators have
12030 // the weird behavior of overloading member and non-member functions.
12031 // Just don't report anything.
12032 if (Fn->isInvalidDecl() &&
12033 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12034 return true;
12035
12036 if (NumArgs < MinParams) {
12037 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12039 Cand->DeductionFailure.getResult() ==
12041 } else {
12042 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12044 Cand->DeductionFailure.getResult() ==
12046 }
12047
12048 return false;
12049}
12050
12051/// General arity mismatch diagnosis over a candidate in a candidate set.
12053 unsigned NumFormalArgs,
12054 bool IsAddressOf = false) {
12055 assert(isa<FunctionDecl>(D) &&
12056 "The templated declaration should at least be a function"
12057 " when diagnosing bad template argument deduction due to too many"
12058 " or too few arguments");
12059
12061
12062 // TODO: treat calls to a missing default constructor as a special case
12063 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12064 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12065 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12066
12067 // at least / at most / exactly
12068 bool HasExplicitObjectParam =
12069 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12070
12071 unsigned ParamCount =
12072 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12073 unsigned mode, modeCount;
12074
12075 if (NumFormalArgs < MinParams) {
12076 if (MinParams != ParamCount || FnTy->isVariadic() ||
12077 FnTy->isTemplateVariadic())
12078 mode = 0; // "at least"
12079 else
12080 mode = 2; // "exactly"
12081 modeCount = MinParams;
12082 } else {
12083 if (MinParams != ParamCount)
12084 mode = 1; // "at most"
12085 else
12086 mode = 2; // "exactly"
12087 modeCount = ParamCount;
12088 }
12089
12090 std::string Description;
12091 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12092 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12093
12094 if (modeCount == 1 && !IsAddressOf &&
12095 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12097 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12098 << Description << mode
12099 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12100 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12101 else
12102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12103 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12104 << Description << mode << modeCount << NumFormalArgs
12105 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12106
12107 MaybeEmitInheritedConstructorNote(S, Found);
12108}
12109
12110/// Arity mismatch diagnosis specific to a function overload candidate.
12112 unsigned NumFormalArgs) {
12113 assert(Cand->Function && "Candidate must be a function");
12114 FunctionDecl *Fn = Cand->Function;
12115 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12116 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12117 Cand->TookAddressOfOverload);
12118}
12119
12121 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12122 return TD;
12123 llvm_unreachable("Unsupported: Getting the described template declaration"
12124 " for bad deduction diagnosis");
12125}
12126
12127/// Diagnose a failed template-argument deduction.
12128static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12129 DeductionFailureInfo &DeductionFailure,
12130 unsigned NumArgs,
12131 bool TakingCandidateAddress) {
12132 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12133 NamedDecl *ParamD;
12134 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12135 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12136 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12137 switch (DeductionFailure.getResult()) {
12139 llvm_unreachable(
12140 "TemplateDeductionResult::Success while diagnosing bad deduction");
12142 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12143 "while diagnosing bad deduction");
12146 return;
12147
12149 assert(ParamD && "no parameter found for incomplete deduction result");
12150 S.Diag(Templated->getLocation(),
12151 diag::note_ovl_candidate_incomplete_deduction)
12152 << ParamD->getDeclName();
12153 MaybeEmitInheritedConstructorNote(S, Found);
12154 return;
12155 }
12156
12158 assert(ParamD && "no parameter found for incomplete deduction result");
12159 S.Diag(Templated->getLocation(),
12160 diag::note_ovl_candidate_incomplete_deduction_pack)
12161 << ParamD->getDeclName()
12162 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12163 << *DeductionFailure.getFirstArg();
12164 MaybeEmitInheritedConstructorNote(S, Found);
12165 return;
12166 }
12167
12169 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12171
12172 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12173
12174 // Param will have been canonicalized, but it should just be a
12175 // qualified version of ParamD, so move the qualifiers to that.
12177 Qs.strip(Param);
12178 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12179 assert(S.Context.hasSameType(Param, NonCanonParam));
12180
12181 // Arg has also been canonicalized, but there's nothing we can do
12182 // about that. It also doesn't matter as much, because it won't
12183 // have any template parameters in it (because deduction isn't
12184 // done on dependent types).
12185 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12186
12187 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12188 << ParamD->getDeclName() << Arg << NonCanonParam;
12189 MaybeEmitInheritedConstructorNote(S, Found);
12190 return;
12191 }
12192
12194 assert(ParamD && "no parameter found for inconsistent deduction result");
12195 int which = 0;
12196 if (isa<TemplateTypeParmDecl>(ParamD))
12197 which = 0;
12198 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12199 // Deduction might have failed because we deduced arguments of two
12200 // different types for a non-type template parameter.
12201 // FIXME: Use a different TDK value for this.
12202 QualType T1 =
12203 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12204 QualType T2 =
12205 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12206 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12207 S.Diag(Templated->getLocation(),
12208 diag::note_ovl_candidate_inconsistent_deduction_types)
12209 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12210 << *DeductionFailure.getSecondArg() << T2;
12211 MaybeEmitInheritedConstructorNote(S, Found);
12212 return;
12213 }
12214
12215 which = 1;
12216 } else {
12217 which = 2;
12218 }
12219
12220 // Tweak the diagnostic if the problem is that we deduced packs of
12221 // different arities. We'll print the actual packs anyway in case that
12222 // includes additional useful information.
12223 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12224 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12225 DeductionFailure.getFirstArg()->pack_size() !=
12226 DeductionFailure.getSecondArg()->pack_size()) {
12227 which = 3;
12228 }
12229
12230 S.Diag(Templated->getLocation(),
12231 diag::note_ovl_candidate_inconsistent_deduction)
12232 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12233 << *DeductionFailure.getSecondArg();
12234 MaybeEmitInheritedConstructorNote(S, Found);
12235 return;
12236 }
12237
12239 assert(ParamD && "no parameter found for invalid explicit arguments");
12240 if (ParamD->getDeclName())
12241 S.Diag(Templated->getLocation(),
12242 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12243 << ParamD->getDeclName();
12244 else {
12245 int index = 0;
12246 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12247 index = TTP->getIndex();
12248 else if (NonTypeTemplateParmDecl *NTTP
12249 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12250 index = NTTP->getIndex();
12251 else
12252 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12253 S.Diag(Templated->getLocation(),
12254 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12255 << (index + 1);
12256 }
12257 MaybeEmitInheritedConstructorNote(S, Found);
12258 return;
12259
12261 // Format the template argument list into the argument string.
12262 SmallString<128> TemplateArgString;
12263 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12264 TemplateArgString = " ";
12265 TemplateArgString += S.getTemplateArgumentBindingsText(
12266 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12267 if (TemplateArgString.size() == 1)
12268 TemplateArgString.clear();
12269 S.Diag(Templated->getLocation(),
12270 diag::note_ovl_candidate_unsatisfied_constraints)
12271 << TemplateArgString;
12272
12274 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12275 return;
12276 }
12279 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12280 return;
12281
12283 S.Diag(Templated->getLocation(),
12284 diag::note_ovl_candidate_instantiation_depth);
12285 MaybeEmitInheritedConstructorNote(S, Found);
12286 return;
12287
12289 // Format the template argument list into the argument string.
12290 SmallString<128> TemplateArgString;
12291 if (TemplateArgumentList *Args =
12292 DeductionFailure.getTemplateArgumentList()) {
12293 TemplateArgString = " ";
12294 TemplateArgString += S.getTemplateArgumentBindingsText(
12295 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12296 if (TemplateArgString.size() == 1)
12297 TemplateArgString.clear();
12298 }
12299
12300 // If this candidate was disabled by enable_if, say so.
12301 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12302 if (PDiag && PDiag->second.getDiagID() ==
12303 diag::err_typename_nested_not_found_enable_if) {
12304 // FIXME: Use the source range of the condition, and the fully-qualified
12305 // name of the enable_if template. These are both present in PDiag.
12306 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12307 << "'enable_if'" << TemplateArgString;
12308 return;
12309 }
12310
12311 // We found a specific requirement that disabled the enable_if.
12312 if (PDiag && PDiag->second.getDiagID() ==
12313 diag::err_typename_nested_not_found_requirement) {
12314 S.Diag(Templated->getLocation(),
12315 diag::note_ovl_candidate_disabled_by_requirement)
12316 << PDiag->second.getStringArg(0) << TemplateArgString;
12317 return;
12318 }
12319
12320 // Format the SFINAE diagnostic into the argument string.
12321 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12322 // formatted message in another diagnostic.
12323 SmallString<128> SFINAEArgString;
12324 SourceRange R;
12325 if (PDiag) {
12326 SFINAEArgString = ": ";
12327 R = SourceRange(PDiag->first, PDiag->first);
12328 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12329 }
12330
12331 S.Diag(Templated->getLocation(),
12332 diag::note_ovl_candidate_substitution_failure)
12333 << TemplateArgString << SFINAEArgString << R;
12334 MaybeEmitInheritedConstructorNote(S, Found);
12335 return;
12336 }
12337
12340 // Format the template argument list into the argument string.
12341 SmallString<128> TemplateArgString;
12342 if (TemplateArgumentList *Args =
12343 DeductionFailure.getTemplateArgumentList()) {
12344 TemplateArgString = " ";
12345 TemplateArgString += S.getTemplateArgumentBindingsText(
12346 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12347 if (TemplateArgString.size() == 1)
12348 TemplateArgString.clear();
12349 }
12350
12351 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12352 << (*DeductionFailure.getCallArgIndex() + 1)
12353 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12354 << TemplateArgString
12355 << (DeductionFailure.getResult() ==
12357 break;
12358 }
12359
12361 // FIXME: Provide a source location to indicate what we couldn't match.
12362 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12363 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12364 if (FirstTA.getKind() == TemplateArgument::Template &&
12365 SecondTA.getKind() == TemplateArgument::Template) {
12366 TemplateName FirstTN = FirstTA.getAsTemplate();
12367 TemplateName SecondTN = SecondTA.getAsTemplate();
12368 if (FirstTN.getKind() == TemplateName::Template &&
12369 SecondTN.getKind() == TemplateName::Template) {
12370 if (FirstTN.getAsTemplateDecl()->getName() ==
12371 SecondTN.getAsTemplateDecl()->getName()) {
12372 // FIXME: This fixes a bad diagnostic where both templates are named
12373 // the same. This particular case is a bit difficult since:
12374 // 1) It is passed as a string to the diagnostic printer.
12375 // 2) The diagnostic printer only attempts to find a better
12376 // name for types, not decls.
12377 // Ideally, this should folded into the diagnostic printer.
12378 S.Diag(Templated->getLocation(),
12379 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12380 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12381 return;
12382 }
12383 }
12384 }
12385
12386 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12388 return;
12389
12390 // FIXME: For generic lambda parameters, check if the function is a lambda
12391 // call operator, and if so, emit a prettier and more informative
12392 // diagnostic that mentions 'auto' and lambda in addition to
12393 // (or instead of?) the canonical template type parameters.
12394 S.Diag(Templated->getLocation(),
12395 diag::note_ovl_candidate_non_deduced_mismatch)
12396 << FirstTA << SecondTA;
12397 return;
12398 }
12399 // TODO: diagnose these individually, then kill off
12400 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12402 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12403 MaybeEmitInheritedConstructorNote(S, Found);
12404 return;
12406 S.Diag(Templated->getLocation(),
12407 diag::note_cuda_ovl_candidate_target_mismatch);
12408 return;
12409 }
12410}
12411
12412/// Diagnose a failed template-argument deduction, for function calls.
12414 unsigned NumArgs,
12415 bool TakingCandidateAddress) {
12416 assert(Cand->Function && "Candidate must be a function");
12417 FunctionDecl *Fn = Cand->Function;
12421 if (CheckArityMismatch(S, Cand, NumArgs))
12422 return;
12423 }
12424 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12425 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12426}
12427
12428/// CUDA: diagnose an invalid call across targets.
12430 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12431 assert(Cand->Function && "Candidate must be a Function.");
12432 FunctionDecl *Callee = Cand->Function;
12433
12434 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12435 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12436
12437 std::string FnDesc;
12438 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12439 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12440 Cand->getRewriteKind(), FnDesc);
12441
12442 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12443 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12444 << FnDesc /* Ignored */
12445 << CalleeTarget << CallerTarget;
12446
12447 // This could be an implicit constructor for which we could not infer the
12448 // target due to a collsion. Diagnose that case.
12449 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12450 if (Meth != nullptr && Meth->isImplicit()) {
12451 CXXRecordDecl *ParentClass = Meth->getParent();
12453
12454 switch (FnKindPair.first) {
12455 default:
12456 return;
12457 case oc_implicit_default_constructor:
12459 break;
12460 case oc_implicit_copy_constructor:
12462 break;
12463 case oc_implicit_move_constructor:
12465 break;
12466 case oc_implicit_copy_assignment:
12468 break;
12469 case oc_implicit_move_assignment:
12471 break;
12472 };
12473
12474 bool ConstRHS = false;
12475 if (Meth->getNumParams()) {
12476 if (const ReferenceType *RT =
12477 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12478 ConstRHS = RT->getPointeeType().isConstQualified();
12479 }
12480 }
12481
12482 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12483 /* ConstRHS */ ConstRHS,
12484 /* Diagnose */ true);
12485 }
12486}
12487
12489 assert(Cand->Function && "Candidate must be a function");
12490 FunctionDecl *Callee = Cand->Function;
12491 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12492
12493 S.Diag(Callee->getLocation(),
12494 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12495 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12496}
12497
12499 assert(Cand->Function && "Candidate must be a function");
12500 FunctionDecl *Fn = Cand->Function;
12502 assert(ES.isExplicit() && "not an explicit candidate");
12503
12504 unsigned Kind;
12505 switch (Fn->getDeclKind()) {
12506 case Decl::Kind::CXXConstructor:
12507 Kind = 0;
12508 break;
12509 case Decl::Kind::CXXConversion:
12510 Kind = 1;
12511 break;
12512 case Decl::Kind::CXXDeductionGuide:
12513 Kind = Fn->isImplicit() ? 0 : 2;
12514 break;
12515 default:
12516 llvm_unreachable("invalid Decl");
12517 }
12518
12519 // Note the location of the first (in-class) declaration; a redeclaration
12520 // (particularly an out-of-class definition) will typically lack the
12521 // 'explicit' specifier.
12522 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12523 FunctionDecl *First = Fn->getFirstDecl();
12524 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12525 First = Pattern->getFirstDecl();
12526
12527 S.Diag(First->getLocation(),
12528 diag::note_ovl_candidate_explicit)
12529 << Kind << (ES.getExpr() ? 1 : 0)
12530 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12531}
12532
12534 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12535 if (!DG)
12536 return;
12537 TemplateDecl *OriginTemplate =
12539 // We want to always print synthesized deduction guides for type aliases.
12540 // They would retain the explicit bit of the corresponding constructor.
12541 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12542 return;
12543 std::string FunctionProto;
12544 llvm::raw_string_ostream OS(FunctionProto);
12545 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12546 if (!Template) {
12547 // This also could be an instantiation. Find out the primary template.
12548 FunctionDecl *Pattern =
12549 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12550 if (!Pattern) {
12551 // The implicit deduction guide is built on an explicit non-template
12552 // deduction guide. Currently, this might be the case only for type
12553 // aliases.
12554 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12555 // gets merged.
12556 assert(OriginTemplate->isTypeAlias() &&
12557 "Non-template implicit deduction guides are only possible for "
12558 "type aliases");
12559 DG->print(OS);
12560 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12561 << FunctionProto;
12562 return;
12563 }
12565 assert(Template && "Cannot find the associated function template of "
12566 "CXXDeductionGuideDecl?");
12567 }
12568 Template->print(OS);
12569 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12570 << FunctionProto;
12571}
12572
12573/// Generates a 'note' diagnostic for an overload candidate. We've
12574/// already generated a primary error at the call site.
12575///
12576/// It really does need to be a single diagnostic with its caret
12577/// pointed at the candidate declaration. Yes, this creates some
12578/// major challenges of technical writing. Yes, this makes pointing
12579/// out problems with specific arguments quite awkward. It's still
12580/// better than generating twenty screens of text for every failed
12581/// overload.
12582///
12583/// It would be great to be able to express per-candidate problems
12584/// more richly for those diagnostic clients that cared, but we'd
12585/// still have to be just as careful with the default diagnostics.
12586/// \param CtorDestAS Addr space of object being constructed (for ctor
12587/// candidates only).
12589 unsigned NumArgs,
12590 bool TakingCandidateAddress,
12591 LangAS CtorDestAS = LangAS::Default) {
12592 assert(Cand->Function && "Candidate must be a function");
12593 FunctionDecl *Fn = Cand->Function;
12595 return;
12596
12597 // There is no physical candidate declaration to point to for OpenCL builtins.
12598 // Except for failed conversions, the notes are identical for each candidate,
12599 // so do not generate such notes.
12600 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12602 return;
12603
12604 // Skip implicit member functions when trying to resolve
12605 // the address of a an overload set for a function pointer.
12606 if (Cand->TookAddressOfOverload &&
12607 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12608 return;
12609
12610 // Note deleted candidates, but only if they're viable.
12611 if (Cand->Viable) {
12612 if (Fn->isDeleted()) {
12613 std::string FnDesc;
12614 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12615 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12616 Cand->getRewriteKind(), FnDesc);
12617
12618 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12619 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12620 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12621 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12622 return;
12623 }
12624
12625 // We don't really have anything else to say about viable candidates.
12626 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12627 return;
12628 }
12629
12630 // If this is a synthesized deduction guide we're deducing against, add a note
12631 // for it. These deduction guides are not explicitly spelled in the source
12632 // code, so simply printing a deduction failure note mentioning synthesized
12633 // template parameters or pointing to the header of the surrounding RecordDecl
12634 // would be confusing.
12635 //
12636 // We prefer adding such notes at the end of the deduction failure because
12637 // duplicate code snippets appearing in the diagnostic would likely become
12638 // noisy.
12639 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12640
12641 switch (Cand->FailureKind) {
12644 return DiagnoseArityMismatch(S, Cand, NumArgs);
12645
12647 return DiagnoseBadDeduction(S, Cand, NumArgs,
12648 TakingCandidateAddress);
12649
12651 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12652 << (Fn->getPrimaryTemplate() ? 1 : 0);
12653 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12654 return;
12655 }
12656
12658 Qualifiers QualsForPrinting;
12659 QualsForPrinting.setAddressSpace(CtorDestAS);
12660 S.Diag(Fn->getLocation(),
12661 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12662 << QualsForPrinting;
12663 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12664 return;
12665 }
12666
12670 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12671
12673 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12674 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12675 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12676 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12677
12678 // FIXME: this currently happens when we're called from SemaInit
12679 // when user-conversion overload fails. Figure out how to handle
12680 // those conditions and diagnose them well.
12681 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12682 }
12683
12685 return DiagnoseBadTarget(S, Cand);
12686
12687 case ovl_fail_enable_if:
12688 return DiagnoseFailedEnableIfAttr(S, Cand);
12689
12690 case ovl_fail_explicit:
12691 return DiagnoseFailedExplicitSpec(S, Cand);
12692
12694 // It's generally not interesting to note copy/move constructors here.
12695 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12696 return;
12697 S.Diag(Fn->getLocation(),
12698 diag::note_ovl_candidate_inherited_constructor_slice)
12699 << (Fn->getPrimaryTemplate() ? 1 : 0)
12700 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12701 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12702 return;
12703
12705 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12706 (void)Available;
12707 assert(!Available);
12708 break;
12709 }
12711 // Do nothing, these should simply be ignored.
12712 break;
12713
12715 std::string FnDesc;
12716 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12717 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12718 Cand->getRewriteKind(), FnDesc);
12719
12720 S.Diag(Fn->getLocation(),
12721 diag::note_ovl_candidate_constraints_not_satisfied)
12722 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12723 << FnDesc /* Ignored */;
12724 ConstraintSatisfaction Satisfaction;
12725 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12726 /*ForOverloadResolution=*/true))
12727 break;
12728 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12729 }
12730 }
12731}
12732
12735 return;
12736
12737 // Desugar the type of the surrogate down to a function type,
12738 // retaining as many typedefs as possible while still showing
12739 // the function type (and, therefore, its parameter types).
12740 QualType FnType = Cand->Surrogate->getConversionType();
12741 bool isLValueReference = false;
12742 bool isRValueReference = false;
12743 bool isPointer = false;
12744 if (const LValueReferenceType *FnTypeRef =
12745 FnType->getAs<LValueReferenceType>()) {
12746 FnType = FnTypeRef->getPointeeType();
12747 isLValueReference = true;
12748 } else if (const RValueReferenceType *FnTypeRef =
12749 FnType->getAs<RValueReferenceType>()) {
12750 FnType = FnTypeRef->getPointeeType();
12751 isRValueReference = true;
12752 }
12753 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12754 FnType = FnTypePtr->getPointeeType();
12755 isPointer = true;
12756 }
12757 // Desugar down to a function type.
12758 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12759 // Reconstruct the pointer/reference as appropriate.
12760 if (isPointer) FnType = S.Context.getPointerType(FnType);
12761 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12762 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12763
12764 if (!Cand->Viable &&
12766 S.Diag(Cand->Surrogate->getLocation(),
12767 diag::note_ovl_surrogate_constraints_not_satisfied)
12768 << Cand->Surrogate;
12769 ConstraintSatisfaction Satisfaction;
12770 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12771 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12772 } else {
12773 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12774 << FnType;
12775 }
12776}
12777
12778static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12779 SourceLocation OpLoc,
12780 OverloadCandidate *Cand) {
12781 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12782 std::string TypeStr("operator");
12783 TypeStr += Opc;
12784 TypeStr += "(";
12785 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12786 if (Cand->Conversions.size() == 1) {
12787 TypeStr += ")";
12788 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12789 } else {
12790 TypeStr += ", ";
12791 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12792 TypeStr += ")";
12793 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12794 }
12795}
12796
12798 OverloadCandidate *Cand) {
12799 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12800 if (ICS.isBad()) break; // all meaningless after first invalid
12801 if (!ICS.isAmbiguous()) continue;
12802
12804 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12805 }
12806}
12807
12809 if (Cand->Function)
12810 return Cand->Function->getLocation();
12811 if (Cand->IsSurrogate)
12812 return Cand->Surrogate->getLocation();
12813 return SourceLocation();
12814}
12815
12816static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12817 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12821 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12822
12826 return 1;
12827
12830 return 2;
12831
12839 return 3;
12840
12842 return 4;
12843
12845 return 5;
12846
12849 return 6;
12850 }
12851 llvm_unreachable("Unhandled deduction result");
12852}
12853
12854namespace {
12855
12856struct CompareOverloadCandidatesForDisplay {
12857 Sema &S;
12858 SourceLocation Loc;
12859 size_t NumArgs;
12861
12862 CompareOverloadCandidatesForDisplay(
12863 Sema &S, SourceLocation Loc, size_t NArgs,
12865 : S(S), NumArgs(NArgs), CSK(CSK) {}
12866
12867 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12868 // If there are too many or too few arguments, that's the high-order bit we
12869 // want to sort by, even if the immediate failure kind was something else.
12870 if (C->FailureKind == ovl_fail_too_many_arguments ||
12871 C->FailureKind == ovl_fail_too_few_arguments)
12872 return static_cast<OverloadFailureKind>(C->FailureKind);
12873
12874 if (C->Function) {
12875 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12877 if (NumArgs < C->Function->getMinRequiredArguments())
12879 }
12880
12881 return static_cast<OverloadFailureKind>(C->FailureKind);
12882 }
12883
12884 bool operator()(const OverloadCandidate *L,
12885 const OverloadCandidate *R) {
12886 // Fast-path this check.
12887 if (L == R) return false;
12888
12889 // Order first by viability.
12890 if (L->Viable) {
12891 if (!R->Viable) return true;
12892
12893 if (int Ord = CompareConversions(*L, *R))
12894 return Ord < 0;
12895 // Use other tie breakers.
12896 } else if (R->Viable)
12897 return false;
12898
12899 assert(L->Viable == R->Viable);
12900
12901 // Criteria by which we can sort non-viable candidates:
12902 if (!L->Viable) {
12903 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12904 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12905
12906 // 1. Arity mismatches come after other candidates.
12907 if (LFailureKind == ovl_fail_too_many_arguments ||
12908 LFailureKind == ovl_fail_too_few_arguments) {
12909 if (RFailureKind == ovl_fail_too_many_arguments ||
12910 RFailureKind == ovl_fail_too_few_arguments) {
12911 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12912 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12913 if (LDist == RDist) {
12914 if (LFailureKind == RFailureKind)
12915 // Sort non-surrogates before surrogates.
12916 return !L->IsSurrogate && R->IsSurrogate;
12917 // Sort candidates requiring fewer parameters than there were
12918 // arguments given after candidates requiring more parameters
12919 // than there were arguments given.
12920 return LFailureKind == ovl_fail_too_many_arguments;
12921 }
12922 return LDist < RDist;
12923 }
12924 return false;
12925 }
12926 if (RFailureKind == ovl_fail_too_many_arguments ||
12927 RFailureKind == ovl_fail_too_few_arguments)
12928 return true;
12929
12930 // 2. Bad conversions come first and are ordered by the number
12931 // of bad conversions and quality of good conversions.
12932 if (LFailureKind == ovl_fail_bad_conversion) {
12933 if (RFailureKind != ovl_fail_bad_conversion)
12934 return true;
12935
12936 // The conversion that can be fixed with a smaller number of changes,
12937 // comes first.
12938 unsigned numLFixes = L->Fix.NumConversionsFixed;
12939 unsigned numRFixes = R->Fix.NumConversionsFixed;
12940 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12941 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12942 if (numLFixes != numRFixes) {
12943 return numLFixes < numRFixes;
12944 }
12945
12946 // If there's any ordering between the defined conversions...
12947 if (int Ord = CompareConversions(*L, *R))
12948 return Ord < 0;
12949 } else if (RFailureKind == ovl_fail_bad_conversion)
12950 return false;
12951
12952 if (LFailureKind == ovl_fail_bad_deduction) {
12953 if (RFailureKind != ovl_fail_bad_deduction)
12954 return true;
12955
12957 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12958 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12959 if (LRank != RRank)
12960 return LRank < RRank;
12961 }
12962 } else if (RFailureKind == ovl_fail_bad_deduction)
12963 return false;
12964
12965 // TODO: others?
12966 }
12967
12968 // Sort everything else by location.
12969 SourceLocation LLoc = GetLocationForCandidate(L);
12970 SourceLocation RLoc = GetLocationForCandidate(R);
12971
12972 // Put candidates without locations (e.g. builtins) at the end.
12973 if (LLoc.isValid() && RLoc.isValid())
12974 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12975 if (LLoc.isValid() && !RLoc.isValid())
12976 return true;
12977 if (RLoc.isValid() && !LLoc.isValid())
12978 return false;
12979 assert(!LLoc.isValid() && !RLoc.isValid());
12980 // For builtins and other functions without locations, fallback to the order
12981 // in which they were added into the candidate set.
12982 return L < R;
12983 }
12984
12985private:
12986 struct ConversionSignals {
12987 unsigned KindRank = 0;
12989
12990 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12991 ConversionSignals Sig;
12992 Sig.KindRank = Seq.getKindRank();
12993 if (Seq.isStandard())
12994 Sig.Rank = Seq.Standard.getRank();
12995 else if (Seq.isUserDefined())
12996 Sig.Rank = Seq.UserDefined.After.getRank();
12997 // We intend StaticObjectArgumentConversion to compare the same as
12998 // StandardConversion with ICR_ExactMatch rank.
12999 return Sig;
13000 }
13001
13002 static ConversionSignals ForObjectArgument() {
13003 // We intend StaticObjectArgumentConversion to compare the same as
13004 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13005 return {};
13006 }
13007 };
13008
13009 // Returns -1 if conversions in L are considered better.
13010 // 0 if they are considered indistinguishable.
13011 // 1 if conversions in R are better.
13012 int CompareConversions(const OverloadCandidate &L,
13013 const OverloadCandidate &R) {
13014 // We cannot use `isBetterOverloadCandidate` because it is defined
13015 // according to the C++ standard and provides a partial order, but we need
13016 // a total order as this function is used in sort.
13017 assert(L.Conversions.size() == R.Conversions.size());
13018 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13019 auto LS = L.IgnoreObjectArgument && I == 0
13020 ? ConversionSignals::ForObjectArgument()
13021 : ConversionSignals::ForSequence(L.Conversions[I]);
13022 auto RS = R.IgnoreObjectArgument
13023 ? ConversionSignals::ForObjectArgument()
13024 : ConversionSignals::ForSequence(R.Conversions[I]);
13025 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13026 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13027 ? -1
13028 : 1;
13029 }
13030 // FIXME: find a way to compare templates for being more or less
13031 // specialized that provides a strict weak ordering.
13032 return 0;
13033 }
13034};
13035}
13036
13037/// CompleteNonViableCandidate - Normally, overload resolution only
13038/// computes up to the first bad conversion. Produces the FixIt set if
13039/// possible.
13040static void
13042 ArrayRef<Expr *> Args,
13044 assert(!Cand->Viable);
13045
13046 // Don't do anything on failures other than bad conversion.
13048 return;
13049
13050 // We only want the FixIts if all the arguments can be corrected.
13051 bool Unfixable = false;
13052 // Use a implicit copy initialization to check conversion fixes.
13054
13055 // Attempt to fix the bad conversion.
13056 unsigned ConvCount = Cand->Conversions.size();
13057 for (unsigned ConvIdx =
13058 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13059 : 0);
13060 /**/; ++ConvIdx) {
13061 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13062 if (Cand->Conversions[ConvIdx].isInitialized() &&
13063 Cand->Conversions[ConvIdx].isBad()) {
13064 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13065 break;
13066 }
13067 }
13068
13069 // FIXME: this should probably be preserved from the overload
13070 // operation somehow.
13071 bool SuppressUserConversions = false;
13072
13073 unsigned ConvIdx = 0;
13074 unsigned ArgIdx = 0;
13075 ArrayRef<QualType> ParamTypes;
13076 bool Reversed = Cand->isReversed();
13077
13078 if (Cand->IsSurrogate) {
13079 QualType ConvType
13081 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13082 ConvType = ConvPtrType->getPointeeType();
13083 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13084 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13085 ConvIdx = 1;
13086 } else if (Cand->Function) {
13087 ParamTypes =
13088 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13089 if (isa<CXXMethodDecl>(Cand->Function) &&
13092 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13093 ConvIdx = 1;
13095 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13097 OO_Subscript)
13098 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13099 ArgIdx = 1;
13100 }
13101 } else {
13102 // Builtin operator.
13103 assert(ConvCount <= 3);
13104 ParamTypes = Cand->BuiltinParamTypes;
13105 }
13106
13107 // Fill in the rest of the conversions.
13108 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13109 ConvIdx != ConvCount && ArgIdx < Args.size();
13110 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13111 if (Cand->Conversions[ConvIdx].isInitialized()) {
13112 // We've already checked this conversion.
13113 } else if (ParamIdx < ParamTypes.size()) {
13114 if (ParamTypes[ParamIdx]->isDependentType())
13115 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13116 Args[ArgIdx]->getType());
13117 else {
13118 Cand->Conversions[ConvIdx] =
13119 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13120 SuppressUserConversions,
13121 /*InOverloadResolution=*/true,
13122 /*AllowObjCWritebackConversion=*/
13123 S.getLangOpts().ObjCAutoRefCount);
13124 // Store the FixIt in the candidate if it exists.
13125 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13126 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13127 }
13128 } else
13129 Cand->Conversions[ConvIdx].setEllipsis();
13130 }
13131}
13132
13135 SourceLocation OpLoc,
13136 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13137
13139
13140 // Sort the candidates by viability and position. Sorting directly would
13141 // be prohibitive, so we make a set of pointers and sort those.
13143 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13144 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13145 Cand != LastCand; ++Cand) {
13146 if (!Filter(*Cand))
13147 continue;
13148 switch (OCD) {
13149 case OCD_AllCandidates:
13150 if (!Cand->Viable) {
13151 if (!Cand->Function && !Cand->IsSurrogate) {
13152 // This a non-viable builtin candidate. We do not, in general,
13153 // want to list every possible builtin candidate.
13154 continue;
13155 }
13156 CompleteNonViableCandidate(S, Cand, Args, Kind);
13157 }
13158 break;
13159
13161 if (!Cand->Viable)
13162 continue;
13163 break;
13164
13166 if (!Cand->Best)
13167 continue;
13168 break;
13169 }
13170
13171 Cands.push_back(Cand);
13172 }
13173
13174 llvm::stable_sort(
13175 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13176
13177 return Cands;
13178}
13179
13181 SourceLocation OpLoc) {
13182 bool DeferHint = false;
13183 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13184 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13185 // host device candidates.
13186 auto WrongSidedCands =
13187 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13188 return (Cand.Viable == false &&
13190 (Cand.Function &&
13191 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13192 Cand.Function->template hasAttr<CUDADeviceAttr>());
13193 });
13194 DeferHint = !WrongSidedCands.empty();
13195 }
13196 return DeferHint;
13197}
13198
13199/// When overload resolution fails, prints diagnostic messages containing the
13200/// candidates in the candidate set.
13203 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13204 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13205
13206 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13207
13208 {
13209 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13210 S.Diag(PD.first, PD.second);
13211 }
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 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13276 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13277 }
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:45
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:298
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:1488
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1532
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h: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:10271
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:6327
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6356
RAII class to control scope of DeferDiags.
Definition Sema.h:10008
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:12406
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12440
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:10024
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:9297
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9324
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9309
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9305
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:168
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:1441
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:10354
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10357
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10363
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10361
@ AR_dependent
Definition Sema.h:1656
@ AR_accessible
Definition Sema.h:1654
@ AR_inaccessible
Definition Sema.h:1655
@ AR_delayed
Definition Sema.h:1657
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:2045
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:1651
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:1486
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:10742
@ FRS_DiagnosticIssued
Definition Sema.h:10744
@ FRS_NoViableFunction
Definition Sema.h:10743
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9290
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:10075
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:3572
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:12106
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:1451
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9289
MemberPointerConversionDirection
Definition Sema.h:10195
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:10382
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.
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:15403
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:6941
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:1414
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:8136
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:13879
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:7436
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13614
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:15358
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:6712
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6681
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:10187
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:6389
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:1421
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:8615
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:224
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
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
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:10474
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10481
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13048
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13136
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13174
Abstract class used to diagnose incomplete types.
Definition Sema.h:8217
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.