clang 23.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaObjC.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/STLForwardCompat.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdlib>
50#include <optional>
51
52using namespace clang;
53using namespace sema;
54
56
58 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
59 return P->hasAttr<PassObjectSizeAttr>();
60 });
61}
62
63/// A convenience routine for creating a decayed reference to a function.
65 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
66 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
67 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
68 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
69 return ExprError();
70 // If FoundDecl is different from Fn (such as if one is a template
71 // and the other a specialization), make sure DiagnoseUseOfDecl is
72 // called on both.
73 // FIXME: This would be more comprehensively addressed by modifying
74 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
75 // being used.
76 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
77 return ExprError();
78 DeclRefExpr *DRE = new (S.Context)
79 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
80 if (HadMultipleCandidates)
81 DRE->setHadMultipleCandidates(true);
82
84 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
85 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
86 S.ResolveExceptionSpec(Loc, FPT);
87 DRE->setType(Fn->getType());
88 }
89 }
90 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
91 CK_FunctionToPointerDecay);
92}
93
94static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
95 bool InOverloadResolution,
97 bool CStyle,
98 bool AllowObjCWritebackConversion);
99
101 QualType &ToType,
102 bool InOverloadResolution,
104 bool CStyle);
106IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
108 OverloadCandidateSet& Conversions,
109 AllowedExplicit AllowExplicit,
110 bool AllowObjCConversionOnExplicit);
111
114 const StandardConversionSequence& SCS1,
115 const StandardConversionSequence& SCS2);
116
119 const StandardConversionSequence& SCS1,
120 const StandardConversionSequence& SCS2);
121
124 const StandardConversionSequence &SCS1,
125 const StandardConversionSequence &SCS2);
126
129 const StandardConversionSequence& SCS1,
130 const StandardConversionSequence& SCS2);
131
132/// GetConversionRank - Retrieve the implicit conversion rank
133/// corresponding to the given implicit conversion kind.
135 static const ImplicitConversionRank Rank[] = {
162 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
163 // it was omitted by the patch that added
164 // ICK_Zero_Event_Conversion
165 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
166 // it was omitted by the patch that added
167 // ICK_Zero_Queue_Conversion
176 };
177 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
178 return Rank[(int)Kind];
179}
180
199
200/// GetImplicitConversionName - Return the name of this kind of
201/// implicit conversion.
203 static const char *const Name[] = {
204 "No conversion",
205 "Lvalue-to-rvalue",
206 "Array-to-pointer",
207 "Function-to-pointer",
208 "Function pointer conversion",
209 "Qualification",
210 "Integral promotion",
211 "Floating point promotion",
212 "Complex promotion",
213 "Integral conversion",
214 "Floating conversion",
215 "Complex conversion",
216 "Floating-integral conversion",
217 "Pointer conversion",
218 "Pointer-to-member conversion",
219 "Boolean conversion",
220 "Compatible-types conversion",
221 "Derived-to-base conversion",
222 "Vector conversion",
223 "SVE Vector conversion",
224 "RVV Vector conversion",
225 "Vector splat",
226 "Complex-real conversion",
227 "Block Pointer conversion",
228 "Transparent Union Conversion",
229 "Writeback conversion",
230 "OpenCL Zero Event Conversion",
231 "OpenCL Zero Queue Conversion",
232 "C specific type conversion",
233 "Incompatible pointer conversion",
234 "Fixed point conversion",
235 "HLSL vector truncation",
236 "HLSL matrix truncation",
237 "Non-decaying array conversion",
238 "HLSL vector splat",
239 "HLSL matrix splat",
240 };
241 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
242 return Name[Kind];
243}
244
245/// StandardConversionSequence - Set the standard conversion
246/// sequence to the identity conversion.
264
265/// getRank - Retrieve the rank of this standard conversion sequence
266/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
267/// implicit conversions.
280
281/// isPointerConversionToBool - Determines whether this conversion is
282/// a conversion of a pointer or pointer-to-member to bool. This is
283/// used as part of the ranking of standard conversion sequences
284/// (C++ 13.3.3.2p4).
286 // Note that FromType has not necessarily been transformed by the
287 // array-to-pointer or function-to-pointer implicit conversions, so
288 // check for their presence as well as checking whether FromType is
289 // a pointer.
290 if (getToType(1)->isBooleanType() &&
291 (getFromType()->isPointerType() ||
292 getFromType()->isMemberPointerType() ||
293 getFromType()->isObjCObjectPointerType() ||
294 getFromType()->isBlockPointerType() ||
296 return true;
297
298 return false;
299}
300
301/// isPointerConversionToVoidPointer - Determines whether this
302/// conversion is a conversion of a pointer to a void pointer. This is
303/// used as part of the ranking of standard conversion sequences (C++
304/// 13.3.3.2p4).
305bool
308 QualType FromType = getFromType();
309 QualType ToType = getToType(1);
310
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer implicit conversion, so check for its presence
313 // and redo the conversion to get a pointer.
315 FromType = Context.getArrayDecayedType(FromType);
316
317 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
318 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
319 return ToPtrType->getPointeeType()->isVoidType();
320
321 return false;
322}
323
324/// Skip any implicit casts which could be either part of a narrowing conversion
325/// or after one in an implicit conversion.
327 const Expr *Converted) {
328 // We can have cleanups wrapping the converted expression; these need to be
329 // preserved so that destructors run if necessary.
330 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
331 Expr *Inner =
332 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
333 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
334 EWC->getObjects());
335 }
336
337 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
338 switch (ICE->getCastKind()) {
339 case CK_NoOp:
340 case CK_IntegralCast:
341 case CK_IntegralToBoolean:
342 case CK_IntegralToFloating:
343 case CK_BooleanToSignedIntegral:
344 case CK_FloatingToIntegral:
345 case CK_FloatingToBoolean:
346 case CK_FloatingCast:
347 Converted = ICE->getSubExpr();
348 continue;
349
350 default:
351 return Converted;
352 }
353 }
354
355 return Converted;
356}
357
358/// Check if this standard conversion sequence represents a narrowing
359/// conversion, according to C++11 [dcl.init.list]p7.
360///
361/// \param Ctx The AST context.
362/// \param Converted The result of applying this standard conversion sequence.
363/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
364/// value of the expression prior to the narrowing conversion.
365/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
366/// type of the expression prior to the narrowing conversion.
367/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
368/// from floating point types to integral types should be ignored.
370 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
371 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
372 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
373 "narrowing check outside C++");
374
375 // C++11 [dcl.init.list]p7:
376 // A narrowing conversion is an implicit conversion ...
377 QualType FromType = getToType(0);
378 QualType ToType = getToType(1);
379
380 // A conversion to an enumeration type is narrowing if the conversion to
381 // the underlying type is narrowing. This only arises for expressions of
382 // the form 'Enum{init}'.
383 if (const auto *ED = ToType->getAsEnumDecl())
384 ToType = ED->getIntegerType();
385
386 switch (Second) {
387 // 'bool' is an integral type; dispatch to the right place to handle it.
389 if (FromType->isRealFloatingType())
390 goto FloatingIntegralConversion;
392 goto IntegralConversion;
393 // -- from a pointer type or pointer-to-member type to bool, or
394 return NK_Type_Narrowing;
395
396 // -- from a floating-point type to an integer type, or
397 //
398 // -- from an integer type or unscoped enumeration type to a floating-point
399 // type, except where the source is a constant expression and the actual
400 // value after conversion will fit into the target type and will produce
401 // the original value when converted back to the original type, or
403 FloatingIntegralConversion:
404 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
405 return NK_Type_Narrowing;
406 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
407 ToType->isRealFloatingType()) {
408 if (IgnoreFloatToIntegralConversion)
409 return NK_Not_Narrowing;
410 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
411 assert(Initializer && "Unknown conversion expression");
412
413 // If it's value-dependent, we can't tell whether it's narrowing.
414 if (Initializer->isValueDependent())
416
417 if (std::optional<llvm::APSInt> IntConstantValue =
418 Initializer->getIntegerConstantExpr(Ctx)) {
419 // Convert the integer to the floating type.
420 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
421 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
422 llvm::APFloat::rmNearestTiesToEven);
423 // And back.
424 llvm::APSInt ConvertedValue = *IntConstantValue;
425 bool ignored;
426 llvm::APFloat::opStatus Status = Result.convertToInteger(
427 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
428 // If the converted-back integer has unspecified value, or if the
429 // resulting value is different, this was a narrowing conversion.
430 if (Status == llvm::APFloat::opInvalidOp ||
431 *IntConstantValue != ConvertedValue) {
432 ConstantValue = APValue(*IntConstantValue);
433 ConstantType = Initializer->getType();
435 }
436 } else {
437 // Variables are always narrowings.
439 }
440 }
441 return NK_Not_Narrowing;
442
443 // -- from long double to double or float, or from double to float, except
444 // where the source is a constant expression and the actual value after
445 // conversion is within the range of values that can be represented (even
446 // if it cannot be represented exactly), or
448 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
449 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
450 // FromType is larger than ToType.
451 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
452
453 // If it's value-dependent, we can't tell whether it's narrowing.
454 if (Initializer->isValueDependent())
456
458 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
459 ((Ctx.getLangOpts().CPlusPlus &&
460 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
461 // Constant!
462 if (Ctx.getLangOpts().C23)
463 ConstantValue = R.Val;
464 assert(ConstantValue.isFloat());
465 llvm::APFloat FloatVal = ConstantValue.getFloat();
466 // Convert the source value into the target type.
467 bool ignored;
468 llvm::APFloat Converted = FloatVal;
469 llvm::APFloat::opStatus ConvertStatus =
470 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
471 llvm::APFloat::rmNearestTiesToEven, &ignored);
472 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
473 llvm::APFloat::rmNearestTiesToEven, &ignored);
474 if (Ctx.getLangOpts().C23) {
475 if (FloatVal.isNaN() && Converted.isNaN() &&
476 !FloatVal.isSignaling() && !Converted.isSignaling()) {
477 // Quiet NaNs are considered the same value, regardless of
478 // payloads.
479 return NK_Not_Narrowing;
480 }
481 // For normal values, check exact equality.
482 if (!Converted.bitwiseIsEqual(FloatVal)) {
483 ConstantType = Initializer->getType();
485 }
486 } else {
487 // If there was no overflow, the source value is within the range of
488 // values that can be represented.
489 if (ConvertStatus & llvm::APFloat::opOverflow) {
490 ConstantType = Initializer->getType();
492 }
493 }
494 } else {
496 }
497 }
498 return NK_Not_Narrowing;
499
500 // -- from an integer type or unscoped enumeration type to an integer type
501 // that cannot represent all the values of the original type, except where
502 // (CWG2627) -- the source is a bit-field whose width w is less than that
503 // of its type (or, for an enumeration type, its underlying type) and the
504 // target type can represent all the values of a hypothetical extended
505 // integer type with width w and with the same signedness as the original
506 // type or
507 // -- the source is a constant expression and the actual value after
508 // conversion will fit into the target type and will produce the original
509 // value when converted back to the original type.
511 IntegralConversion: {
512 assert(FromType->isIntegralOrUnscopedEnumerationType());
513 assert(ToType->isIntegralOrUnscopedEnumerationType());
514 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
515 unsigned FromWidth = Ctx.getIntWidth(FromType);
516 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
517 const unsigned ToWidth = Ctx.getIntWidth(ToType);
518
519 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
520 bool ToSigned, unsigned ToWidth) {
521 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
522 !(FromSigned && !ToSigned);
523 };
524
525 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // Not all values of FromType can be represented in ToType.
529 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
530
531 bool DependentBitField = false;
532 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
533 if (BitField->getBitWidth()->isValueDependent())
534 DependentBitField = true;
535 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
536 BitFieldWidth < FromWidth) {
537 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
538 return NK_Not_Narrowing;
539
540 // The initializer will be truncated to the bit-field width
541 FromWidth = BitFieldWidth;
542 }
543 }
544
545 // If it's value-dependent, we can't tell whether it's narrowing.
546 if (Initializer->isValueDependent())
548
549 std::optional<llvm::APSInt> OptInitializerValue =
550 Initializer->getIntegerConstantExpr(Ctx);
551 if (!OptInitializerValue) {
552 // If the bit-field width was dependent, it might end up being small
553 // enough to fit in the target type (unless the target type is unsigned
554 // and the source type is signed, in which case it will never fit)
555 if (DependentBitField && !(FromSigned && !ToSigned))
557
558 // Otherwise, such a conversion is always narrowing
560 }
561 llvm::APSInt &InitializerValue = *OptInitializerValue;
562 bool Narrowing = false;
563 if (FromWidth < ToWidth) {
564 // Negative -> unsigned is narrowing. Otherwise, more bits is never
565 // narrowing.
566 if (InitializerValue.isSigned() && InitializerValue.isNegative())
567 Narrowing = true;
568 } else {
569 // Add a bit to the InitializerValue so we don't have to worry about
570 // signed vs. unsigned comparisons.
571 InitializerValue =
572 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
573 // Convert the initializer to and from the target width and signed-ness.
574 llvm::APSInt ConvertedValue = InitializerValue;
575 ConvertedValue = ConvertedValue.trunc(ToWidth);
576 ConvertedValue.setIsSigned(ToSigned);
577 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
578 ConvertedValue.setIsSigned(InitializerValue.isSigned());
579 // If the result is different, this was a narrowing conversion.
580 if (ConvertedValue != InitializerValue)
581 Narrowing = true;
582 }
583 if (Narrowing) {
584 ConstantType = Initializer->getType();
585 ConstantValue = APValue(InitializerValue);
587 }
588
589 return NK_Not_Narrowing;
590 }
591 case ICK_Complex_Real:
592 if (FromType->isComplexType() && !ToType->isComplexType())
593 return NK_Type_Narrowing;
594 return NK_Not_Narrowing;
595
597 if (Ctx.getLangOpts().C23) {
598 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
600 if (Initializer->EvaluateAsRValue(R, Ctx)) {
601 ConstantValue = R.Val;
602 assert(ConstantValue.isFloat());
603 llvm::APFloat FloatVal = ConstantValue.getFloat();
604 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
605 // value, the unqualified versions of the type of the initializer and
606 // the corresponding real type of the object declared shall be
607 // compatible.
608 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
609 ConstantType = Initializer->getType();
611 }
612 }
613 }
614 return NK_Not_Narrowing;
615 default:
616 // Other kinds of conversions are not narrowings.
617 return NK_Not_Narrowing;
618 }
619}
620
621/// dump - Print this standard conversion sequence to standard
622/// error. Useful for debugging overloading issues.
623LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
624 raw_ostream &OS = llvm::errs();
625 bool PrintedSomething = false;
626 if (First != ICK_Identity) {
628 PrintedSomething = true;
629 }
630
631 if (Second != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636
637 if (CopyConstructor) {
638 OS << " (by copy constructor)";
639 } else if (DirectBinding) {
640 OS << " (direct reference binding)";
641 } else if (ReferenceBinding) {
642 OS << " (reference binding)";
643 }
644 PrintedSomething = true;
645 }
646
647 if (Third != ICK_Identity) {
648 if (PrintedSomething) {
649 OS << " -> ";
650 }
652 PrintedSomething = true;
653 }
654
655 if (!PrintedSomething) {
656 OS << "No conversions required";
657 }
658}
659
660/// dump - Print this user-defined conversion sequence to standard
661/// error. Useful for debugging overloading issues.
663 raw_ostream &OS = llvm::errs();
664 if (Before.First || Before.Second || Before.Third) {
665 Before.dump();
666 OS << " -> ";
667 }
669 OS << '\'' << *ConversionFunction << '\'';
670 else
671 OS << "aggregate initialization";
672 if (After.First || After.Second || After.Third) {
673 OS << " -> ";
674 After.dump();
675 }
676}
677
678/// dump - Print this implicit conversion sequence to standard
679/// error. Useful for debugging overloading issues.
681 raw_ostream &OS = llvm::errs();
683 OS << "Worst list element conversion: ";
684 switch (ConversionKind) {
686 OS << "Standard conversion: ";
687 Standard.dump();
688 break;
690 OS << "User-defined conversion: ";
691 UserDefined.dump();
692 break;
694 OS << "Ellipsis conversion";
695 break;
697 OS << "Ambiguous conversion";
698 break;
699 case BadConversion:
700 OS << "Bad conversion";
701 break;
702 }
703
704 OS << "\n";
705}
706
710
712 conversions().~ConversionSet();
713}
714
715void
721
722namespace {
723 // Structure used by DeductionFailureInfo to store
724 // template argument information.
725 struct DFIArguments {
726 TemplateArgument FirstArg;
727 TemplateArgument SecondArg;
728 };
729 // Structure used by DeductionFailureInfo to store
730 // template parameter and template argument information.
731 struct DFIParamWithArguments : DFIArguments {
732 TemplateParameter Param;
733 };
734 // Structure used by DeductionFailureInfo to store template argument
735 // information and the index of the problematic call argument.
736 struct DFIDeducedMismatchArgs : DFIArguments {
737 TemplateArgumentList *TemplateArgs;
738 unsigned CallArgIndex;
739 };
740 // Structure used by DeductionFailureInfo to store information about
741 // unsatisfied constraints.
742 struct CNSInfo {
743 TemplateArgumentList *TemplateArgs;
744 ConstraintSatisfaction Satisfaction;
745 };
746}
747
748/// Convert from Sema's representation of template deduction information
749/// to the form used in overload-candidate information.
753 TemplateDeductionInfo &Info) {
755 Result.Result = static_cast<unsigned>(TDK);
756 Result.HasDiagnostic = false;
757 switch (TDK) {
764 Result.Data = nullptr;
765 break;
766
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
771 Result.Data = Info.Param.getOpaqueValue();
772 if (Info.hasSFINAEDiagnostic()) {
776 Result.HasDiagnostic = true;
777 }
778 break;
779
782 // FIXME: Should allocate from normal heap so that we can free this later.
783 auto *Saved = new (Context) DFIDeducedMismatchArgs;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Saved->TemplateArgs = Info.takeSugared();
787 Saved->CallArgIndex = Info.CallArgIndex;
788 Result.Data = Saved;
789 break;
790 }
791
793 // FIXME: Should allocate from normal heap so that we can free this later.
794 DFIArguments *Saved = new (Context) DFIArguments;
795 Saved->FirstArg = Info.FirstArg;
796 Saved->SecondArg = Info.SecondArg;
797 Result.Data = Saved;
798 break;
799 }
800
802 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
805 // FIXME: Should allocate from normal heap so that we can free this later.
806 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
807 Saved->Param = Info.Param;
808 Saved->FirstArg = Info.FirstArg;
809 Saved->SecondArg = Info.SecondArg;
810 Result.Data = Saved;
811 break;
812 }
813
815 Result.Data = Info.takeSugared();
816 if (Info.hasSFINAEDiagnostic()) {
820 Result.HasDiagnostic = true;
821 }
822 break;
823
825 CNSInfo *Saved = new (Context) CNSInfo;
826 Saved->TemplateArgs = Info.takeSugared();
827 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
828 Result.Data = Saved;
829 break;
830 }
831
835 llvm_unreachable("not a deduction failure");
836 }
837
838 return Result;
839}
840
842 switch (static_cast<TemplateDeductionResult>(Result)) {
851 break;
852
859 // FIXME: Destroy the data?
860 Data = nullptr;
861 break;
862
865 // FIXME: Destroy the template argument list?
866 Data = nullptr;
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
874 // FIXME: Destroy the template argument list?
875 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
876 Data = nullptr;
878 Diag->~PartialDiagnosticAt();
879 HasDiagnostic = false;
880 }
881 break;
882
883 // Unhandled
886 break;
887 }
888}
889
891 if (HasDiagnostic)
892 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
893 return nullptr;
894}
895
929
965
997
1029
1031 switch (static_cast<TemplateDeductionResult>(Result)) {
1034 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1035
1036 default:
1037 return std::nullopt;
1038 }
1039}
1040
1042 const FunctionDecl *Y) {
1043 if (!X || !Y)
1044 return false;
1045 if (X->getNumParams() != Y->getNumParams())
1046 return false;
1047 // FIXME: when do rewritten comparison operators
1048 // with explicit object parameters correspond?
1049 // https://cplusplus.github.io/CWG/issues/2797.html
1050 for (unsigned I = 0; I < X->getNumParams(); ++I)
1051 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1052 Y->getParamDecl(I)->getType()))
1053 return false;
1054 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1055 auto *FTY = Y->getDescribedFunctionTemplate();
1056 if (!FTY)
1057 return false;
1058 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1059 FTY->getTemplateParameters()))
1060 return false;
1061 }
1062 return true;
1063}
1064
1066 Expr *FirstOperand, FunctionDecl *EqFD) {
1067 assert(EqFD->getOverloadedOperator() ==
1068 OverloadedOperatorKind::OO_EqualEqual);
1069 // C++2a [over.match.oper]p4:
1070 // A non-template function or function template F named operator== is a
1071 // rewrite target with first operand o unless a search for the name operator!=
1072 // in the scope S from the instantiation context of the operator expression
1073 // finds a function or function template that would correspond
1074 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1075 // scope of the class type of o if F is a class member, and the namespace
1076 // scope of which F is a member otherwise. A function template specialization
1077 // named operator== is a rewrite target if its function template is a rewrite
1078 // target.
1080 OverloadedOperatorKind::OO_ExclaimEqual);
1081 if (isa<CXXMethodDecl>(EqFD)) {
1082 // If F is a class member, search scope is class type of first operand.
1083 QualType RHS = FirstOperand->getType();
1084 auto *RHSRec = RHS->getAsCXXRecordDecl();
1085 if (!RHSRec)
1086 return true;
1087 LookupResult Members(S, NotEqOp, OpLoc,
1089 S.LookupQualifiedName(Members, RHSRec);
1090 Members.suppressAccessDiagnostics();
1091 for (NamedDecl *Op : Members)
1092 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1093 return false;
1094 return true;
1095 }
1096 // Otherwise the search scope is the namespace scope of which F is a member.
1097 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1098 auto *NotEqFD = Op->getAsFunction();
1099 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1100 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1101 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1103 cast<Decl>(Op->getLexicalDeclContext())))
1104 return false;
1105 }
1106 return true;
1107}
1108
1110 OverloadedOperatorKind Op) const {
1112 return false;
1113 return Op == OO_EqualEqual || Op == OO_Spaceship;
1114}
1115
1117 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1118 auto Op = FD->getOverloadedOperator();
1119 if (!allowsReversed(Op))
1120 return false;
1121 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1122 assert(OriginalArgs.size() == 2);
1124 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1125 return false;
1126 }
1127 // Don't bother adding a reversed candidate that can never be a better
1128 // match than the non-reversed version.
1129 return FD->getNumNonObjectParams() != 2 ||
1131 FD->getParamDecl(1)->getType()) ||
1132 FD->hasAttr<EnableIfAttr>();
1133}
1134
1135void OverloadCandidateSet::destroyCandidates() {
1136 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1137 for (auto &C : i->Conversions)
1138 C.~ImplicitConversionSequence();
1139 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1140 i->DeductionFailure.Destroy();
1141 }
1142}
1143
1145 destroyCandidates();
1146 SlabAllocator.Reset();
1147 NumInlineBytesUsed = 0;
1148 Candidates.clear();
1149 Functions.clear();
1150 Kind = CSK;
1151 FirstDeferredCandidate = nullptr;
1152 DeferredCandidatesCount = 0;
1153 HasDeferredTemplateConstructors = false;
1154 ResolutionByPerfectCandidateIsDisabled = false;
1155}
1156
1157namespace {
1158 class UnbridgedCastsSet {
1159 struct Entry {
1160 Expr **Addr;
1161 Expr *Saved;
1162 };
1163 SmallVector<Entry, 2> Entries;
1164
1165 public:
1166 void save(Sema &S, Expr *&E) {
1167 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1168 Entry entry = { &E, E };
1169 Entries.push_back(entry);
1170 E = S.ObjC().stripARCUnbridgedCast(E);
1171 }
1172
1173 void restore() {
1174 for (SmallVectorImpl<Entry>::iterator
1175 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1176 *i->Addr = i->Saved;
1177 }
1178 };
1179}
1180
1181/// checkPlaceholderForOverload - Do any interesting placeholder-like
1182/// preprocessing on the given expression.
1183///
1184/// \param unbridgedCasts a collection to which to add unbridged casts;
1185/// without this, they will be immediately diagnosed as errors
1186///
1187/// Return true on unrecoverable error.
1188static bool
1190 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1191 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1192 // We can't handle overloaded expressions here because overload
1193 // resolution might reasonably tweak them.
1194 if (placeholder->getKind() == BuiltinType::Overload) return false;
1195
1196 // If the context potentially accepts unbridged ARC casts, strip
1197 // the unbridged cast and add it to the collection for later restoration.
1198 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1199 unbridgedCasts) {
1200 unbridgedCasts->save(S, E);
1201 return false;
1202 }
1203
1204 // Go ahead and check everything else.
1205 ExprResult result = S.CheckPlaceholderExpr(E);
1206 if (result.isInvalid())
1207 return true;
1208
1209 E = result.get();
1210 return false;
1211 }
1212
1213 // Nothing to do.
1214 return false;
1215}
1216
1217/// checkArgPlaceholdersForOverload - Check a set of call operands for
1218/// placeholders.
1220 UnbridgedCastsSet &unbridged) {
1221 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1222 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1223 return true;
1224
1225 return false;
1226}
1227
1229 const LookupResult &Old, NamedDecl *&Match,
1230 bool NewIsUsingDecl) {
1231 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1232 I != E; ++I) {
1233 NamedDecl *OldD = *I;
1234
1235 bool OldIsUsingDecl = false;
1236 if (isa<UsingShadowDecl>(OldD)) {
1237 OldIsUsingDecl = true;
1238
1239 // We can always introduce two using declarations into the same
1240 // context, even if they have identical signatures.
1241 if (NewIsUsingDecl) continue;
1242
1243 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1244 }
1245
1246 // A using-declaration does not conflict with another declaration
1247 // if one of them is hidden.
1248 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1249 continue;
1250
1251 // If either declaration was introduced by a using declaration,
1252 // we'll need to use slightly different rules for matching.
1253 // Essentially, these rules are the normal rules, except that
1254 // function templates hide function templates with different
1255 // return types or template parameter lists.
1256 bool UseMemberUsingDeclRules =
1257 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1258 !New->getFriendObjectKind();
1259
1260 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1261 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1262 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1264 continue;
1265 }
1266
1267 if (!isa<FunctionTemplateDecl>(OldD) &&
1268 !shouldLinkPossiblyHiddenDecl(*I, New))
1269 continue;
1270
1271 Match = *I;
1272 return OverloadKind::Match;
1273 }
1274
1275 // Builtins that have custom typechecking or have a reference should
1276 // not be overloadable or redeclarable.
1277 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1278 Match = *I;
1280 }
1281 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1282 // We can overload with these, which can show up when doing
1283 // redeclaration checks for UsingDecls.
1284 assert(Old.getLookupKind() == LookupUsingDeclName);
1285 } else if (isa<TagDecl>(OldD)) {
1286 // We can always overload with tags by hiding them.
1287 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1288 // Optimistically assume that an unresolved using decl will
1289 // overload; if it doesn't, we'll have to diagnose during
1290 // template instantiation.
1291 //
1292 // Exception: if the scope is dependent and this is not a class
1293 // member, the using declaration can only introduce an enumerator.
1294 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1295 Match = *I;
1297 }
1298 } else {
1299 // (C++ 13p1):
1300 // Only function declarations can be overloaded; object and type
1301 // declarations cannot be overloaded.
1302 Match = *I;
1304 }
1305 }
1306
1307 // C++ [temp.friend]p1:
1308 // For a friend function declaration that is not a template declaration:
1309 // -- if the name of the friend is a qualified or unqualified template-id,
1310 // [...], otherwise
1311 // -- if the name of the friend is a qualified-id and a matching
1312 // non-template function is found in the specified class or namespace,
1313 // the friend declaration refers to that function, otherwise,
1314 // -- if the name of the friend is a qualified-id and a matching function
1315 // template is found in the specified class or namespace, the friend
1316 // declaration refers to the deduced specialization of that function
1317 // template, otherwise
1318 // -- the name shall be an unqualified-id [...]
1319 // If we get here for a qualified friend declaration, we've just reached the
1320 // third bullet. If the type of the friend is dependent, skip this lookup
1321 // until instantiation.
1322 if (New->getFriendObjectKind() && New->getQualifier() &&
1323 !New->getDescribedFunctionTemplate() &&
1324 !New->getDependentSpecializationInfo() &&
1325 !New->getType()->isDependentType()) {
1326 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1327 TemplateSpecResult.addAllDecls(Old);
1328 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1329 /*QualifiedFriend*/true)) {
1330 New->setInvalidDecl();
1332 }
1333
1334 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1335 return OverloadKind::Match;
1336 }
1337
1339}
1340
1341template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1342 assert(D && "function decl should not be null");
1343 if (auto *A = D->getAttr<AttrT>())
1344 return !A->isImplicit();
1345 return false;
1346}
1347
1349 FunctionDecl *Old,
1350 bool UseMemberUsingDeclRules,
1351 bool ConsiderCudaAttrs,
1352 bool UseOverrideRules = false) {
1353 // C++ [basic.start.main]p2: This function shall not be overloaded.
1354 if (New->isMain())
1355 return false;
1356
1357 // MSVCRT user defined entry points cannot be overloaded.
1358 if (New->isMSVCRTEntryPoint())
1359 return false;
1360
1361 NamedDecl *OldDecl = Old;
1362 NamedDecl *NewDecl = New;
1364 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1365
1366 // C++ [temp.fct]p2:
1367 // A function template can be overloaded with other function templates
1368 // and with normal (non-template) functions.
1369 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1370 return true;
1371
1372 // Is the function New an overload of the function Old?
1373 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1374 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1375
1376 // Compare the signatures (C++ 1.3.10) of the two functions to
1377 // determine whether they are overloads. If we find any mismatch
1378 // in the signature, they are overloads.
1379
1380 // If either of these functions is a K&R-style function (no
1381 // prototype), then we consider them to have matching signatures.
1382 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1384 return false;
1385
1386 const auto *OldType = cast<FunctionProtoType>(OldQType);
1387 const auto *NewType = cast<FunctionProtoType>(NewQType);
1388
1389 // The signature of a function includes the types of its
1390 // parameters (C++ 1.3.10), which includes the presence or absence
1391 // of the ellipsis; see C++ DR 357).
1392 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1393 return true;
1394
1395 // For member-like friends, the enclosing class is part of the signature.
1396 if ((New->isMemberLikeConstrainedFriend() ||
1398 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1399 return true;
1400
1401 // Compare the parameter lists.
1402 // This can only be done once we have establish that friend functions
1403 // inhabit the same context, otherwise we might tried to instantiate
1404 // references to non-instantiated entities during constraint substitution.
1405 // GH78101.
1406 if (NewTemplate) {
1407 OldDecl = OldTemplate;
1408 NewDecl = NewTemplate;
1409 // C++ [temp.over.link]p4:
1410 // The signature of a function template consists of its function
1411 // signature, its return type and its template parameter list. The names
1412 // of the template parameters are significant only for establishing the
1413 // relationship between the template parameters and the rest of the
1414 // signature.
1415 //
1416 // We check the return type and template parameter lists for function
1417 // templates first; the remaining checks follow.
1418 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1419 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1420 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1421 bool SameReturnType = SemaRef.Context.hasSameType(
1422 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1423 // FIXME(GH58571): Match template parameter list even for non-constrained
1424 // template heads. This currently ensures that the code prior to C++20 is
1425 // not newly broken.
1426 bool ConstraintsInTemplateHead =
1429 // C++ [namespace.udecl]p11:
1430 // The set of declarations named by a using-declarator that inhabits a
1431 // class C does not include member functions and member function
1432 // templates of a base class that "correspond" to (and thus would
1433 // conflict with) a declaration of a function or function template in
1434 // C.
1435 // Comparing return types is not required for the "correspond" check to
1436 // decide whether a member introduced by a shadow declaration is hidden.
1437 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1438 !SameTemplateParameterList)
1439 return true;
1440 if (!UseMemberUsingDeclRules &&
1441 (!SameTemplateParameterList || !SameReturnType))
1442 return true;
1443 }
1444
1445 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1446 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1447
1448 int OldParamsOffset = 0;
1449 int NewParamsOffset = 0;
1450
1451 // When determining if a method is an overload from a base class, act as if
1452 // the implicit object parameter are of the same type.
1453
1454 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1456 auto ThisType = M->getFunctionObjectParameterReferenceType();
1457 if (ThisType.isConstQualified())
1458 Q.removeConst();
1459 return Q;
1460 }
1461
1462 // We do not allow overloading based off of '__restrict'.
1463 Q.removeRestrict();
1464
1465 // We may not have applied the implicit const for a constexpr member
1466 // function yet (because we haven't yet resolved whether this is a static
1467 // or non-static member function). Add it now, on the assumption that this
1468 // is a redeclaration of OldMethod.
1469 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1470 (M->isConstexpr() || M->isConsteval()) &&
1471 !isa<CXXConstructorDecl>(NewMethod))
1472 Q.addConst();
1473 return Q;
1474 };
1475
1476 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1477 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1478 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1479
1480 if (OldMethod->isExplicitObjectMemberFunction()) {
1481 BS.Quals.removeVolatile();
1482 DS.Quals.removeVolatile();
1483 }
1484
1485 return BS.Quals == DS.Quals;
1486 };
1487
1488 auto CompareType = [&](QualType Base, QualType D) {
1489 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1490 auto DS = D.getNonReferenceType().getCanonicalType().split();
1491
1492 if (!AreQualifiersEqual(BS, DS))
1493 return false;
1494
1495 if (OldMethod->isImplicitObjectMemberFunction() &&
1496 OldMethod->getParent() != NewMethod->getParent()) {
1497 CanQualType ParentType =
1498 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1499 if (ParentType.getTypePtr() != BS.Ty)
1500 return false;
1501 BS.Ty = DS.Ty;
1502 }
1503
1504 // FIXME: should we ignore some type attributes here?
1505 if (BS.Ty != DS.Ty)
1506 return false;
1507
1508 if (Base->isLValueReferenceType())
1509 return D->isLValueReferenceType();
1510 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1511 };
1512
1513 // If the function is a class member, its signature includes the
1514 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1515 auto DiagnoseInconsistentRefQualifiers = [&]() {
1516 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1517 return false;
1518 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1519 return false;
1520 if (OldMethod->isExplicitObjectMemberFunction() ||
1521 NewMethod->isExplicitObjectMemberFunction())
1522 return false;
1523 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1524 NewMethod->getRefQualifier() == RQ_None)) {
1525 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1526 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1527 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1528 return true;
1529 }
1530 return false;
1531 };
1532
1533 // We look at the parameters first, as it is the common case.
1534 // However we should not emit diagnostic before checking
1535 // the overloads do not differ by constraints or other discriminant.
1536 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1537 bool HaveInconsistentQualifiers = false;
1538
1539 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1540 OldParamsOffset++;
1541 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1542 NewParamsOffset++;
1543
1544 if (OldType->getNumParams() - OldParamsOffset !=
1545 NewType->getNumParams() - NewParamsOffset ||
1547 {OldType->param_type_begin() + OldParamsOffset,
1548 OldType->param_type_end()},
1549 {NewType->param_type_begin() + NewParamsOffset,
1550 NewType->param_type_end()},
1551 nullptr)) {
1552 return true;
1553 }
1554
1555 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1556 !NewMethod->isStatic()) {
1557 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1558 const CXXMethodDecl *New) {
1559 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1560 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1561
1562 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1563 return F->getRefQualifier() == RQ_None &&
1564 !F->isExplicitObjectMemberFunction();
1565 };
1566
1567 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1568 CompareType(OldObjectType.getNonReferenceType(),
1569 NewObjectType.getNonReferenceType()))
1570 return true;
1571 return CompareType(OldObjectType, NewObjectType);
1572 }(OldMethod, NewMethod);
1573
1574 if (!HaveCorrespondingObjectParameters) {
1575 ShouldDiagnoseInconsistentRefQualifiers = true;
1576 // CWG2554
1577 // and, if at least one is an explicit object member function, ignoring
1578 // object parameters
1579 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1580 !OldMethod->isExplicitObjectMemberFunction()))
1581 HaveInconsistentQualifiers = true;
1582 }
1583 }
1584
1585 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1586 NewMethod->isImplicitObjectMemberFunction())
1587 ShouldDiagnoseInconsistentRefQualifiers = true;
1588
1589 if (!UseOverrideRules &&
1590 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1591 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1592 OldRC = Old->getTrailingRequiresClause();
1593 if (!NewRC != !OldRC)
1594 return true;
1595 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1596 return true;
1597 if (NewRC &&
1598 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1599 NewDecl, NewRC.ConstraintExpr))
1600 return true;
1601 }
1602
1603 // Though pass_object_size is placed on parameters and takes an argument, we
1604 // consider it to be a function-level modifier for the sake of function
1605 // identity. Either the function has one or more parameters with
1606 // pass_object_size or it doesn't.
1609 return true;
1610
1611 // enable_if attributes are an order-sensitive part of the signature.
1613 NewI = New->specific_attr_begin<EnableIfAttr>(),
1614 NewE = New->specific_attr_end<EnableIfAttr>(),
1615 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1616 OldE = Old->specific_attr_end<EnableIfAttr>();
1617 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1618 if (NewI == NewE || OldI == OldE)
1619 return true;
1620 llvm::FoldingSetNodeID NewID, OldID;
1621 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1622 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1623 if (NewID != OldID)
1624 return true;
1625 }
1626
1627 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1628 DiagnoseInconsistentRefQualifiers()) ||
1629 HaveInconsistentQualifiers)
1630 return true;
1631
1632 // At this point, it is known that the two functions have the same signature.
1633 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1634 // Don't allow overloading of destructors. (In theory we could, but it
1635 // would be a giant change to clang.)
1637 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1638 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1639 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1640 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1641 "Unexpected invalid target.");
1642
1643 // Allow overloading of functions with same signature and different CUDA
1644 // target attributes.
1645 if (NewTarget != OldTarget) {
1646 // Special case: non-constexpr function is allowed to override
1647 // constexpr virtual function
1648 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1649 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1654 return false;
1655 }
1656 return true;
1657 }
1658 }
1659 }
1660 }
1661
1662 // The signatures match; this is not an overload.
1663 return false;
1664}
1665
1667 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1668 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1669 ConsiderCudaAttrs);
1670}
1671
1673 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1674 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1675 /*UseMemberUsingDeclRules=*/false,
1676 /*ConsiderCudaAttrs=*/true,
1677 /*UseOverrideRules=*/true);
1678}
1679
1680/// Tries a user-defined conversion from From to ToType.
1681///
1682/// Produces an implicit conversion sequence for when a standard conversion
1683/// is not an option. See TryImplicitConversion for more information.
1686 bool SuppressUserConversions,
1687 AllowedExplicit AllowExplicit,
1688 bool InOverloadResolution,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion,
1691 bool AllowObjCConversionOnExplicit) {
1693
1694 if (SuppressUserConversions) {
1695 // We're not in the case above, so there is no conversion that
1696 // we can perform.
1698 return ICS;
1699 }
1700
1701 // Attempt user-defined conversion.
1702 OverloadCandidateSet Conversions(From->getExprLoc(),
1704 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1705 Conversions, AllowExplicit,
1706 AllowObjCConversionOnExplicit)) {
1707 case OR_Success:
1708 case OR_Deleted:
1709 ICS.setUserDefined();
1710 // C++ [over.ics.user]p4:
1711 // A conversion of an expression of class type to the same class
1712 // type is given Exact Match rank, and a conversion of an
1713 // expression of class type to a base class of that type is
1714 // given Conversion rank, in spite of the fact that a copy
1715 // constructor (i.e., a user-defined conversion function) is
1716 // called for those cases.
1718 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1719 QualType FromType;
1720 SourceLocation FromLoc;
1721 // C++11 [over.ics.list]p6, per DR2137:
1722 // C++17 [over.ics.list]p6:
1723 // If C is not an initializer-list constructor and the initializer list
1724 // has a single element of type cv U, where U is X or a class derived
1725 // from X, the implicit conversion sequence has Exact Match rank if U is
1726 // X, or Conversion rank if U is derived from X.
1727 bool FromListInit = false;
1728 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1729 InitList && InitList->getNumInits() == 1 &&
1731 const Expr *SingleInit = InitList->getInit(0);
1732 FromType = SingleInit->getType();
1733 FromLoc = SingleInit->getBeginLoc();
1734 FromListInit = true;
1735 } else {
1736 FromType = From->getType();
1737 FromLoc = From->getBeginLoc();
1738 }
1739 QualType FromCanon =
1741 QualType ToCanon
1743 if ((FromCanon == ToCanon ||
1744 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1745 // Turn this into a "standard" conversion sequence, so that it
1746 // gets ranked with standard conversion sequences.
1748 ICS.setStandard();
1750 ICS.Standard.setFromType(FromType);
1751 ICS.Standard.setAllToTypes(ToType);
1752 ICS.Standard.FromBracedInitList = FromListInit;
1755 if (ToCanon != FromCanon)
1757 }
1758 }
1759 break;
1760
1761 case OR_Ambiguous:
1762 ICS.setAmbiguous();
1763 ICS.Ambiguous.setFromType(From->getType());
1764 ICS.Ambiguous.setToType(ToType);
1765 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1766 Cand != Conversions.end(); ++Cand)
1767 if (Cand->Best)
1768 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1769 break;
1770
1771 // Fall through.
1774 break;
1775 }
1776
1777 return ICS;
1778}
1779
1780/// TryImplicitConversion - Attempt to perform an implicit conversion
1781/// from the given expression (Expr) to the given type (ToType). This
1782/// function returns an implicit conversion sequence that can be used
1783/// to perform the initialization. Given
1784///
1785/// void f(float f);
1786/// void g(int i) { f(i); }
1787///
1788/// this routine would produce an implicit conversion sequence to
1789/// describe the initialization of f from i, which will be a standard
1790/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1791/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1792//
1793/// Note that this routine only determines how the conversion can be
1794/// performed; it does not actually perform the conversion. As such,
1795/// it will not produce any diagnostics if no conversion is available,
1796/// but will instead return an implicit conversion sequence of kind
1797/// "BadConversion".
1798///
1799/// If @p SuppressUserConversions, then user-defined conversions are
1800/// not permitted.
1801/// If @p AllowExplicit, then explicit user-defined conversions are
1802/// permitted.
1803///
1804/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1805/// writeback conversion, which allows __autoreleasing id* parameters to
1806/// be initialized with __strong id* or __weak id* arguments.
1807static ImplicitConversionSequence
1809 bool SuppressUserConversions,
1810 AllowedExplicit AllowExplicit,
1811 bool InOverloadResolution,
1812 bool CStyle,
1813 bool AllowObjCWritebackConversion,
1814 bool AllowObjCConversionOnExplicit) {
1816 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1817 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1818 ICS.setStandard();
1819 return ICS;
1820 }
1821
1822 if (!S.getLangOpts().CPlusPlus) {
1824 return ICS;
1825 }
1826
1827 // C++ [over.ics.user]p4:
1828 // A conversion of an expression of class type to the same class
1829 // type is given Exact Match rank, and a conversion of an
1830 // expression of class type to a base class of that type is
1831 // given Conversion rank, in spite of the fact that a copy/move
1832 // constructor (i.e., a user-defined conversion function) is
1833 // called for those cases.
1834 QualType FromType = From->getType();
1835 if (ToType->isRecordType() &&
1836 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1837 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1838 ICS.setStandard();
1840 ICS.Standard.setFromType(FromType);
1841 ICS.Standard.setAllToTypes(ToType);
1842
1843 // We don't actually check at this point whether there is a valid
1844 // copy/move constructor, since overloading just assumes that it
1845 // exists. When we actually perform initialization, we'll find the
1846 // appropriate constructor to copy the returned object, if needed.
1847 ICS.Standard.CopyConstructor = nullptr;
1848
1849 // In HLSL, a conversion of an expression of class type to the same class
1850 // type needs implicit LvaluetoRvalue conversion.
1851 if (S.getLangOpts().HLSL)
1853
1854 // Determine whether this is considered a derived-to-base conversion.
1855 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1857
1858 return ICS;
1859 }
1860
1861 if (S.getLangOpts().HLSL) {
1862 // Handle conversion of the HLSL resource types.
1863 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1864 if (FromTy->isHLSLAttributedResourceType()) {
1865 // Attributed resource types can convert to other attributed
1866 // resource types with the same attributes and contained types,
1867 // or to __hlsl_resource_t without any attributes.
1868 bool CanConvert = false;
1869 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1870 if (ToTy->isHLSLAttributedResourceType()) {
1871 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1872 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1873 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1874 FromResType->getWrappedType()) &&
1875 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1876 FromResType->getContainedType()) &&
1877 ToResType->getAttrs() == FromResType->getAttrs())
1878 CanConvert = true;
1879 } else if (ToTy->isHLSLResourceType()) {
1880 CanConvert = true;
1881 }
1882 if (CanConvert) {
1883 ICS.setStandard();
1885 ICS.Standard.setFromType(FromType);
1886 ICS.Standard.setAllToTypes(ToType);
1887 return ICS;
1888 }
1889 }
1890 }
1891
1892 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1893 AllowExplicit, InOverloadResolution, CStyle,
1894 AllowObjCWritebackConversion,
1895 AllowObjCConversionOnExplicit);
1896}
1897
1898ImplicitConversionSequence
1900 bool SuppressUserConversions,
1901 AllowedExplicit AllowExplicit,
1902 bool InOverloadResolution,
1903 bool CStyle,
1904 bool AllowObjCWritebackConversion) {
1905 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1906 AllowExplicit, InOverloadResolution, CStyle,
1907 AllowObjCWritebackConversion,
1908 /*AllowObjCConversionOnExplicit=*/false);
1909}
1910
1912 AssignmentAction Action,
1913 bool AllowExplicit) {
1914 if (checkPlaceholderForOverload(*this, From))
1915 return ExprError();
1916
1917 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1918 bool AllowObjCWritebackConversion =
1919 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1920 Action == AssignmentAction::Sending);
1921 if (getLangOpts().ObjC)
1922 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1923 From->getType(), From);
1925 *this, From, ToType,
1926 /*SuppressUserConversions=*/false,
1927 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1928 /*InOverloadResolution=*/false,
1929 /*CStyle=*/false, AllowObjCWritebackConversion,
1930 /*AllowObjCConversionOnExplicit=*/false);
1931 return PerformImplicitConversion(From, ToType, ICS, Action);
1932}
1933
1935 QualType &ResultTy) const {
1936 bool Changed = IsFunctionConversion(FromType, ToType);
1937 if (Changed)
1938 ResultTy = ToType;
1939 return Changed;
1940}
1941
1942bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1943 if (Context.hasSameUnqualifiedType(FromType, ToType))
1944 return false;
1945
1946 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1947 // or F(t noexcept) -> F(t)
1948 // where F adds one of the following at most once:
1949 // - a pointer
1950 // - a member pointer
1951 // - a block pointer
1952 // Changes here need matching changes in FindCompositePointerType.
1953 CanQualType CanTo = Context.getCanonicalType(ToType);
1954 CanQualType CanFrom = Context.getCanonicalType(FromType);
1955 Type::TypeClass TyClass = CanTo->getTypeClass();
1956 if (TyClass != CanFrom->getTypeClass()) return false;
1957 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1958 if (TyClass == Type::Pointer) {
1959 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1960 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1961 } else if (TyClass == Type::BlockPointer) {
1962 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1963 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1964 } else if (TyClass == Type::MemberPointer) {
1965 auto ToMPT = CanTo.castAs<MemberPointerType>();
1966 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1967 // A function pointer conversion cannot change the class of the function.
1968 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1969 FromMPT->getMostRecentCXXRecordDecl()))
1970 return false;
1971 CanTo = ToMPT->getPointeeType();
1972 CanFrom = FromMPT->getPointeeType();
1973 } else {
1974 return false;
1975 }
1976
1977 TyClass = CanTo->getTypeClass();
1978 if (TyClass != CanFrom->getTypeClass()) return false;
1979 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1980 return false;
1981 }
1982
1983 const auto *FromFn = cast<FunctionType>(CanFrom);
1984 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1985
1986 const auto *ToFn = cast<FunctionType>(CanTo);
1987 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1988
1989 bool Changed = false;
1990
1991 // Drop 'noreturn' if not present in target type.
1992 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1993 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1994 Changed = true;
1995 }
1996
1997 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1998 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1999
2000 if (FromFPT && ToFPT) {
2001 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2002 QualType NewTy = Context.getFunctionType(
2003 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2004 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2005 ToFPT->hasCFIUncheckedCallee()));
2006 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2007 FromFn = FromFPT;
2008 Changed = true;
2009 }
2010 }
2011
2012 // Drop 'noexcept' if not present in target type.
2013 if (FromFPT && ToFPT) {
2014 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2015 FromFn = cast<FunctionType>(
2016 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2017 EST_None)
2018 .getTypePtr());
2019 Changed = true;
2020 }
2021
2022 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2023 // only if the ExtParameterInfo lists of the two function prototypes can be
2024 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2026 bool CanUseToFPT, CanUseFromFPT;
2027 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2028 CanUseFromFPT, NewParamInfos) &&
2029 CanUseToFPT && !CanUseFromFPT) {
2030 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2031 ExtInfo.ExtParameterInfos =
2032 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2033 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2034 FromFPT->getParamTypes(), ExtInfo);
2035 FromFn = QT->getAs<FunctionType>();
2036 Changed = true;
2037 }
2038
2039 if (Context.hasAnyFunctionEffects()) {
2040 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2041
2042 // Transparently add/drop effects; here we are concerned with
2043 // language rules/canonicalization. Adding/dropping effects is a warning.
2044 const auto FromFX = FromFPT->getFunctionEffects();
2045 const auto ToFX = ToFPT->getFunctionEffects();
2046 if (FromFX != ToFX) {
2047 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2048 ExtInfo.FunctionEffects = ToFX;
2049 QualType QT = Context.getFunctionType(
2050 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2051 FromFn = QT->getAs<FunctionType>();
2052 Changed = true;
2053 }
2054 }
2055 }
2056
2057 if (!Changed)
2058 return false;
2059
2060 assert(QualType(FromFn, 0).isCanonical());
2061 if (QualType(FromFn, 0) != CanTo) return false;
2062
2063 return true;
2064}
2065
2066/// Determine whether the conversion from FromType to ToType is a valid
2067/// floating point conversion.
2068///
2069static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2070 QualType ToType) {
2071 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2072 return false;
2073 // FIXME: disable conversions between long double, __ibm128 and __float128
2074 // if their representation is different until there is back end support
2075 // We of course allow this conversion if long double is really double.
2076
2077 // Conversions between bfloat16 and float16 are currently not supported.
2078 if ((FromType->isBFloat16Type() &&
2079 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2080 (ToType->isBFloat16Type() &&
2081 (FromType->isFloat16Type() || FromType->isHalfType())))
2082 return false;
2083
2084 // Conversions between IEEE-quad and IBM-extended semantics are not
2085 // permitted.
2086 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2087 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2088 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2089 &ToSem == &llvm::APFloat::IEEEquad()) ||
2090 (&FromSem == &llvm::APFloat::IEEEquad() &&
2091 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2092 return false;
2093 return true;
2094}
2095
2097 QualType ToType,
2099 Expr *From) {
2100 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2101 return true;
2102
2103 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2105 return true;
2106 }
2107
2108 if (IsFloatingPointConversion(S, FromType, ToType)) {
2110 return true;
2111 }
2112
2113 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2115 return true;
2116 }
2117
2118 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2120 ToType->isRealFloatingType())) {
2122 return true;
2123 }
2124
2125 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2127 return true;
2128 }
2129
2130 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2131 ToType->isIntegralType(S.Context)) {
2133 return true;
2134 }
2135
2136 return false;
2137}
2138
2139/// Determine whether the conversion from FromType to ToType is a valid
2140/// matrix conversion.
2141///
2142/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2143/// conversion.
2144static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2146 ImplicitConversionKind &ElConv, Expr *From,
2147 bool InOverloadResolution, bool CStyle) {
2148 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2149 if (!S.getLangOpts().HLSL)
2150 return false;
2151
2152 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2153 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2154
2155 // If both arguments are matrix, handle possible matrix truncation and
2156 // element conversion.
2157 if (ToMatrixType && FromMatrixType) {
2158 unsigned FromCols = FromMatrixType->getNumColumns();
2159 unsigned ToCols = ToMatrixType->getNumColumns();
2160 if (FromCols < ToCols)
2161 return false;
2162
2163 unsigned FromRows = FromMatrixType->getNumRows();
2164 unsigned ToRows = ToMatrixType->getNumRows();
2165 if (FromRows < ToRows)
2166 return false;
2167
2168 if (FromRows == ToRows && FromCols == ToCols)
2169 ElConv = ICK_Identity;
2170 else
2172
2173 QualType FromElTy = FromMatrixType->getElementType();
2174 QualType ToElTy = ToMatrixType->getElementType();
2175 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2176 return true;
2177 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2178 }
2179
2180 // Matrix splat from any arithmetic type to a matrix.
2181 if (ToMatrixType && FromType->isArithmeticType()) {
2182 ElConv = ICK_HLSL_Matrix_Splat;
2183 QualType ToElTy = ToMatrixType->getElementType();
2184 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2185 }
2186 if (FromMatrixType && !ToMatrixType) {
2188 QualType FromElTy = FromMatrixType->getElementType();
2189 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2190 return true;
2191 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2192 }
2193
2194 return false;
2195}
2196
2197/// Determine whether the conversion from FromType to ToType is a valid
2198/// vector conversion.
2199///
2200/// \param ICK Will be set to the vector conversion kind, if this is a vector
2201/// conversion.
2202static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2204 ImplicitConversionKind &ElConv, Expr *From,
2205 bool InOverloadResolution, bool CStyle) {
2206 // We need at least one of these types to be a vector type to have a vector
2207 // conversion.
2208 if (!ToType->isVectorType() && !FromType->isVectorType())
2209 return false;
2210
2211 // Identical types require no conversions.
2212 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2213 return false;
2214
2215 // HLSL allows implicit truncation of vector types.
2216 if (S.getLangOpts().HLSL) {
2217 auto *ToExtType = ToType->getAs<ExtVectorType>();
2218 auto *FromExtType = FromType->getAs<ExtVectorType>();
2219
2220 // If both arguments are vectors, handle possible vector truncation and
2221 // element conversion.
2222 if (ToExtType && FromExtType) {
2223 unsigned FromElts = FromExtType->getNumElements();
2224 unsigned ToElts = ToExtType->getNumElements();
2225 if (FromElts < ToElts)
2226 return false;
2227 if (FromElts == ToElts)
2228 ElConv = ICK_Identity;
2229 else
2231
2232 QualType FromElTy = FromExtType->getElementType();
2233 QualType ToElTy = ToExtType->getElementType();
2234 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2235 return true;
2236 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2237 }
2238 if (FromExtType && !ToExtType) {
2240 QualType FromElTy = FromExtType->getElementType();
2241 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2242 return true;
2243 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2244 }
2245 // Fallthrough for the case where ToType is a vector and FromType is not.
2246 }
2247
2248 // There are no conversions between extended vector types, only identity.
2249 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2250 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2251 // Implicit conversions require the same number of elements.
2252 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2253 return false;
2254
2255 // Permit implicit conversions from integral values to boolean vectors.
2256 if (ToType->isExtVectorBoolType() &&
2257 FromExtType->getElementType()->isIntegerType()) {
2259 return true;
2260 }
2261 // There are no other conversions between extended vector types.
2262 return false;
2263 }
2264
2265 // Vector splat from any arithmetic type to a vector.
2266 if (FromType->isArithmeticType()) {
2267 if (S.getLangOpts().HLSL) {
2268 ElConv = ICK_HLSL_Vector_Splat;
2269 QualType ToElTy = ToExtType->getElementType();
2270 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2271 From);
2272 }
2273 ICK = ICK_Vector_Splat;
2274 return true;
2275 }
2276 }
2277
2278 if (ToType->isSVESizelessBuiltinType() ||
2279 FromType->isSVESizelessBuiltinType())
2280 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2281 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2283 return true;
2284 }
2285
2286 if (ToType->isRVVSizelessBuiltinType() ||
2287 FromType->isRVVSizelessBuiltinType())
2288 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2289 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2291 return true;
2292 }
2293
2294 // We can perform the conversion between vector types in the following cases:
2295 // 1)vector types are equivalent AltiVec and GCC vector types
2296 // 2)lax vector conversions are permitted and the vector types are of the
2297 // same size
2298 // 3)the destination type does not have the ARM MVE strict-polymorphism
2299 // attribute, which inhibits lax vector conversion for overload resolution
2300 // only
2301 if (ToType->isVectorType() && FromType->isVectorType()) {
2302 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2303 (S.isLaxVectorConversion(FromType, ToType) &&
2304 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2305 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2306 S.isLaxVectorConversion(FromType, ToType) &&
2307 S.anyAltivecTypes(FromType, ToType) &&
2308 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2309 !InOverloadResolution && !CStyle) {
2310 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2311 << FromType << ToType;
2312 }
2314 return true;
2315 }
2316 }
2317
2318 return false;
2319}
2320
2321static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2322 bool InOverloadResolution,
2323 StandardConversionSequence &SCS,
2324 bool CStyle);
2325
2326static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2327 QualType ToType,
2328 bool InOverloadResolution,
2329 StandardConversionSequence &SCS,
2330 bool CStyle);
2331
2332/// IsStandardConversion - Determines whether there is a standard
2333/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2334/// expression From to the type ToType. Standard conversion sequences
2335/// only consider non-class types; for conversions that involve class
2336/// types, use TryImplicitConversion. If a conversion exists, SCS will
2337/// contain the standard conversion sequence required to perform this
2338/// conversion and this routine will return true. Otherwise, this
2339/// routine will return false and the value of SCS is unspecified.
2340static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2341 bool InOverloadResolution,
2343 bool CStyle,
2344 bool AllowObjCWritebackConversion) {
2345 QualType FromType = From->getType();
2346
2347 // Standard conversions (C++ [conv])
2349 SCS.IncompatibleObjC = false;
2350 SCS.setFromType(FromType);
2351 SCS.CopyConstructor = nullptr;
2352
2353 // There are no standard conversions for class types in C++, so
2354 // abort early. When overloading in C, however, we do permit them.
2355 if (S.getLangOpts().CPlusPlus &&
2356 (FromType->isRecordType() || ToType->isRecordType()))
2357 return false;
2358
2359 // The first conversion can be an lvalue-to-rvalue conversion,
2360 // array-to-pointer conversion, or function-to-pointer conversion
2361 // (C++ 4p1).
2362
2363 if (FromType == S.Context.OverloadTy) {
2364 DeclAccessPair AccessPair;
2365 if (FunctionDecl *Fn
2366 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2367 AccessPair)) {
2368 // We were able to resolve the address of the overloaded function,
2369 // so we can convert to the type of that function.
2370 FromType = Fn->getType();
2371 SCS.setFromType(FromType);
2372
2373 // we can sometimes resolve &foo<int> regardless of ToType, so check
2374 // if the type matches (identity) or we are converting to bool
2376 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2377 // if the function type matches except for [[noreturn]], it's ok
2378 if (!S.IsFunctionConversion(FromType,
2380 // otherwise, only a boolean conversion is standard
2381 if (!ToType->isBooleanType())
2382 return false;
2383 }
2384
2385 // Check if the "from" expression is taking the address of an overloaded
2386 // function and recompute the FromType accordingly. Take advantage of the
2387 // fact that non-static member functions *must* have such an address-of
2388 // expression.
2389 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2390 if (Method && !Method->isStatic() &&
2391 !Method->isExplicitObjectMemberFunction()) {
2392 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2393 "Non-unary operator on non-static member address");
2394 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2395 == UO_AddrOf &&
2396 "Non-address-of operator on non-static member address");
2397 FromType = S.Context.getMemberPointerType(
2398 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2399 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2400 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2401 UO_AddrOf &&
2402 "Non-address-of operator for overloaded function expression");
2403 FromType = S.Context.getPointerType(FromType);
2404 }
2405 } else {
2406 return false;
2407 }
2408 }
2409
2410 bool argIsLValue = From->isGLValue();
2411 // To handle conversion from ArrayParameterType to ConstantArrayType
2412 // this block must be above the one below because Array parameters
2413 // do not decay and when handling HLSLOutArgExprs and
2414 // the From expression is an LValue.
2415 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2416 ToType->isConstantArrayType()) {
2417 // HLSL constant array parameters do not decay, so if the argument is a
2418 // constant array and the parameter is an ArrayParameterType we have special
2419 // handling here.
2420 if (ToType->isArrayParameterType()) {
2421 FromType = S.Context.getArrayParameterType(FromType);
2422 } else if (FromType->isArrayParameterType()) {
2423 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2424 FromType = APT->getConstantArrayType(S.Context);
2425 }
2426
2428
2429 // Don't consider qualifiers, which include things like address spaces
2430 if (FromType.getCanonicalType().getUnqualifiedType() !=
2432 return false;
2433
2434 SCS.setAllToTypes(ToType);
2435 return true;
2436 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2437 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2438 // Lvalue-to-rvalue conversion (C++11 4.1):
2439 // A glvalue (3.10) of a non-function, non-array type T can
2440 // be converted to a prvalue.
2441
2443
2444 // C11 6.3.2.1p2:
2445 // ... if the lvalue has atomic type, the value has the non-atomic version
2446 // of the type of the lvalue ...
2447 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2448 FromType = Atomic->getValueType();
2449
2450 // If T is a non-class type, the type of the rvalue is the
2451 // cv-unqualified version of T. Otherwise, the type of the rvalue
2452 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2453 // just strip the qualifiers because they don't matter.
2454 FromType = FromType.getUnqualifiedType();
2455 } else if (FromType->isArrayType()) {
2456 // Array-to-pointer conversion (C++ 4.2)
2458
2459 // An lvalue or rvalue of type "array of N T" or "array of unknown
2460 // bound of T" can be converted to an rvalue of type "pointer to
2461 // T" (C++ 4.2p1).
2462 FromType = S.Context.getArrayDecayedType(FromType);
2463
2464 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2465 // This conversion is deprecated in C++03 (D.4)
2467
2468 // For the purpose of ranking in overload resolution
2469 // (13.3.3.1.1), this conversion is considered an
2470 // array-to-pointer conversion followed by a qualification
2471 // conversion (4.4). (C++ 4.2p2)
2472 SCS.Second = ICK_Identity;
2475 SCS.setAllToTypes(FromType);
2476 return true;
2477 }
2478 } else if (FromType->isFunctionType() && argIsLValue) {
2479 // Function-to-pointer conversion (C++ 4.3).
2481
2482 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2483 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2485 return false;
2486
2487 // An lvalue of function type T can be converted to an rvalue of
2488 // type "pointer to T." The result is a pointer to the
2489 // function. (C++ 4.3p1).
2490 FromType = S.Context.getPointerType(FromType);
2491 } else {
2492 // We don't require any conversions for the first step.
2493 SCS.First = ICK_Identity;
2494 }
2495 SCS.setToType(0, FromType);
2496
2497 // The second conversion can be an integral promotion, floating
2498 // point promotion, integral conversion, floating point conversion,
2499 // floating-integral conversion, pointer conversion,
2500 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2501 // For overloading in C, this can also be a "compatible-type"
2502 // conversion.
2503 bool IncompatibleObjC = false;
2505 ImplicitConversionKind DimensionICK = ICK_Identity;
2506 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2507 // The unqualified versions of the types are the same: there's no
2508 // conversion to do.
2509 SCS.Second = ICK_Identity;
2510 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2511 // Integral promotion (C++ 4.5).
2513 FromType = ToType.getUnqualifiedType();
2514 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2515 // Floating point promotion (C++ 4.6).
2517 FromType = ToType.getUnqualifiedType();
2518 } else if (S.IsComplexPromotion(FromType, ToType)) {
2519 // Complex promotion (Clang extension)
2521 FromType = ToType.getUnqualifiedType();
2522 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2523 // OverflowBehaviorType promotions
2525 FromType = ToType.getUnqualifiedType();
2526 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2527 // OverflowBehaviorType conversions
2529 FromType = ToType.getUnqualifiedType();
2530 } else if (ToType->isBooleanType() &&
2531 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2532 FromType->isBlockPointerType() ||
2533 FromType->isMemberPointerType())) {
2534 // Boolean conversions (C++ 4.12).
2536 FromType = S.Context.BoolTy;
2537 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2538 ToType->isIntegralType(S.Context)) {
2539 // Integral conversions (C++ 4.7).
2541 FromType = ToType.getUnqualifiedType();
2542 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2543 // Complex conversions (C99 6.3.1.6)
2545 FromType = ToType.getUnqualifiedType();
2546 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2547 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2548 // Complex-real conversions (C99 6.3.1.7)
2550 FromType = ToType.getUnqualifiedType();
2551 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2552 // Floating point conversions (C++ 4.8).
2554 FromType = ToType.getUnqualifiedType();
2555 } else if ((FromType->isRealFloatingType() &&
2556 ToType->isIntegralType(S.Context)) ||
2558 ToType->isRealFloatingType())) {
2559
2560 // Floating-integral conversions (C++ 4.9).
2562 FromType = ToType.getUnqualifiedType();
2563 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2565 } else if (AllowObjCWritebackConversion &&
2566 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2568 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2569 FromType, IncompatibleObjC)) {
2570 // Pointer conversions (C++ 4.10).
2572 SCS.IncompatibleObjC = IncompatibleObjC;
2573 FromType = FromType.getUnqualifiedType();
2574 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2575 InOverloadResolution, FromType)) {
2576 // Pointer to member conversions (4.11).
2578 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2579 From, InOverloadResolution, CStyle)) {
2580 SCS.Second = SecondICK;
2581 SCS.Dimension = DimensionICK;
2582 FromType = ToType.getUnqualifiedType();
2583 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2584 From, InOverloadResolution, CStyle)) {
2585 SCS.Second = SecondICK;
2586 SCS.Dimension = DimensionICK;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (!S.getLangOpts().CPlusPlus &&
2589 S.Context.typesAreCompatible(ToType, FromType)) {
2590 // Compatible conversions (Clang extension for C function overloading)
2592 FromType = ToType.getUnqualifiedType();
2594 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2596 FromType = ToType;
2597 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2598 CStyle)) {
2599 // tryAtomicConversion has updated the standard conversion sequence
2600 // appropriately.
2601 return true;
2603 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2604 return true;
2605 } else if (ToType->isEventT() &&
2607 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2609 FromType = ToType;
2610 } else if (ToType->isQueueT() &&
2612 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2614 FromType = ToType;
2615 } else if (ToType->isSamplerT() &&
2618 FromType = ToType;
2619 } else if ((ToType->isFixedPointType() &&
2620 FromType->isConvertibleToFixedPointType()) ||
2621 (FromType->isFixedPointType() &&
2622 ToType->isConvertibleToFixedPointType())) {
2624 FromType = ToType;
2625 } else {
2626 // No second conversion required.
2627 SCS.Second = ICK_Identity;
2628 }
2629 SCS.setToType(1, FromType);
2630
2631 // The third conversion can be a function pointer conversion or a
2632 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2633 bool ObjCLifetimeConversion;
2634 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2635 // Function pointer conversions (removing 'noexcept') including removal of
2636 // 'noreturn' (Clang extension).
2638 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2639 ObjCLifetimeConversion)) {
2641 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2642 FromType = ToType;
2643 } else {
2644 // No conversion required
2645 SCS.Third = ICK_Identity;
2646 }
2647
2648 // C++ [over.best.ics]p6:
2649 // [...] Any difference in top-level cv-qualification is
2650 // subsumed by the initialization itself and does not constitute
2651 // a conversion. [...]
2652 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2653 QualType CanonTo = S.Context.getCanonicalType(ToType);
2654 if (CanonFrom.getLocalUnqualifiedType()
2655 == CanonTo.getLocalUnqualifiedType() &&
2656 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2657 FromType = ToType;
2658 CanonFrom = CanonTo;
2659 }
2660
2661 SCS.setToType(2, FromType);
2662
2663 if (CanonFrom == CanonTo)
2664 return true;
2665
2666 // If we have not converted the argument type to the parameter type,
2667 // this is a bad conversion sequence, unless we're resolving an overload in C.
2668 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2669 return false;
2670
2671 ExprResult ER = ExprResult{From};
2672 AssignConvertType Conv =
2674 /*Diagnose=*/false,
2675 /*DiagnoseCFAudited=*/false,
2676 /*ConvertRHS=*/false);
2677 ImplicitConversionKind SecondConv;
2678 switch (Conv) {
2680 case AssignConvertType::
2681 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2682 SecondConv = ICK_C_Only_Conversion;
2683 break;
2684 // For our purposes, discarding qualifiers is just as bad as using an
2685 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2686 // qualifiers, as well.
2691 break;
2692 default:
2693 return false;
2694 }
2695
2696 // First can only be an lvalue conversion, so we pretend that this was the
2697 // second conversion. First should already be valid from earlier in the
2698 // function.
2699 SCS.Second = SecondConv;
2700 SCS.setToType(1, ToType);
2701
2702 // Third is Identity, because Second should rank us worse than any other
2703 // conversion. This could also be ICK_Qualification, but it's simpler to just
2704 // lump everything in with the second conversion, and we don't gain anything
2705 // from making this ICK_Qualification.
2706 SCS.Third = ICK_Identity;
2707 SCS.setToType(2, ToType);
2708 return true;
2709}
2710
2711static bool
2713 QualType &ToType,
2714 bool InOverloadResolution,
2716 bool CStyle) {
2717
2718 const RecordType *UT = ToType->getAsUnionType();
2719 if (!UT)
2720 return false;
2721 // The field to initialize within the transparent union.
2722 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2723 if (!UD->hasAttr<TransparentUnionAttr>())
2724 return false;
2725 // It's compatible if the expression matches any of the fields.
2726 for (const auto *it : UD->fields()) {
2727 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2728 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2729 ToType = it->getType();
2730 return true;
2731 }
2732 }
2733 return false;
2734}
2735
2736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2737 const BuiltinType *To = ToType->getAs<BuiltinType>();
2738 // All integers are built-in.
2739 if (!To) {
2740 return false;
2741 }
2742
2743 // An rvalue of type char, signed char, unsigned char, short int, or
2744 // unsigned short int can be converted to an rvalue of type int if
2745 // int can represent all the values of the source type; otherwise,
2746 // the source rvalue can be converted to an rvalue of type unsigned
2747 // int (C++ 4.5p1).
2748 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2749 !FromType->isEnumeralType()) {
2750 if ( // We can promote any signed, promotable integer type to an int
2751 (FromType->isSignedIntegerType() ||
2752 // We can promote any unsigned integer type whose size is
2753 // less than int to an int.
2754 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2755 return To->getKind() == BuiltinType::Int;
2756 }
2757
2758 return To->getKind() == BuiltinType::UInt;
2759 }
2760
2761 // C++11 [conv.prom]p3:
2762 // A prvalue of an unscoped enumeration type whose underlying type is not
2763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2764 // following types that can represent all the values of the enumeration
2765 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2766 // unsigned int, long int, unsigned long int, long long int, or unsigned
2767 // long long int. If none of the types in that list can represent all the
2768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2769 // type can be converted to an rvalue a prvalue of the extended integer type
2770 // with lowest integer conversion rank (4.13) greater than the rank of long
2771 // long in which all the values of the enumeration can be represented. If
2772 // there are two such extended types, the signed one is chosen.
2773 // C++11 [conv.prom]p4:
2774 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2775 // can be converted to a prvalue of its underlying type. Moreover, if
2776 // integral promotion can be applied to its underlying type, a prvalue of an
2777 // unscoped enumeration type whose underlying type is fixed can also be
2778 // converted to a prvalue of the promoted underlying type.
2779 if (const auto *FromED = FromType->getAsEnumDecl()) {
2780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2781 // provided for a scoped enumeration.
2782 if (FromED->isScoped())
2783 return false;
2784
2785 // We can perform an integral promotion to the underlying type of the enum,
2786 // even if that's not the promoted type. Note that the check for promoting
2787 // the underlying type is based on the type alone, and does not consider
2788 // the bitfield-ness of the actual source expression.
2789 if (FromED->isFixed()) {
2790 QualType Underlying = FromED->getIntegerType();
2791 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2792 IsIntegralPromotion(nullptr, Underlying, ToType);
2793 }
2794
2795 // We have already pre-calculated the promotion type, so this is trivial.
2796 if (ToType->isIntegerType() &&
2797 isCompleteType(From->getBeginLoc(), FromType))
2798 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2799
2800 // C++ [conv.prom]p5:
2801 // If the bit-field has an enumerated type, it is treated as any other
2802 // value of that type for promotion purposes.
2803 //
2804 // ... so do not fall through into the bit-field checks below in C++.
2805 if (getLangOpts().CPlusPlus)
2806 return false;
2807 }
2808
2809 // C++0x [conv.prom]p2:
2810 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2811 // to an rvalue a prvalue of the first of the following types that can
2812 // represent all the values of its underlying type: int, unsigned int,
2813 // long int, unsigned long int, long long int, or unsigned long long int.
2814 // If none of the types in that list can represent all the values of its
2815 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2816 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2817 // type.
2818 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2819 ToType->isIntegerType()) {
2820 // Determine whether the type we're converting from is signed or
2821 // unsigned.
2822 bool FromIsSigned = FromType->isSignedIntegerType();
2823 uint64_t FromSize = Context.getTypeSize(FromType);
2824
2825 // The types we'll try to promote to, in the appropriate
2826 // order. Try each of these types.
2827 QualType PromoteTypes[6] = {
2828 Context.IntTy, Context.UnsignedIntTy,
2829 Context.LongTy, Context.UnsignedLongTy ,
2830 Context.LongLongTy, Context.UnsignedLongLongTy
2831 };
2832 for (int Idx = 0; Idx < 6; ++Idx) {
2833 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2834 if (FromSize < ToSize ||
2835 (FromSize == ToSize &&
2836 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2837 // We found the type that we can promote to. If this is the
2838 // type we wanted, we have a promotion. Otherwise, no
2839 // promotion.
2840 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2841 }
2842 }
2843 }
2844
2845 // An rvalue for an integral bit-field (9.6) can be converted to an
2846 // rvalue of type int if int can represent all the values of the
2847 // bit-field; otherwise, it can be converted to unsigned int if
2848 // unsigned int can represent all the values of the bit-field. If
2849 // the bit-field is larger yet, no integral promotion applies to
2850 // it. If the bit-field has an enumerated type, it is treated as any
2851 // other value of that type for promotion purposes (C++ 4.5p3).
2852 // FIXME: We should delay checking of bit-fields until we actually perform the
2853 // conversion.
2854 //
2855 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2856 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2857 // bit-fields and those whose underlying type is larger than int) for GCC
2858 // compatibility.
2859 if (From) {
2860 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2861 std::optional<llvm::APSInt> BitWidth;
2862 if (FromType->isIntegralType(Context) &&
2863 (BitWidth =
2864 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2865 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2866 ToSize = Context.getTypeSize(ToType);
2867
2868 // Are we promoting to an int from a bitfield that fits in an int?
2869 if (*BitWidth < ToSize ||
2870 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2871 return To->getKind() == BuiltinType::Int;
2872 }
2873
2874 // Are we promoting to an unsigned int from an unsigned bitfield
2875 // that fits into an unsigned int?
2876 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2877 return To->getKind() == BuiltinType::UInt;
2878 }
2879
2880 return false;
2881 }
2882 }
2883 }
2884
2885 // An rvalue of type bool can be converted to an rvalue of type int,
2886 // with false becoming zero and true becoming one (C++ 4.5p4).
2887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2888 return true;
2889 }
2890
2891 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2892 // integral type.
2893 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2894 ToType->isIntegerType())
2895 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2896
2897 return false;
2898}
2899
2901 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2902 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2903 /// An rvalue of type float can be converted to an rvalue of type
2904 /// double. (C++ 4.6p1).
2905 if (FromBuiltin->getKind() == BuiltinType::Float &&
2906 ToBuiltin->getKind() == BuiltinType::Double)
2907 return true;
2908
2909 // C99 6.3.1.5p1:
2910 // When a float is promoted to double or long double, or a
2911 // double is promoted to long double [...].
2912 if (!getLangOpts().CPlusPlus &&
2913 (FromBuiltin->getKind() == BuiltinType::Float ||
2914 FromBuiltin->getKind() == BuiltinType::Double) &&
2915 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2916 ToBuiltin->getKind() == BuiltinType::Float128 ||
2917 ToBuiltin->getKind() == BuiltinType::Ibm128))
2918 return true;
2919
2920 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2921 // or not native half types are enabled.
2922 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2923 (ToBuiltin->getKind() == BuiltinType::Float ||
2924 ToBuiltin->getKind() == BuiltinType::Double))
2925 return true;
2926
2927 // Half can be promoted to float.
2928 if (!getLangOpts().NativeHalfType &&
2929 FromBuiltin->getKind() == BuiltinType::Half &&
2930 ToBuiltin->getKind() == BuiltinType::Float)
2931 return true;
2932 }
2933
2934 return false;
2935}
2936
2938 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2939 if (!FromComplex)
2940 return false;
2941
2942 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2943 if (!ToComplex)
2944 return false;
2945
2946 return IsFloatingPointPromotion(FromComplex->getElementType(),
2947 ToComplex->getElementType()) ||
2948 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2949 ToComplex->getElementType());
2950}
2951
2953 if (!getLangOpts().OverflowBehaviorTypes)
2954 return false;
2955
2956 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2957 return false;
2958
2959 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2960}
2961
2963 QualType ToType) {
2964 if (!getLangOpts().OverflowBehaviorTypes)
2965 return false;
2966
2967 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2968 if (ToType->isBooleanType())
2969 return false;
2970 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2971 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2972 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2973 if (ToED->isScoped())
2974 return false;
2975 }
2976 return true;
2977 }
2978
2979 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2980 return true;
2981
2982 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2983 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2984
2985 return false;
2986}
2987
2988/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2989/// the pointer type FromPtr to a pointer to type ToPointee, with the
2990/// same type qualifiers as FromPtr has on its pointee type. ToType,
2991/// if non-empty, will be a pointer to ToType that may or may not have
2992/// the right set of qualifiers on its pointee.
2993///
2994static QualType
2996 QualType ToPointee, QualType ToType,
2997 ASTContext &Context,
2998 bool StripObjCLifetime = false) {
2999 assert((FromPtr->getTypeClass() == Type::Pointer ||
3000 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3001 "Invalid similarly-qualified pointer type");
3002
3003 /// Conversions to 'id' subsume cv-qualifier conversions.
3004 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3005 return ToType.getUnqualifiedType();
3006
3007 QualType CanonFromPointee
3008 = Context.getCanonicalType(FromPtr->getPointeeType());
3009 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3010 Qualifiers Quals = CanonFromPointee.getQualifiers();
3011
3012 if (StripObjCLifetime)
3013 Quals.removeObjCLifetime();
3014
3015 // Exact qualifier match -> return the pointer type we're converting to.
3016 if (CanonToPointee.getLocalQualifiers() == Quals) {
3017 // ToType is exactly what we need. Return it.
3018 if (!ToType.isNull())
3019 return ToType.getUnqualifiedType();
3020
3021 // Build a pointer to ToPointee. It has the right qualifiers
3022 // already.
3023 if (isa<ObjCObjectPointerType>(ToType))
3024 return Context.getObjCObjectPointerType(ToPointee);
3025 return Context.getPointerType(ToPointee);
3026 }
3027
3028 // Just build a canonical type that has the right qualifiers.
3029 QualType QualifiedCanonToPointee
3030 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3031
3032 if (isa<ObjCObjectPointerType>(ToType))
3033 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3034 return Context.getPointerType(QualifiedCanonToPointee);
3035}
3036
3038 bool InOverloadResolution,
3039 ASTContext &Context) {
3040 // Handle value-dependent integral null pointer constants correctly.
3041 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3042 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3044 return !InOverloadResolution;
3045
3046 return Expr->isNullPointerConstant(Context,
3047 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3049}
3050
3052 bool InOverloadResolution,
3053 QualType& ConvertedType,
3054 bool &IncompatibleObjC) {
3055 IncompatibleObjC = false;
3056 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3057 IncompatibleObjC))
3058 return true;
3059
3060 // Conversion from a null pointer constant to any Objective-C pointer type.
3061 if (ToType->isObjCObjectPointerType() &&
3062 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3063 ConvertedType = ToType;
3064 return true;
3065 }
3066
3067 // Blocks: Block pointers can be converted to void*.
3068 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3069 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073 // Blocks: A null pointer constant can be converted to a block
3074 // pointer type.
3075 if (ToType->isBlockPointerType() &&
3076 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3077 ConvertedType = ToType;
3078 return true;
3079 }
3080
3081 // If the left-hand-side is nullptr_t, the right side can be a null
3082 // pointer constant.
3083 if (ToType->isNullPtrType() &&
3084 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3085 ConvertedType = ToType;
3086 return true;
3087 }
3088
3089 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3090 if (!ToTypePtr)
3091 return false;
3092
3093 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3094 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3095 ConvertedType = ToType;
3096 return true;
3097 }
3098
3099 // Beyond this point, both types need to be pointers
3100 // , including objective-c pointers.
3101 QualType ToPointeeType = ToTypePtr->getPointeeType();
3102 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3103 !getLangOpts().ObjCAutoRefCount) {
3104 ConvertedType = BuildSimilarlyQualifiedPointerType(
3105 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3106 Context);
3107 return true;
3108 }
3109 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3110 if (!FromTypePtr)
3111 return false;
3112
3113 QualType FromPointeeType = FromTypePtr->getPointeeType();
3114
3115 // If the unqualified pointee types are the same, this can't be a
3116 // pointer conversion, so don't do all of the work below.
3117 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3118 return false;
3119
3120 // An rvalue of type "pointer to cv T," where T is an object type,
3121 // can be converted to an rvalue of type "pointer to cv void" (C++
3122 // 4.10p2).
3123 if (FromPointeeType->isIncompleteOrObjectType() &&
3124 ToPointeeType->isVoidType()) {
3125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3126 ToPointeeType,
3127 ToType, Context,
3128 /*StripObjCLifetime=*/true);
3129 return true;
3130 }
3131
3132 // MSVC allows implicit function to void* type conversion.
3133 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3134 ToPointeeType->isVoidType()) {
3135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3136 ToPointeeType,
3137 ToType, Context);
3138 return true;
3139 }
3140
3141 // When we're overloading in C, we allow a special kind of pointer
3142 // conversion for compatible-but-not-identical pointee types.
3143 if (!getLangOpts().CPlusPlus &&
3144 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3146 ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 // C++ [conv.ptr]p3:
3152 //
3153 // An rvalue of type "pointer to cv D," where D is a class type,
3154 // can be converted to an rvalue of type "pointer to cv B," where
3155 // B is a base class (clause 10) of D. If B is an inaccessible
3156 // (clause 11) or ambiguous (10.2) base class of D, a program that
3157 // necessitates this conversion is ill-formed. The result of the
3158 // conversion is a pointer to the base class sub-object of the
3159 // derived class object. The null pointer value is converted to
3160 // the null pointer value of the destination type.
3161 //
3162 // Note that we do not check for ambiguity or inaccessibility
3163 // here. That is handled by CheckPointerConversion.
3164 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3165 ToPointeeType->isRecordType() &&
3166 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3167 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3169 ToPointeeType,
3170 ToType, Context);
3171 return true;
3172 }
3173
3174 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3175 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3176 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3177 ToPointeeType,
3178 ToType, Context);
3179 return true;
3180 }
3181
3182 return false;
3183}
3184
3185/// Adopt the given qualifiers for the given type.
3187 Qualifiers TQs = T.getQualifiers();
3188
3189 // Check whether qualifiers already match.
3190 if (TQs == Qs)
3191 return T;
3192
3193 if (Qs.compatiblyIncludes(TQs, Context))
3194 return Context.getQualifiedType(T, Qs);
3195
3196 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3197}
3198
3200 QualType& ConvertedType,
3201 bool &IncompatibleObjC) {
3202 if (!getLangOpts().ObjC)
3203 return false;
3204
3205 // The set of qualifiers on the type we're converting from.
3206 Qualifiers FromQualifiers = FromType.getQualifiers();
3207
3208 // First, we handle all conversions on ObjC object pointer types.
3209 const ObjCObjectPointerType* ToObjCPtr =
3210 ToType->getAs<ObjCObjectPointerType>();
3211 const ObjCObjectPointerType *FromObjCPtr =
3212 FromType->getAs<ObjCObjectPointerType>();
3213
3214 if (ToObjCPtr && FromObjCPtr) {
3215 // If the pointee types are the same (ignoring qualifications),
3216 // then this is not a pointer conversion.
3217 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3218 FromObjCPtr->getPointeeType()))
3219 return false;
3220
3221 // Conversion between Objective-C pointers.
3222 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3223 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3224 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3225 if (getLangOpts().CPlusPlus && LHS && RHS &&
3227 FromObjCPtr->getPointeeType(), getASTContext()))
3228 return false;
3229 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3230 ToObjCPtr->getPointeeType(),
3231 ToType, Context);
3232 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3233 return true;
3234 }
3235
3236 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3237 // Okay: this is some kind of implicit downcast of Objective-C
3238 // interfaces, which is permitted. However, we're going to
3239 // complain about it.
3240 IncompatibleObjC = true;
3241 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3242 ToObjCPtr->getPointeeType(),
3243 ToType, Context);
3244 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3245 return true;
3246 }
3247 }
3248 // Beyond this point, both types need to be C pointers or block pointers.
3249 QualType ToPointeeType;
3250 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3251 ToPointeeType = ToCPtr->getPointeeType();
3252 else if (const BlockPointerType *ToBlockPtr =
3253 ToType->getAs<BlockPointerType>()) {
3254 // Objective C++: We're able to convert from a pointer to any object
3255 // to a block pointer type.
3256 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3257 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3258 return true;
3259 }
3260 ToPointeeType = ToBlockPtr->getPointeeType();
3261 }
3262 else if (FromType->getAs<BlockPointerType>() &&
3263 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3264 // Objective C++: We're able to convert from a block pointer type to a
3265 // pointer to any object.
3266 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3267 return true;
3268 }
3269 else
3270 return false;
3271
3272 QualType FromPointeeType;
3273 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3274 FromPointeeType = FromCPtr->getPointeeType();
3275 else if (const BlockPointerType *FromBlockPtr =
3276 FromType->getAs<BlockPointerType>())
3277 FromPointeeType = FromBlockPtr->getPointeeType();
3278 else
3279 return false;
3280
3281 // If we have pointers to pointers, recursively check whether this
3282 // is an Objective-C conversion.
3283 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3284 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3285 IncompatibleObjC)) {
3286 // We always complain about this conversion.
3287 IncompatibleObjC = true;
3288 ConvertedType = Context.getPointerType(ConvertedType);
3289 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3290 return true;
3291 }
3292 // Allow conversion of pointee being objective-c pointer to another one;
3293 // as in I* to id.
3294 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3295 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3296 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3297 IncompatibleObjC)) {
3298
3299 ConvertedType = Context.getPointerType(ConvertedType);
3300 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3301 return true;
3302 }
3303
3304 // If we have pointers to functions or blocks, check whether the only
3305 // differences in the argument and result types are in Objective-C
3306 // pointer conversions. If so, we permit the conversion (but
3307 // complain about it).
3308 const FunctionProtoType *FromFunctionType
3309 = FromPointeeType->getAs<FunctionProtoType>();
3310 const FunctionProtoType *ToFunctionType
3311 = ToPointeeType->getAs<FunctionProtoType>();
3312 if (FromFunctionType && ToFunctionType) {
3313 // If the function types are exactly the same, this isn't an
3314 // Objective-C pointer conversion.
3315 if (Context.getCanonicalType(FromPointeeType)
3316 == Context.getCanonicalType(ToPointeeType))
3317 return false;
3318
3319 // Perform the quick checks that will tell us whether these
3320 // function types are obviously different.
3321 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3322 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3323 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3324 return false;
3325
3326 bool HasObjCConversion = false;
3327 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3328 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3329 // Okay, the types match exactly. Nothing to do.
3330 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3331 ToFunctionType->getReturnType(),
3332 ConvertedType, IncompatibleObjC)) {
3333 // Okay, we have an Objective-C pointer conversion.
3334 HasObjCConversion = true;
3335 } else {
3336 // Function types are too different. Abort.
3337 return false;
3338 }
3339
3340 // Check argument types.
3341 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3342 ArgIdx != NumArgs; ++ArgIdx) {
3343 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3344 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3345 if (Context.getCanonicalType(FromArgType)
3346 == Context.getCanonicalType(ToArgType)) {
3347 // Okay, the types match exactly. Nothing to do.
3348 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3349 ConvertedType, IncompatibleObjC)) {
3350 // Okay, we have an Objective-C pointer conversion.
3351 HasObjCConversion = true;
3352 } else {
3353 // Argument types are too different. Abort.
3354 return false;
3355 }
3356 }
3357
3358 if (HasObjCConversion) {
3359 // We had an Objective-C conversion. Allow this pointer
3360 // conversion, but complain about it.
3361 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3362 IncompatibleObjC = true;
3363 return true;
3364 }
3365 }
3366
3367 return false;
3368}
3369
3371 QualType& ConvertedType) {
3372 QualType ToPointeeType;
3373 if (const BlockPointerType *ToBlockPtr =
3374 ToType->getAs<BlockPointerType>())
3375 ToPointeeType = ToBlockPtr->getPointeeType();
3376 else
3377 return false;
3378
3379 QualType FromPointeeType;
3380 if (const BlockPointerType *FromBlockPtr =
3381 FromType->getAs<BlockPointerType>())
3382 FromPointeeType = FromBlockPtr->getPointeeType();
3383 else
3384 return false;
3385 // We have pointer to blocks, check whether the only
3386 // differences in the argument and result types are in Objective-C
3387 // pointer conversions. If so, we permit the conversion.
3388
3389 const FunctionProtoType *FromFunctionType
3390 = FromPointeeType->getAs<FunctionProtoType>();
3391 const FunctionProtoType *ToFunctionType
3392 = ToPointeeType->getAs<FunctionProtoType>();
3393
3394 if (!FromFunctionType || !ToFunctionType)
3395 return false;
3396
3397 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3398 return true;
3399
3400 // Perform the quick checks that will tell us whether these
3401 // function types are obviously different.
3402 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3403 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3404 return false;
3405
3406 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3407 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3408 if (FromEInfo != ToEInfo)
3409 return false;
3410
3411 bool IncompatibleObjC = false;
3412 if (Context.hasSameType(FromFunctionType->getReturnType(),
3413 ToFunctionType->getReturnType())) {
3414 // Okay, the types match exactly. Nothing to do.
3415 } else {
3416 QualType RHS = FromFunctionType->getReturnType();
3417 QualType LHS = ToFunctionType->getReturnType();
3418 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3419 !RHS.hasQualifiers() && LHS.hasQualifiers())
3420 LHS = LHS.getUnqualifiedType();
3421
3422 if (Context.hasSameType(RHS,LHS)) {
3423 // OK exact match.
3424 } else if (isObjCPointerConversion(RHS, LHS,
3425 ConvertedType, IncompatibleObjC)) {
3426 if (IncompatibleObjC)
3427 return false;
3428 // Okay, we have an Objective-C pointer conversion.
3429 }
3430 else
3431 return false;
3432 }
3433
3434 // Check argument types.
3435 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3436 ArgIdx != NumArgs; ++ArgIdx) {
3437 IncompatibleObjC = false;
3438 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3439 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3440 if (Context.hasSameType(FromArgType, ToArgType)) {
3441 // Okay, the types match exactly. Nothing to do.
3442 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3443 ConvertedType, IncompatibleObjC)) {
3444 if (IncompatibleObjC)
3445 return false;
3446 // Okay, we have an Objective-C pointer conversion.
3447 } else
3448 // Argument types are too different. Abort.
3449 return false;
3450 }
3451
3453 bool CanUseToFPT, CanUseFromFPT;
3454 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3455 CanUseToFPT, CanUseFromFPT,
3456 NewParamInfos))
3457 return false;
3458
3459 ConvertedType = ToType;
3460 return true;
3461}
3462
3463enum {
3471};
3472
3473/// Attempts to get the FunctionProtoType from a Type. Handles
3474/// MemberFunctionPointers properly.
3476 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3477 return FPT;
3478
3479 if (auto *MPT = FromType->getAs<MemberPointerType>())
3480 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3481
3482 return nullptr;
3483}
3484
3486 QualType FromType, QualType ToType) {
3487 // If either type is not valid, include no extra info.
3488 if (FromType.isNull() || ToType.isNull()) {
3489 PDiag << ft_default;
3490 return;
3491 }
3492
3493 // Get the function type from the pointers.
3494 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3495 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3496 *ToMember = ToType->castAs<MemberPointerType>();
3497 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3498 ToMember->getMostRecentCXXRecordDecl())) {
3500 if (ToMember->isSugared())
3501 PDiag << Context.getCanonicalTagType(
3502 ToMember->getMostRecentCXXRecordDecl());
3503 else
3504 PDiag << ToMember->getQualifier();
3505 if (FromMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 FromMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << FromMember->getQualifier();
3510 return;
3511 }
3512 FromType = FromMember->getPointeeType();
3513 ToType = ToMember->getPointeeType();
3514 }
3515
3516 if (FromType->isPointerType())
3517 FromType = FromType->getPointeeType();
3518 if (ToType->isPointerType())
3519 ToType = ToType->getPointeeType();
3520
3521 // Remove references.
3522 FromType = FromType.getNonReferenceType();
3523 ToType = ToType.getNonReferenceType();
3524
3525 // Don't print extra info for non-specialized template functions.
3526 if (FromType->isInstantiationDependentType() &&
3527 !FromType->getAs<TemplateSpecializationType>()) {
3528 PDiag << ft_default;
3529 return;
3530 }
3531
3532 // No extra info for same types.
3533 if (Context.hasSameType(FromType, ToType)) {
3534 PDiag << ft_default;
3535 return;
3536 }
3537
3538 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3539 *ToFunction = tryGetFunctionProtoType(ToType);
3540
3541 // Both types need to be function types.
3542 if (!FromFunction || !ToFunction) {
3543 PDiag << ft_default;
3544 return;
3545 }
3546
3547 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3548 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3549 << FromFunction->getNumParams();
3550 return;
3551 }
3552
3553 // Handle different parameter types.
3554 unsigned ArgPos;
3555 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3556 PDiag << ft_parameter_mismatch << ArgPos + 1
3557 << ToFunction->getParamType(ArgPos)
3558 << FromFunction->getParamType(ArgPos);
3559 return;
3560 }
3561
3562 // Handle different return type.
3563 if (!Context.hasSameType(FromFunction->getReturnType(),
3564 ToFunction->getReturnType())) {
3565 PDiag << ft_return_type << ToFunction->getReturnType()
3566 << FromFunction->getReturnType();
3567 return;
3568 }
3569
3570 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3571 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3572 << FromFunction->getMethodQuals();
3573 return;
3574 }
3575
3576 // Handle exception specification differences on canonical type (in C++17
3577 // onwards).
3579 ->isNothrow() !=
3580 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3581 ->isNothrow()) {
3582 PDiag << ft_noexcept;
3583 return;
3584 }
3585
3586 // Unable to find a difference, so add no extra info.
3587 PDiag << ft_default;
3588}
3589
3591 ArrayRef<QualType> New, unsigned *ArgPos,
3592 bool Reversed) {
3593 assert(llvm::size(Old) == llvm::size(New) &&
3594 "Can't compare parameters of functions with different number of "
3595 "parameters!");
3596
3597 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3598 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3599 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3600
3601 // Ignore address spaces in pointee type. This is to disallow overloading
3602 // on __ptr32/__ptr64 address spaces.
3603 QualType OldType =
3604 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3605 QualType NewType =
3606 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3607
3608 if (!Context.hasSameType(OldType, NewType)) {
3609 if (ArgPos)
3610 *ArgPos = Idx;
3611 return false;
3612 }
3613 }
3614 return true;
3615}
3616
3618 const FunctionProtoType *NewType,
3619 unsigned *ArgPos, bool Reversed) {
3620 return FunctionParamTypesAreEqual(OldType->param_types(),
3621 NewType->param_types(), ArgPos, Reversed);
3622}
3623
3625 const FunctionDecl *NewFunction,
3626 unsigned *ArgPos,
3627 bool Reversed) {
3628
3629 if (OldFunction->getNumNonObjectParams() !=
3630 NewFunction->getNumNonObjectParams())
3631 return false;
3632
3633 unsigned OldIgnore =
3635 unsigned NewIgnore =
3637
3638 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3639 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3640
3641 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3642 NewPT->param_types().slice(NewIgnore),
3643 ArgPos, Reversed);
3644}
3645
3647 CastKind &Kind,
3648 CXXCastPath& BasePath,
3649 bool IgnoreBaseAccess,
3650 bool Diagnose) {
3651 QualType FromType = From->getType();
3652 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3653
3654 Kind = CK_BitCast;
3655
3656 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3659 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3660 DiagRuntimeBehavior(From->getExprLoc(), From,
3661 PDiag(diag::warn_impcast_bool_to_null_pointer)
3662 << ToType << From->getSourceRange());
3663 else if (!isUnevaluatedContext())
3664 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3665 << ToType << From->getSourceRange();
3666 }
3667 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3668 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3669 QualType FromPointeeType = FromPtrType->getPointeeType(),
3670 ToPointeeType = ToPtrType->getPointeeType();
3671
3672 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3673 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3674 // We must have a derived-to-base conversion. Check an
3675 // ambiguous or inaccessible conversion.
3676 unsigned InaccessibleID = 0;
3677 unsigned AmbiguousID = 0;
3678 if (Diagnose) {
3679 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3680 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3681 }
3683 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3684 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3685 &BasePath, IgnoreBaseAccess))
3686 return true;
3687
3688 // The conversion was successful.
3689 Kind = CK_DerivedToBase;
3690 }
3691
3692 if (Diagnose && !IsCStyleOrFunctionalCast &&
3693 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3694 assert(getLangOpts().MSVCCompat &&
3695 "this should only be possible with MSVCCompat!");
3696 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3697 << From->getSourceRange();
3698 }
3699 }
3700 } else if (const ObjCObjectPointerType *ToPtrType =
3701 ToType->getAs<ObjCObjectPointerType>()) {
3702 if (const ObjCObjectPointerType *FromPtrType =
3703 FromType->getAs<ObjCObjectPointerType>()) {
3704 // Objective-C++ conversions are always okay.
3705 // FIXME: We should have a different class of conversions for the
3706 // Objective-C++ implicit conversions.
3707 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3708 return false;
3709 } else if (FromType->isBlockPointerType()) {
3710 Kind = CK_BlockPointerToObjCPointerCast;
3711 } else {
3712 Kind = CK_CPointerToObjCPointerCast;
3713 }
3714 } else if (ToType->isBlockPointerType()) {
3715 if (!FromType->isBlockPointerType())
3716 Kind = CK_AnyPointerToBlockPointerCast;
3717 }
3718
3719 // We shouldn't fall into this case unless it's valid for other
3720 // reasons.
3722 Kind = CK_NullToPointer;
3723
3724 return false;
3725}
3726
3728 QualType ToType,
3729 bool InOverloadResolution,
3730 QualType &ConvertedType) {
3731 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3732 if (!ToTypePtr)
3733 return false;
3734
3735 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3737 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3739 ConvertedType = ToType;
3740 return true;
3741 }
3742
3743 // Otherwise, both types have to be member pointers.
3744 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3745 if (!FromTypePtr)
3746 return false;
3747
3748 // A pointer to member of B can be converted to a pointer to member of D,
3749 // where D is derived from B (C++ 4.11p2).
3750 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3751 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3752
3753 if (!declaresSameEntity(FromClass, ToClass) &&
3754 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3755 ConvertedType = Context.getMemberPointerType(
3756 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3757 return true;
3758 }
3759
3760 return false;
3761}
3762
3764 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3765 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3766 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3767 // Lock down the inheritance model right now in MS ABI, whether or not the
3768 // pointee types are the same.
3769 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3770 (void)isCompleteType(CheckLoc, FromType);
3771 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3772 }
3773
3774 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3775 if (!FromPtrType) {
3776 // This must be a null pointer to member pointer conversion
3777 Kind = CK_NullToMemberPointer;
3779 }
3780
3781 // T == T, modulo cv
3783 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3784 ToPtrType->getPointeeType()))
3786
3787 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3788 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3789
3790 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3791 const CXXRecordDecl *Cls) {
3792 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3793 PD << Qual;
3794 else
3795 PD << Context.getCanonicalTagType(Cls);
3796 };
3797 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3798 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3799 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3800 return PD;
3801 };
3802
3803 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3805 std::swap(Base, Derived);
3806
3807 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3808 /*DetectVirtual=*/true);
3809 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3811
3812 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3813 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3814 PD << int(Direction);
3815 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3816 Diag(CheckLoc, PD);
3818 }
3819
3820 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3821 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3822 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3823 Diag(CheckLoc, PD);
3825 }
3826
3827 // Must be a base to derived member conversion.
3828 BuildBasePathArray(Paths, BasePath);
3830 ? CK_DerivedToBaseMemberPointer
3831 : CK_BaseToDerivedMemberPointer;
3832
3833 if (!IgnoreBaseAccess)
3834 switch (CheckBaseClassAccess(
3835 CheckLoc, Base, Derived, Paths.front(),
3837 ? diag::err_upcast_to_inaccessible_base
3838 : diag::err_downcast_from_inaccessible_base,
3839 [&](PartialDiagnostic &PD) {
3840 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3841 DerivedQual = ToPtrType->getQualifier();
3842 if (Direction == MemberPointerConversionDirection::Upcast)
3843 std::swap(BaseQual, DerivedQual);
3844 DiagCls(PD, DerivedQual, Derived);
3845 DiagCls(PD, BaseQual, Base);
3846 })) {
3848 case Sema::AR_delayed:
3849 case Sema::AR_dependent:
3850 // Optimistically assume that the delayed and dependent cases
3851 // will work out.
3852 break;
3853
3856 }
3857
3859}
3860
3861/// Determine whether the lifetime conversion between the two given
3862/// qualifiers sets is nontrivial.
3864 Qualifiers ToQuals) {
3865 // Converting anything to const __unsafe_unretained is trivial.
3866 if (ToQuals.hasConst() &&
3868 return false;
3869
3870 return true;
3871}
3872
3873/// Perform a single iteration of the loop for checking if a qualification
3874/// conversion is valid.
3875///
3876/// Specifically, check whether any change between the qualifiers of \p
3877/// FromType and \p ToType is permissible, given knowledge about whether every
3878/// outer layer is const-qualified.
3880 bool CStyle, bool IsTopLevel,
3881 bool &PreviousToQualsIncludeConst,
3882 bool &ObjCLifetimeConversion,
3883 const ASTContext &Ctx) {
3884 Qualifiers FromQuals = FromType.getQualifiers();
3885 Qualifiers ToQuals = ToType.getQualifiers();
3886
3887 // Ignore __unaligned qualifier.
3888 FromQuals.removeUnaligned();
3889
3890 // Objective-C ARC:
3891 // Check Objective-C lifetime conversions.
3892 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3893 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3894 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3895 ObjCLifetimeConversion = true;
3896 FromQuals.removeObjCLifetime();
3897 ToQuals.removeObjCLifetime();
3898 } else {
3899 // Qualification conversions cannot cast between different
3900 // Objective-C lifetime qualifiers.
3901 return false;
3902 }
3903 }
3904
3905 // Allow addition/removal of GC attributes but not changing GC attributes.
3906 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3907 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3908 FromQuals.removeObjCGCAttr();
3909 ToQuals.removeObjCGCAttr();
3910 }
3911
3912 // __ptrauth qualifiers must match exactly.
3913 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3914 return false;
3915
3916 // -- for every j > 0, if const is in cv 1,j then const is in cv
3917 // 2,j, and similarly for volatile.
3918 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3919 return false;
3920
3921 // If address spaces mismatch:
3922 // - in top level it is only valid to convert to addr space that is a
3923 // superset in all cases apart from C-style casts where we allow
3924 // conversions between overlapping address spaces.
3925 // - in non-top levels it is not a valid conversion.
3926 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3927 (!IsTopLevel ||
3928 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3929 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3930 return false;
3931
3932 // -- if the cv 1,j and cv 2,j are different, then const is in
3933 // every cv for 0 < k < j.
3934 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3935 !PreviousToQualsIncludeConst)
3936 return false;
3937
3938 // The following wording is from C++20, where the result of the conversion
3939 // is T3, not T2.
3940 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3941 // "array of unknown bound of"
3942 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3943 return false;
3944
3945 // -- if the resulting P3,i is different from P1,i [...], then const is
3946 // added to every cv 3_k for 0 < k < i.
3947 if (!CStyle && FromType->isConstantArrayType() &&
3948 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3949 return false;
3950
3951 // Keep track of whether all prior cv-qualifiers in the "to" type
3952 // include const.
3953 PreviousToQualsIncludeConst =
3954 PreviousToQualsIncludeConst && ToQuals.hasConst();
3955 return true;
3956}
3957
3958bool
3960 bool CStyle, bool &ObjCLifetimeConversion) {
3961 FromType = Context.getCanonicalType(FromType);
3962 ToType = Context.getCanonicalType(ToType);
3963 ObjCLifetimeConversion = false;
3964
3965 // If FromType and ToType are the same type, this is not a
3966 // qualification conversion.
3967 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3968 return false;
3969
3970 // (C++ 4.4p4):
3971 // A conversion can add cv-qualifiers at levels other than the first
3972 // in multi-level pointers, subject to the following rules: [...]
3973 bool PreviousToQualsIncludeConst = true;
3974 bool UnwrappedAnyPointer = false;
3975 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3976 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3977 !UnwrappedAnyPointer,
3978 PreviousToQualsIncludeConst,
3979 ObjCLifetimeConversion, getASTContext()))
3980 return false;
3981 UnwrappedAnyPointer = true;
3982 }
3983
3984 // We are left with FromType and ToType being the pointee types
3985 // after unwrapping the original FromType and ToType the same number
3986 // of times. If we unwrapped any pointers, and if FromType and
3987 // ToType have the same unqualified type (since we checked
3988 // qualifiers above), then this is a qualification conversion.
3989 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3990}
3991
3992/// - Determine whether this is a conversion from a scalar type to an
3993/// atomic type.
3994///
3995/// If successful, updates \c SCS's second and third steps in the conversion
3996/// sequence to finish the conversion.
3997static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3998 bool InOverloadResolution,
4000 bool CStyle) {
4001 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4002 if (!ToAtomic)
4003 return false;
4004
4006 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4007 InOverloadResolution, InnerSCS,
4008 CStyle, /*AllowObjCWritebackConversion=*/false))
4009 return false;
4010
4011 SCS.Second = InnerSCS.Second;
4012 SCS.setToType(1, InnerSCS.getToType(1));
4013 SCS.Third = InnerSCS.Third;
4016 SCS.setToType(2, InnerSCS.getToType(2));
4017 return true;
4018}
4019
4021 QualType ToType,
4022 bool InOverloadResolution,
4024 bool CStyle) {
4025 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4026 if (!ToOBT)
4027 return false;
4028
4029 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4030 QualType FromType = From->getType();
4031 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4032 return false;
4033
4035 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4036 InOverloadResolution, InnerSCS, CStyle,
4037 /*AllowObjCWritebackConversion=*/false))
4038 return false;
4039
4040 SCS.Second = InnerSCS.Second;
4041 SCS.setToType(1, InnerSCS.getToType(1));
4042 SCS.Third = InnerSCS.Third;
4045 SCS.setToType(2, InnerSCS.getToType(2));
4046 return true;
4047}
4048
4051 QualType Type) {
4052 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4053 if (CtorType->getNumParams() > 0) {
4054 QualType FirstArg = CtorType->getParamType(0);
4055 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4056 return true;
4057 }
4058 return false;
4059}
4060
4061static OverloadingResult
4063 CXXRecordDecl *To,
4065 OverloadCandidateSet &CandidateSet,
4066 bool AllowExplicit) {
4068 for (auto *D : S.LookupConstructors(To)) {
4069 auto Info = getConstructorInfo(D);
4070 if (!Info)
4071 continue;
4072
4073 bool Usable = !Info.Constructor->isInvalidDecl() &&
4074 S.isInitListConstructor(Info.Constructor);
4075 if (Usable) {
4076 bool SuppressUserConversions = false;
4077 if (Info.ConstructorTmpl)
4078 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4079 /*ExplicitArgs*/ nullptr, From,
4080 CandidateSet, SuppressUserConversions,
4081 /*PartialOverloading*/ false,
4082 AllowExplicit);
4083 else
4084 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false, AllowExplicit);
4087 }
4088 }
4089
4090 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4091
4093 switch (auto Result =
4094 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4095 case OR_Deleted:
4096 case OR_Success: {
4097 // Record the standard conversion we used and the conversion function.
4099 QualType ThisType = Constructor->getFunctionObjectParameterType();
4100 // Initializer lists don't have conversions as such.
4102 User.HadMultipleCandidates = HadMultipleCandidates;
4104 User.FoundConversionFunction = Best->FoundDecl;
4106 User.After.setFromType(ThisType);
4107 User.After.setAllToTypes(ToType);
4108 return Result;
4109 }
4110
4112 return OR_No_Viable_Function;
4113 case OR_Ambiguous:
4114 return OR_Ambiguous;
4115 }
4116
4117 llvm_unreachable("Invalid OverloadResult!");
4118}
4119
4120/// Determines whether there is a user-defined conversion sequence
4121/// (C++ [over.ics.user]) that converts expression From to the type
4122/// ToType. If such a conversion exists, User will contain the
4123/// user-defined conversion sequence that performs such a conversion
4124/// and this routine will return true. Otherwise, this routine returns
4125/// false and User is unspecified.
4126///
4127/// \param AllowExplicit true if the conversion should consider C++0x
4128/// "explicit" conversion functions as well as non-explicit conversion
4129/// functions (C++0x [class.conv.fct]p2).
4130///
4131/// \param AllowObjCConversionOnExplicit true if the conversion should
4132/// allow an extra Objective-C pointer conversion on uses of explicit
4133/// constructors. Requires \c AllowExplicit to also be set.
4134static OverloadingResult
4137 OverloadCandidateSet &CandidateSet,
4138 AllowedExplicit AllowExplicit,
4139 bool AllowObjCConversionOnExplicit) {
4140 assert(AllowExplicit != AllowedExplicit::None ||
4141 !AllowObjCConversionOnExplicit);
4143
4144 // Whether we will only visit constructors.
4145 bool ConstructorsOnly = false;
4146
4147 // If the type we are conversion to is a class type, enumerate its
4148 // constructors.
4149 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4150 // C++ [over.match.ctor]p1:
4151 // When objects of class type are direct-initialized (8.5), or
4152 // copy-initialized from an expression of the same or a
4153 // derived class type (8.5), overload resolution selects the
4154 // constructor. [...] For copy-initialization, the candidate
4155 // functions are all the converting constructors (12.3.1) of
4156 // that class. The argument list is the expression-list within
4157 // the parentheses of the initializer.
4158 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4159 (From->getType()->isRecordType() &&
4160 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4161 ConstructorsOnly = true;
4162
4163 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4164 // We're not going to find any constructors.
4165 } else if (auto *ToRecordDecl =
4166 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4167 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4168
4169 Expr **Args = &From;
4170 unsigned NumArgs = 1;
4171 bool ListInitializing = false;
4172 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4173 // But first, see if there is an init-list-constructor that will work.
4175 S, From, ToType, ToRecordDecl, User, CandidateSet,
4176 AllowExplicit == AllowedExplicit::All);
4178 return Result;
4179 // Never mind.
4180 CandidateSet.clear(
4182
4183 // If we're list-initializing, we pass the individual elements as
4184 // arguments, not the entire list.
4185 Args = InitList->getInits();
4186 NumArgs = InitList->getNumInits();
4187 ListInitializing = true;
4188 }
4189
4190 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4191 auto Info = getConstructorInfo(D);
4192 if (!Info)
4193 continue;
4194
4195 bool Usable = !Info.Constructor->isInvalidDecl();
4196 if (!ListInitializing)
4197 Usable = Usable && Info.Constructor->isConvertingConstructor(
4198 /*AllowExplicit*/ true);
4199 if (Usable) {
4200 bool SuppressUserConversions = !ConstructorsOnly;
4201 // C++20 [over.best.ics.general]/4.5:
4202 // if the target is the first parameter of a constructor [of class
4203 // X] and the constructor [...] is a candidate by [...] the second
4204 // phase of [over.match.list] when the initializer list has exactly
4205 // one element that is itself an initializer list, [...] and the
4206 // conversion is to X or reference to cv X, user-defined conversion
4207 // sequences are not considered.
4208 if (SuppressUserConversions && ListInitializing) {
4209 SuppressUserConversions =
4210 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4211 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4212 ToType);
4213 }
4214 if (Info.ConstructorTmpl)
4216 Info.ConstructorTmpl, Info.FoundDecl,
4217 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4218 CandidateSet, SuppressUserConversions,
4219 /*PartialOverloading*/ false,
4220 AllowExplicit == AllowedExplicit::All);
4221 else
4222 // Allow one user-defined conversion when user specifies a
4223 // From->ToType conversion via an static cast (c-style, etc).
4224 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4225 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4226 SuppressUserConversions,
4227 /*PartialOverloading*/ false,
4228 AllowExplicit == AllowedExplicit::All);
4229 }
4230 }
4231 }
4232 }
4233
4234 // Enumerate conversion functions, if we're allowed to.
4235 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4236 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4237 // No conversion functions from incomplete types.
4238 } else if (const RecordType *FromRecordType =
4239 From->getType()->getAsCanonical<RecordType>()) {
4240 if (auto *FromRecordDecl =
4241 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4242 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4243 // Add all of the conversion functions as candidates.
4244 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4245 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4246 DeclAccessPair FoundDecl = I.getPair();
4247 NamedDecl *D = FoundDecl.getDecl();
4248 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4249 if (isa<UsingShadowDecl>(D))
4250 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4251
4252 CXXConversionDecl *Conv;
4253 FunctionTemplateDecl *ConvTemplate;
4254 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4255 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4256 else
4257 Conv = cast<CXXConversionDecl>(D);
4258
4259 if (ConvTemplate)
4261 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4262 CandidateSet, AllowObjCConversionOnExplicit,
4263 AllowExplicit != AllowedExplicit::None);
4264 else
4265 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4266 CandidateSet, AllowObjCConversionOnExplicit,
4267 AllowExplicit != AllowedExplicit::None);
4268 }
4269 }
4270 }
4271
4272 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4273
4275 switch (auto Result =
4276 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4277 case OR_Success:
4278 case OR_Deleted:
4279 // Record the standard conversion we used and the conversion function.
4281 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4282 // C++ [over.ics.user]p1:
4283 // If the user-defined conversion is specified by a
4284 // constructor (12.3.1), the initial standard conversion
4285 // sequence converts the source type to the type required by
4286 // the argument of the constructor.
4287 //
4288 if (isa<InitListExpr>(From)) {
4289 // Initializer lists don't have conversions as such.
4291 User.Before.FromBracedInitList = true;
4292 } else {
4293 if (Best->Conversions[0].isEllipsis())
4294 User.EllipsisConversion = true;
4295 else {
4296 User.Before = Best->Conversions[0].Standard;
4297 User.EllipsisConversion = false;
4298 }
4299 }
4300 User.HadMultipleCandidates = HadMultipleCandidates;
4302 User.FoundConversionFunction = Best->FoundDecl;
4304 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4305 User.After.setAllToTypes(ToType);
4306 return Result;
4307 }
4308 if (CXXConversionDecl *Conversion
4309 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4310
4311 assert(Best->HasFinalConversion);
4312
4313 // C++ [over.ics.user]p1:
4314 //
4315 // [...] If the user-defined conversion is specified by a
4316 // conversion function (12.3.2), the initial standard
4317 // conversion sequence converts the source type to the
4318 // implicit object parameter of the conversion function.
4319 User.Before = Best->Conversions[0].Standard;
4320 User.HadMultipleCandidates = HadMultipleCandidates;
4321 User.ConversionFunction = Conversion;
4322 User.FoundConversionFunction = Best->FoundDecl;
4323 User.EllipsisConversion = false;
4324
4325 // C++ [over.ics.user]p2:
4326 // The second standard conversion sequence converts the
4327 // result of the user-defined conversion to the target type
4328 // for the sequence. Since an implicit conversion sequence
4329 // is an initialization, the special rules for
4330 // initialization by user-defined conversion apply when
4331 // selecting the best user-defined conversion for a
4332 // user-defined conversion sequence (see 13.3.3 and
4333 // 13.3.3.1).
4334 User.After = Best->FinalConversion;
4335 return Result;
4336 }
4337 llvm_unreachable("Not a constructor or conversion function?");
4338
4340 return OR_No_Viable_Function;
4341
4342 case OR_Ambiguous:
4343 return OR_Ambiguous;
4344 }
4345
4346 llvm_unreachable("Invalid OverloadResult!");
4347}
4348
4349bool
4352 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4354 OverloadingResult OvResult =
4355 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4356 CandidateSet, AllowedExplicit::None, false);
4357
4358 if (!(OvResult == OR_Ambiguous ||
4359 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4360 return false;
4361
4362 auto Cands = CandidateSet.CompleteCandidates(
4363 *this,
4365 From);
4366 if (OvResult == OR_Ambiguous)
4367 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4368 << From->getType() << ToType << From->getSourceRange();
4369 else { // OR_No_Viable_Function && !CandidateSet.empty()
4370 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4371 diag::err_typecheck_nonviable_condition_incomplete,
4372 From->getType(), From->getSourceRange()))
4373 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4374 << false << From->getType() << From->getSourceRange() << ToType;
4375 }
4376
4377 CandidateSet.NoteCandidates(
4378 *this, From, Cands);
4379 return true;
4380}
4381
4382// Helper for compareConversionFunctions that gets the FunctionType that the
4383// conversion-operator return value 'points' to, or nullptr.
4384static const FunctionType *
4386 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4387 const PointerType *RetPtrTy =
4388 ConvFuncTy->getReturnType()->getAs<PointerType>();
4389
4390 if (!RetPtrTy)
4391 return nullptr;
4392
4393 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4394}
4395
4396/// Compare the user-defined conversion functions or constructors
4397/// of two user-defined conversion sequences to determine whether any ordering
4398/// is possible.
4401 FunctionDecl *Function2) {
4402 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4403 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4404 if (!Conv1 || !Conv2)
4406
4407 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4409
4410 // Objective-C++:
4411 // If both conversion functions are implicitly-declared conversions from
4412 // a lambda closure type to a function pointer and a block pointer,
4413 // respectively, always prefer the conversion to a function pointer,
4414 // because the function pointer is more lightweight and is more likely
4415 // to keep code working.
4416 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4417 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4418 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4419 if (Block1 != Block2)
4420 return Block1 ? ImplicitConversionSequence::Worse
4422 }
4423
4424 // In order to support multiple calling conventions for the lambda conversion
4425 // operator (such as when the free and member function calling convention is
4426 // different), prefer the 'free' mechanism, followed by the calling-convention
4427 // of operator(). The latter is in place to support the MSVC-like solution of
4428 // defining ALL of the possible conversions in regards to calling-convention.
4429 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4430 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4431
4432 if (Conv1FuncRet && Conv2FuncRet &&
4433 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4434 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4435 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4436
4437 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4438 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4439
4440 CallingConv CallOpCC =
4441 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4443 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4445 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4446
4447 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4448 for (CallingConv CC : PrefOrder) {
4449 if (Conv1CC == CC)
4451 if (Conv2CC == CC)
4453 }
4454 }
4455
4457}
4458
4465
4466/// CompareImplicitConversionSequences - Compare two implicit
4467/// conversion sequences to determine whether one is better than the
4468/// other or if they are indistinguishable (C++ 13.3.3.2).
4471 const ImplicitConversionSequence& ICS1,
4472 const ImplicitConversionSequence& ICS2)
4473{
4474 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4475 // conversion sequences (as defined in 13.3.3.1)
4476 // -- a standard conversion sequence (13.3.3.1.1) is a better
4477 // conversion sequence than a user-defined conversion sequence or
4478 // an ellipsis conversion sequence, and
4479 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4480 // conversion sequence than an ellipsis conversion sequence
4481 // (13.3.3.1.3).
4482 //
4483 // C++0x [over.best.ics]p10:
4484 // For the purpose of ranking implicit conversion sequences as
4485 // described in 13.3.3.2, the ambiguous conversion sequence is
4486 // treated as a user-defined sequence that is indistinguishable
4487 // from any other user-defined conversion sequence.
4488
4489 // String literal to 'char *' conversion has been deprecated in C++03. It has
4490 // been removed from C++11. We still accept this conversion, if it happens at
4491 // the best viable function. Otherwise, this conversion is considered worse
4492 // than ellipsis conversion. Consider this as an extension; this is not in the
4493 // standard. For example:
4494 //
4495 // int &f(...); // #1
4496 // void f(char*); // #2
4497 // void g() { int &r = f("foo"); }
4498 //
4499 // In C++03, we pick #2 as the best viable function.
4500 // In C++11, we pick #1 as the best viable function, because ellipsis
4501 // conversion is better than string-literal to char* conversion (since there
4502 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4503 // convert arguments, #2 would be the best viable function in C++11.
4504 // If the best viable function has this conversion, a warning will be issued
4505 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4506
4507 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4510 // Ill-formedness must not differ
4511 ICS1.isBad() == ICS2.isBad())
4515
4516 if (ICS1.getKindRank() < ICS2.getKindRank())
4518 if (ICS2.getKindRank() < ICS1.getKindRank())
4520
4521 // The following checks require both conversion sequences to be of
4522 // the same kind.
4523 if (ICS1.getKind() != ICS2.getKind())
4525
4528
4529 // Two implicit conversion sequences of the same form are
4530 // indistinguishable conversion sequences unless one of the
4531 // following rules apply: (C++ 13.3.3.2p3):
4532
4533 // List-initialization sequence L1 is a better conversion sequence than
4534 // list-initialization sequence L2 if:
4535 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4536 // if not that,
4537 // — L1 and L2 convert to arrays of the same element type, and either the
4538 // number of elements n_1 initialized by L1 is less than the number of
4539 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4540 // an array of unknown bound and L1 does not,
4541 // even if one of the other rules in this paragraph would otherwise apply.
4542 if (!ICS1.isBad()) {
4543 bool StdInit1 = false, StdInit2 = false;
4546 nullptr);
4549 nullptr);
4550 if (StdInit1 != StdInit2)
4551 return StdInit1 ? ImplicitConversionSequence::Better
4553
4556 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4558 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4560 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4561 CAT2->getElementType())) {
4562 // Both to arrays of the same element type
4563 if (CAT1->getSize() != CAT2->getSize())
4564 // Different sized, the smaller wins
4565 return CAT1->getSize().ult(CAT2->getSize())
4570 // One is incomplete, it loses
4574 }
4575 }
4576 }
4577
4578 if (ICS1.isStandard())
4579 // Standard conversion sequence S1 is a better conversion sequence than
4580 // standard conversion sequence S2 if [...]
4582 ICS1.Standard, ICS2.Standard);
4583 else if (ICS1.isUserDefined()) {
4584 // With lazy template loading, it is possible to find non-canonical
4585 // FunctionDecls, depending on when redecl chains are completed. Make sure
4586 // to compare the canonical decls of conversion functions. This avoids
4587 // ambiguity problems for templated conversion operators.
4588 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4589 if (ConvFunc1)
4590 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4591 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4592 if (ConvFunc2)
4593 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4594 // User-defined conversion sequence U1 is a better conversion
4595 // sequence than another user-defined conversion sequence U2 if
4596 // they contain the same user-defined conversion function or
4597 // constructor and if the second standard conversion sequence of
4598 // U1 is better than the second standard conversion sequence of
4599 // U2 (C++ 13.3.3.2p3).
4600 if (ConvFunc1 == ConvFunc2)
4602 ICS1.UserDefined.After,
4603 ICS2.UserDefined.After);
4604 else
4608 }
4609
4610 return Result;
4611}
4612
4613// Per 13.3.3.2p3, compare the given standard conversion sequences to
4614// determine if one is a proper subset of the other.
4617 const StandardConversionSequence& SCS1,
4618 const StandardConversionSequence& SCS2) {
4621
4622 // the identity conversion sequence is considered to be a subsequence of
4623 // any non-identity conversion sequence
4624 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4626 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4628
4629 if (SCS1.Second != SCS2.Second) {
4630 if (SCS1.Second == ICK_Identity)
4632 else if (SCS2.Second == ICK_Identity)
4634 else
4636 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4638
4639 if (SCS1.Third == SCS2.Third) {
4640 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4642 }
4643
4644 if (SCS1.Third == ICK_Identity)
4648
4649 if (SCS2.Third == ICK_Identity)
4653
4655}
4656
4657/// Determine whether one of the given reference bindings is better
4658/// than the other based on what kind of bindings they are.
4659static bool
4661 const StandardConversionSequence &SCS2) {
4662 // C++0x [over.ics.rank]p3b4:
4663 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4664 // implicit object parameter of a non-static member function declared
4665 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4666 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4667 // lvalue reference to a function lvalue and S2 binds an rvalue
4668 // reference*.
4669 //
4670 // FIXME: Rvalue references. We're going rogue with the above edits,
4671 // because the semantics in the current C++0x working paper (N3225 at the
4672 // time of this writing) break the standard definition of std::forward
4673 // and std::reference_wrapper when dealing with references to functions.
4674 // Proposed wording changes submitted to CWG for consideration.
4677 return false;
4678
4679 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4680 SCS2.IsLvalueReference) ||
4683}
4684
4690
4691/// Returns kind of fixed enum promotion the \a SCS uses.
4692static FixedEnumPromotion
4694
4695 if (SCS.Second != ICK_Integral_Promotion)
4697
4698 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4699 if (!Enum)
4701
4702 if (!Enum->isFixed())
4704
4705 QualType UnderlyingType = Enum->getIntegerType();
4706 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4708
4710}
4711
4712/// CompareStandardConversionSequences - Compare two standard
4713/// conversion sequences to determine whether one is better than the
4714/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4717 const StandardConversionSequence& SCS1,
4718 const StandardConversionSequence& SCS2)
4719{
4720 // Standard conversion sequence S1 is a better conversion sequence
4721 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4722
4723 // -- S1 is a proper subsequence of S2 (comparing the conversion
4724 // sequences in the canonical form defined by 13.3.3.1.1,
4725 // excluding any Lvalue Transformation; the identity conversion
4726 // sequence is considered to be a subsequence of any
4727 // non-identity conversion sequence) or, if not that,
4730 return CK;
4731
4732 // -- the rank of S1 is better than the rank of S2 (by the rules
4733 // defined below), or, if not that,
4734 ImplicitConversionRank Rank1 = SCS1.getRank();
4735 ImplicitConversionRank Rank2 = SCS2.getRank();
4736 if (Rank1 < Rank2)
4738 else if (Rank2 < Rank1)
4740
4741 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4742 // are indistinguishable unless one of the following rules
4743 // applies:
4744
4745 // A conversion that is not a conversion of a pointer, or
4746 // pointer to member, to bool is better than another conversion
4747 // that is such a conversion.
4749 return SCS2.isPointerConversionToBool()
4752
4753 // C++14 [over.ics.rank]p4b2:
4754 // This is retroactively applied to C++11 by CWG 1601.
4755 //
4756 // A conversion that promotes an enumeration whose underlying type is fixed
4757 // to its underlying type is better than one that promotes to the promoted
4758 // underlying type, if the two are different.
4761 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4762 FEP1 != FEP2)
4766
4767 // C++ [over.ics.rank]p4b2:
4768 //
4769 // If class B is derived directly or indirectly from class A,
4770 // conversion of B* to A* is better than conversion of B* to
4771 // void*, and conversion of A* to void* is better than conversion
4772 // of B* to void*.
4773 bool SCS1ConvertsToVoid
4775 bool SCS2ConvertsToVoid
4777 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4778 // Exactly one of the conversion sequences is a conversion to
4779 // a void pointer; it's the worse conversion.
4780 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4782 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4783 // Neither conversion sequence converts to a void pointer; compare
4784 // their derived-to-base conversions.
4786 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4787 return DerivedCK;
4788 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4789 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4790 // Both conversion sequences are conversions to void
4791 // pointers. Compare the source types to determine if there's an
4792 // inheritance relationship in their sources.
4793 QualType FromType1 = SCS1.getFromType();
4794 QualType FromType2 = SCS2.getFromType();
4795
4796 // Adjust the types we're converting from via the array-to-pointer
4797 // conversion, if we need to.
4798 if (SCS1.First == ICK_Array_To_Pointer)
4799 FromType1 = S.Context.getArrayDecayedType(FromType1);
4800 if (SCS2.First == ICK_Array_To_Pointer)
4801 FromType2 = S.Context.getArrayDecayedType(FromType2);
4802
4803 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4804 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4805
4806 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4808 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4810
4811 // Objective-C++: If one interface is more specific than the
4812 // other, it is the better one.
4813 const ObjCObjectPointerType* FromObjCPtr1
4814 = FromType1->getAs<ObjCObjectPointerType>();
4815 const ObjCObjectPointerType* FromObjCPtr2
4816 = FromType2->getAs<ObjCObjectPointerType>();
4817 if (FromObjCPtr1 && FromObjCPtr2) {
4818 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4819 FromObjCPtr2);
4820 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4821 FromObjCPtr1);
4822 if (AssignLeft != AssignRight) {
4823 return AssignLeft? ImplicitConversionSequence::Better
4825 }
4826 }
4827 }
4828
4829 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4830 // Check for a better reference binding based on the kind of bindings.
4831 if (isBetterReferenceBindingKind(SCS1, SCS2))
4833 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4835 }
4836
4837 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4838 // bullet 3).
4840 = CompareQualificationConversions(S, SCS1, SCS2))
4841 return QualCK;
4842
4845 return ObtCK;
4846
4847 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4848 // C++ [over.ics.rank]p3b4:
4849 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4850 // which the references refer are the same type except for
4851 // top-level cv-qualifiers, and the type to which the reference
4852 // initialized by S2 refers is more cv-qualified than the type
4853 // to which the reference initialized by S1 refers.
4854 QualType T1 = SCS1.getToType(2);
4855 QualType T2 = SCS2.getToType(2);
4856 T1 = S.Context.getCanonicalType(T1);
4857 T2 = S.Context.getCanonicalType(T2);
4858 Qualifiers T1Quals, T2Quals;
4859 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4860 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4861 if (UnqualT1 == UnqualT2) {
4862 // Objective-C++ ARC: If the references refer to objects with different
4863 // lifetimes, prefer bindings that don't change lifetime.
4869 }
4870
4871 // If the type is an array type, promote the element qualifiers to the
4872 // type for comparison.
4873 if (isa<ArrayType>(T1) && T1Quals)
4874 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4875 if (isa<ArrayType>(T2) && T2Quals)
4876 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4877 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4879 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4881 }
4882 }
4883
4884 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4885 // floating-to-integral conversion if the integral conversion
4886 // is between types of the same size.
4887 // For example:
4888 // void f(float);
4889 // void f(int);
4890 // int main {
4891 // long a;
4892 // f(a);
4893 // }
4894 // Here, MSVC will call f(int) instead of generating a compile error
4895 // as clang will do in standard mode.
4896 if (S.getLangOpts().MSVCCompat &&
4899 SCS2.Second == ICK_Floating_Integral &&
4900 S.Context.getTypeSize(SCS1.getFromType()) ==
4901 S.Context.getTypeSize(SCS1.getToType(2)))
4903
4904 // Prefer a compatible vector conversion over a lax vector conversion
4905 // For example:
4906 //
4907 // typedef float __v4sf __attribute__((__vector_size__(16)));
4908 // void f(vector float);
4909 // void f(vector signed int);
4910 // int main() {
4911 // __v4sf a;
4912 // f(a);
4913 // }
4914 // Here, we'd like to choose f(vector float) and not
4915 // report an ambiguous call error
4916 if (SCS1.Second == ICK_Vector_Conversion &&
4917 SCS2.Second == ICK_Vector_Conversion) {
4918 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4919 SCS1.getFromType(), SCS1.getToType(2));
4920 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4921 SCS2.getFromType(), SCS2.getToType(2));
4922
4923 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4924 return SCS1IsCompatibleVectorConversion
4927 }
4928
4929 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4931 bool SCS1IsCompatibleSVEVectorConversion =
4932 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4933 bool SCS2IsCompatibleSVEVectorConversion =
4934 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4935
4936 if (SCS1IsCompatibleSVEVectorConversion !=
4937 SCS2IsCompatibleSVEVectorConversion)
4938 return SCS1IsCompatibleSVEVectorConversion
4941 }
4942
4943 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4945 bool SCS1IsCompatibleRVVVectorConversion =
4947 bool SCS2IsCompatibleRVVVectorConversion =
4949
4950 if (SCS1IsCompatibleRVVVectorConversion !=
4951 SCS2IsCompatibleRVVVectorConversion)
4952 return SCS1IsCompatibleRVVVectorConversion
4955 }
4957}
4958
4959/// CompareOverflowBehaviorConversions - Compares two standard conversion
4960/// sequences to determine whether they can be ranked based on their
4961/// OverflowBehaviorType's underlying type.
4977
4978/// CompareQualificationConversions - Compares two standard conversion
4979/// sequences to determine whether they can be ranked based on their
4980/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4983 const StandardConversionSequence& SCS1,
4984 const StandardConversionSequence& SCS2) {
4985 // C++ [over.ics.rank]p3:
4986 // -- S1 and S2 differ only in their qualification conversion and
4987 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4988 // [C++98]
4989 // [...] and the cv-qualification signature of type T1 is a proper subset
4990 // of the cv-qualification signature of type T2, and S1 is not the
4991 // deprecated string literal array-to-pointer conversion (4.2).
4992 // [C++2a]
4993 // [...] where T1 can be converted to T2 by a qualification conversion.
4994 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4995 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4997
4998 // FIXME: the example in the standard doesn't use a qualification
4999 // conversion (!)
5000 QualType T1 = SCS1.getToType(2);
5001 QualType T2 = SCS2.getToType(2);
5002 T1 = S.Context.getCanonicalType(T1);
5003 T2 = S.Context.getCanonicalType(T2);
5004 assert(!T1->isReferenceType() && !T2->isReferenceType());
5005 Qualifiers T1Quals, T2Quals;
5006 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5007 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5008
5009 // If the types are the same, we won't learn anything by unwrapping
5010 // them.
5011 if (UnqualT1 == UnqualT2)
5013
5014 // Don't ever prefer a standard conversion sequence that uses the deprecated
5015 // string literal array to pointer conversion.
5016 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5017 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5018
5019 // Objective-C++ ARC:
5020 // Prefer qualification conversions not involving a change in lifetime
5021 // to qualification conversions that do change lifetime.
5024 CanPick1 = false;
5027 CanPick2 = false;
5028
5029 bool ObjCLifetimeConversion;
5030 if (CanPick1 &&
5031 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5032 CanPick1 = false;
5033 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5034 // directions, so we can't short-cut this second check in general.
5035 if (CanPick2 &&
5036 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5037 CanPick2 = false;
5038
5039 if (CanPick1 != CanPick2)
5040 return CanPick1 ? ImplicitConversionSequence::Better
5043}
5044
5045/// CompareDerivedToBaseConversions - Compares two standard conversion
5046/// sequences to determine whether they can be ranked based on their
5047/// various kinds of derived-to-base conversions (C++
5048/// [over.ics.rank]p4b3). As part of these checks, we also look at
5049/// conversions between Objective-C interface types.
5052 const StandardConversionSequence& SCS1,
5053 const StandardConversionSequence& SCS2) {
5054 QualType FromType1 = SCS1.getFromType();
5055 QualType ToType1 = SCS1.getToType(1);
5056 QualType FromType2 = SCS2.getFromType();
5057 QualType ToType2 = SCS2.getToType(1);
5058
5059 // Adjust the types we're converting from via the array-to-pointer
5060 // conversion, if we need to.
5061 if (SCS1.First == ICK_Array_To_Pointer)
5062 FromType1 = S.Context.getArrayDecayedType(FromType1);
5063 if (SCS2.First == ICK_Array_To_Pointer)
5064 FromType2 = S.Context.getArrayDecayedType(FromType2);
5065
5066 // Canonicalize all of the types.
5067 FromType1 = S.Context.getCanonicalType(FromType1);
5068 ToType1 = S.Context.getCanonicalType(ToType1);
5069 FromType2 = S.Context.getCanonicalType(FromType2);
5070 ToType2 = S.Context.getCanonicalType(ToType2);
5071
5072 // C++ [over.ics.rank]p4b3:
5073 //
5074 // If class B is derived directly or indirectly from class A and
5075 // class C is derived directly or indirectly from B,
5076 //
5077 // Compare based on pointer conversions.
5078 if (SCS1.Second == ICK_Pointer_Conversion &&
5080 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5081 FromType1->isPointerType() && FromType2->isPointerType() &&
5082 ToType1->isPointerType() && ToType2->isPointerType()) {
5083 QualType FromPointee1 =
5085 QualType ToPointee1 =
5087 QualType FromPointee2 =
5089 QualType ToPointee2 =
5091
5092 // -- conversion of C* to B* is better than conversion of C* to A*,
5093 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5094 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5096 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5098 }
5099
5100 // -- conversion of B* to A* is better than conversion of C* to A*,
5101 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5102 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5104 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5106 }
5107 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5109 const ObjCObjectPointerType *FromPtr1
5110 = FromType1->getAs<ObjCObjectPointerType>();
5111 const ObjCObjectPointerType *FromPtr2
5112 = FromType2->getAs<ObjCObjectPointerType>();
5113 const ObjCObjectPointerType *ToPtr1
5114 = ToType1->getAs<ObjCObjectPointerType>();
5115 const ObjCObjectPointerType *ToPtr2
5116 = ToType2->getAs<ObjCObjectPointerType>();
5117
5118 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5119 // Apply the same conversion ranking rules for Objective-C pointer types
5120 // that we do for C++ pointers to class types. However, we employ the
5121 // Objective-C pseudo-subtyping relationship used for assignment of
5122 // Objective-C pointer types.
5123 bool FromAssignLeft
5124 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5125 bool FromAssignRight
5126 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5127 bool ToAssignLeft
5128 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5129 bool ToAssignRight
5130 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5131
5132 // A conversion to an a non-id object pointer type or qualified 'id'
5133 // type is better than a conversion to 'id'.
5134 if (ToPtr1->isObjCIdType() &&
5135 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5137 if (ToPtr2->isObjCIdType() &&
5138 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5140
5141 // A conversion to a non-id object pointer type is better than a
5142 // conversion to a qualified 'id' type
5143 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5145 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5147
5148 // A conversion to an a non-Class object pointer type or qualified 'Class'
5149 // type is better than a conversion to 'Class'.
5150 if (ToPtr1->isObjCClassType() &&
5151 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5153 if (ToPtr2->isObjCClassType() &&
5154 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5156
5157 // A conversion to a non-Class object pointer type is better than a
5158 // conversion to a qualified 'Class' type.
5159 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5161 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5163
5164 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5165 if (S.Context.hasSameType(FromType1, FromType2) &&
5166 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5167 (ToAssignLeft != ToAssignRight)) {
5168 if (FromPtr1->isSpecialized()) {
5169 // "conversion of B<A> * to B * is better than conversion of B * to
5170 // C *.
5171 bool IsFirstSame =
5172 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5173 bool IsSecondSame =
5174 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5175 if (IsFirstSame) {
5176 if (!IsSecondSame)
5178 } else if (IsSecondSame)
5180 }
5181 return ToAssignLeft? ImplicitConversionSequence::Worse
5183 }
5184
5185 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5186 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5187 (FromAssignLeft != FromAssignRight))
5188 return FromAssignLeft? ImplicitConversionSequence::Better
5190 }
5191 }
5192
5193 // Ranking of member-pointer types.
5194 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5195 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5196 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5197 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5198 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5199 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5200 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5201 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5202 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5203 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5204 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5205 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5206 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5207 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5209 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5211 }
5212 // conversion of B::* to C::* is better than conversion of A::* to C::*
5213 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5214 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5216 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5218 }
5219 }
5220
5221 if (SCS1.Second == ICK_Derived_To_Base) {
5222 // -- conversion of C to B is better than conversion of C to A,
5223 // -- binding of an expression of type C to a reference of type
5224 // B& is better than binding an expression of type C to a
5225 // reference of type A&,
5226 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5227 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5228 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5230 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5232 }
5233
5234 // -- conversion of B to A is better than conversion of C to A.
5235 // -- binding of an expression of type B to a reference of type
5236 // A& is better than binding an expression of type C to a
5237 // reference of type A&,
5238 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5239 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5240 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5242 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5244 }
5245 }
5246
5248}
5249
5251 if (!T.getQualifiers().hasUnaligned())
5252 return T;
5253
5254 Qualifiers Q;
5255 T = Ctx.getUnqualifiedArrayType(T, Q);
5256 Q.removeUnaligned();
5257 return Ctx.getQualifiedType(T, Q);
5258}
5259
5262 QualType OrigT1, QualType OrigT2,
5263 ReferenceConversions *ConvOut) {
5264 assert(!OrigT1->isReferenceType() &&
5265 "T1 must be the pointee type of the reference type");
5266 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5267
5268 QualType T1 = Context.getCanonicalType(OrigT1);
5269 QualType T2 = Context.getCanonicalType(OrigT2);
5270 Qualifiers T1Quals, T2Quals;
5271 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5272 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5273
5274 ReferenceConversions ConvTmp;
5275 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5276 Conv = ReferenceConversions();
5277
5278 // C++2a [dcl.init.ref]p4:
5279 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5280 // reference-related to "cv2 T2" if T1 is similar to T2, or
5281 // T1 is a base class of T2.
5282 // "cv1 T1" is reference-compatible with "cv2 T2" if
5283 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5284 // "pointer to cv1 T1" via a standard conversion sequence.
5285
5286 // Check for standard conversions we can apply to pointers: derived-to-base
5287 // conversions, ObjC pointer conversions, and function pointer conversions.
5288 // (Qualification conversions are checked last.)
5289 if (UnqualT1 == UnqualT2) {
5290 // Nothing to do.
5291 } else if (isCompleteType(Loc, OrigT2) &&
5292 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5293 Conv |= ReferenceConversions::DerivedToBase;
5294 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5295 UnqualT2->isObjCObjectOrInterfaceType() &&
5296 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5297 Conv |= ReferenceConversions::ObjC;
5298 else if (UnqualT2->isFunctionType() &&
5299 IsFunctionConversion(UnqualT2, UnqualT1)) {
5300 Conv |= ReferenceConversions::Function;
5301 // No need to check qualifiers; function types don't have them.
5302 return Ref_Compatible;
5303 }
5304 bool ConvertedReferent = Conv != 0;
5305
5306 // We can have a qualification conversion. Compute whether the types are
5307 // similar at the same time.
5308 bool PreviousToQualsIncludeConst = true;
5309 bool TopLevel = true;
5310 do {
5311 if (T1 == T2)
5312 break;
5313
5314 // We will need a qualification conversion.
5315 Conv |= ReferenceConversions::Qualification;
5316
5317 // Track whether we performed a qualification conversion anywhere other
5318 // than the top level. This matters for ranking reference bindings in
5319 // overload resolution.
5320 if (!TopLevel)
5321 Conv |= ReferenceConversions::NestedQualification;
5322
5323 // MS compiler ignores __unaligned qualifier for references; do the same.
5324 T1 = withoutUnaligned(Context, T1);
5325 T2 = withoutUnaligned(Context, T2);
5326
5327 // If we find a qualifier mismatch, the types are not reference-compatible,
5328 // but are still be reference-related if they're similar.
5329 bool ObjCLifetimeConversion = false;
5330 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5331 PreviousToQualsIncludeConst,
5332 ObjCLifetimeConversion, getASTContext()))
5333 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5334 ? Ref_Related
5336
5337 // FIXME: Should we track this for any level other than the first?
5338 if (ObjCLifetimeConversion)
5339 Conv |= ReferenceConversions::ObjCLifetime;
5340
5341 TopLevel = false;
5342 } while (Context.UnwrapSimilarTypes(T1, T2));
5343
5344 // At this point, if the types are reference-related, we must either have the
5345 // same inner type (ignoring qualifiers), or must have already worked out how
5346 // to convert the referent.
5347 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5350}
5351
5352/// Look for a user-defined conversion to a value reference-compatible
5353/// with DeclType. Return true if something definite is found.
5354static bool
5356 QualType DeclType, SourceLocation DeclLoc,
5357 Expr *Init, QualType T2, bool AllowRvalues,
5358 bool AllowExplicit) {
5359 assert(T2->isRecordType() && "Can only find conversions of record types.");
5360 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5361 OverloadCandidateSet CandidateSet(
5363 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5364 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5365 NamedDecl *D = *I;
5367 if (isa<UsingShadowDecl>(D))
5368 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5369
5370 FunctionTemplateDecl *ConvTemplate
5371 = dyn_cast<FunctionTemplateDecl>(D);
5372 CXXConversionDecl *Conv;
5373 if (ConvTemplate)
5374 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5375 else
5376 Conv = cast<CXXConversionDecl>(D);
5377
5378 if (AllowRvalues) {
5379 // If we are initializing an rvalue reference, don't permit conversion
5380 // functions that return lvalues.
5381 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5382 const ReferenceType *RefType
5384 if (RefType && !RefType->getPointeeType()->isFunctionType())
5385 continue;
5386 }
5387
5388 if (!ConvTemplate &&
5390 DeclLoc,
5391 Conv->getConversionType()
5396 continue;
5397 } else {
5398 // If the conversion function doesn't return a reference type,
5399 // it can't be considered for this conversion. An rvalue reference
5400 // is only acceptable if its referencee is a function type.
5401
5402 const ReferenceType *RefType =
5404 if (!RefType ||
5405 (!RefType->isLValueReferenceType() &&
5406 !RefType->getPointeeType()->isFunctionType()))
5407 continue;
5408 }
5409
5410 if (ConvTemplate)
5412 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5413 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5414 else
5416 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5417 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5418 }
5419
5420 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5421
5423 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5424 case OR_Success:
5425
5426 assert(Best->HasFinalConversion);
5427
5428 // C++ [over.ics.ref]p1:
5429 //
5430 // [...] If the parameter binds directly to the result of
5431 // applying a conversion function to the argument
5432 // expression, the implicit conversion sequence is a
5433 // user-defined conversion sequence (13.3.3.1.2), with the
5434 // second standard conversion sequence either an identity
5435 // conversion or, if the conversion function returns an
5436 // entity of a type that is a derived class of the parameter
5437 // type, a derived-to-base Conversion.
5438 if (!Best->FinalConversion.DirectBinding)
5439 return false;
5440
5441 ICS.setUserDefined();
5442 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5443 ICS.UserDefined.After = Best->FinalConversion;
5444 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5445 ICS.UserDefined.ConversionFunction = Best->Function;
5446 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5447 ICS.UserDefined.EllipsisConversion = false;
5448 assert(ICS.UserDefined.After.ReferenceBinding &&
5450 "Expected a direct reference binding!");
5451 return true;
5452
5453 case OR_Ambiguous:
5454 ICS.setAmbiguous();
5455 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5456 Cand != CandidateSet.end(); ++Cand)
5457 if (Cand->Best)
5458 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5459 return true;
5460
5462 case OR_Deleted:
5463 // There was no suitable conversion, or we found a deleted
5464 // conversion; continue with other checks.
5465 return false;
5466 }
5467
5468 llvm_unreachable("Invalid OverloadResult!");
5469}
5470
5471/// Compute an implicit conversion sequence for reference
5472/// initialization.
5473static ImplicitConversionSequence
5475 SourceLocation DeclLoc,
5476 bool SuppressUserConversions,
5477 bool AllowExplicit) {
5478 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5479
5480 // Most paths end in a failed conversion.
5483
5484 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5485 QualType T2 = Init->getType();
5486
5487 // If the initializer is the address of an overloaded function, try
5488 // to resolve the overloaded function. If all goes well, T2 is the
5489 // type of the resulting function.
5490 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5493 false, Found))
5494 T2 = Fn->getType();
5495 }
5496
5497 // Compute some basic properties of the types and the initializer.
5498 bool isRValRef = DeclType->isRValueReferenceType();
5499 Expr::Classification InitCategory = Init->Classify(S.Context);
5500
5502 Sema::ReferenceCompareResult RefRelationship =
5503 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5504
5505 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5506 ICS.setStandard();
5508 // FIXME: A reference binding can be a function conversion too. We should
5509 // consider that when ordering reference-to-function bindings.
5510 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5512 : (RefConv & Sema::ReferenceConversions::ObjC)
5514 : ICK_Identity;
5516 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5517 // a reference binding that performs a non-top-level qualification
5518 // conversion as a qualification conversion, not as an identity conversion.
5519 ICS.Standard.Third = (RefConv &
5520 Sema::ReferenceConversions::NestedQualification)
5522 : ICK_Identity;
5523 ICS.Standard.setFromType(T2);
5524 ICS.Standard.setToType(0, T2);
5525 ICS.Standard.setToType(1, T1);
5526 ICS.Standard.setToType(2, T1);
5527 ICS.Standard.ReferenceBinding = true;
5528 ICS.Standard.DirectBinding = BindsDirectly;
5529 ICS.Standard.IsLvalueReference = !isRValRef;
5531 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5534 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5535 ICS.Standard.FromBracedInitList = false;
5536 ICS.Standard.CopyConstructor = nullptr;
5538 };
5539
5540 // C++0x [dcl.init.ref]p5:
5541 // A reference to type "cv1 T1" is initialized by an expression
5542 // of type "cv2 T2" as follows:
5543
5544 // -- If reference is an lvalue reference and the initializer expression
5545 if (!isRValRef) {
5546 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5547 // reference-compatible with "cv2 T2," or
5548 //
5549 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5550 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5551 // C++ [over.ics.ref]p1:
5552 // When a parameter of reference type binds directly (8.5.3)
5553 // to an argument expression, the implicit conversion sequence
5554 // is the identity conversion, unless the argument expression
5555 // has a type that is a derived class of the parameter type,
5556 // in which case the implicit conversion sequence is a
5557 // derived-to-base Conversion (13.3.3.1).
5558 SetAsReferenceBinding(/*BindsDirectly=*/true);
5559
5560 // Nothing more to do: the inaccessibility/ambiguity check for
5561 // derived-to-base conversions is suppressed when we're
5562 // computing the implicit conversion sequence (C++
5563 // [over.best.ics]p2).
5564 return ICS;
5565 }
5566
5567 // -- has a class type (i.e., T2 is a class type), where T1 is
5568 // not reference-related to T2, and can be implicitly
5569 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5570 // is reference-compatible with "cv3 T3" 92) (this
5571 // conversion is selected by enumerating the applicable
5572 // conversion functions (13.3.1.6) and choosing the best
5573 // one through overload resolution (13.3)),
5574 if (!SuppressUserConversions && T2->isRecordType() &&
5575 S.isCompleteType(DeclLoc, T2) &&
5576 RefRelationship == Sema::Ref_Incompatible) {
5577 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5578 Init, T2, /*AllowRvalues=*/false,
5579 AllowExplicit))
5580 return ICS;
5581 }
5582 }
5583
5584 // -- Otherwise, the reference shall be an lvalue reference to a
5585 // non-volatile const type (i.e., cv1 shall be const), or the reference
5586 // shall be an rvalue reference.
5587 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5588 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5590 return ICS;
5591 }
5592
5593 // -- If the initializer expression
5594 //
5595 // -- is an xvalue, class prvalue, array prvalue or function
5596 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5597 if (RefRelationship == Sema::Ref_Compatible &&
5598 (InitCategory.isXValue() ||
5599 (InitCategory.isPRValue() &&
5600 (T2->isRecordType() || T2->isArrayType())) ||
5601 (InitCategory.isLValue() && T2->isFunctionType()))) {
5602 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5603 // binding unless we're binding to a class prvalue.
5604 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5605 // allow the use of rvalue references in C++98/03 for the benefit of
5606 // standard library implementors; therefore, we need the xvalue check here.
5607 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5608 !(InitCategory.isPRValue() || T2->isRecordType()));
5609 return ICS;
5610 }
5611
5612 // -- has a class type (i.e., T2 is a class type), where T1 is not
5613 // reference-related to T2, and can be implicitly converted to
5614 // an xvalue, class prvalue, or function lvalue of type
5615 // "cv3 T3", where "cv1 T1" is reference-compatible with
5616 // "cv3 T3",
5617 //
5618 // then the reference is bound to the value of the initializer
5619 // expression in the first case and to the result of the conversion
5620 // in the second case (or, in either case, to an appropriate base
5621 // class subobject).
5622 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5623 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5624 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5625 Init, T2, /*AllowRvalues=*/true,
5626 AllowExplicit)) {
5627 // In the second case, if the reference is an rvalue reference
5628 // and the second standard conversion sequence of the
5629 // user-defined conversion sequence includes an lvalue-to-rvalue
5630 // conversion, the program is ill-formed.
5631 if (ICS.isUserDefined() && isRValRef &&
5634
5635 return ICS;
5636 }
5637
5638 // A temporary of function type cannot be created; don't even try.
5639 if (T1->isFunctionType())
5640 return ICS;
5641
5642 // -- Otherwise, a temporary of type "cv1 T1" is created and
5643 // initialized from the initializer expression using the
5644 // rules for a non-reference copy initialization (8.5). The
5645 // reference is then bound to the temporary. If T1 is
5646 // reference-related to T2, cv1 must be the same
5647 // cv-qualification as, or greater cv-qualification than,
5648 // cv2; otherwise, the program is ill-formed.
5649 if (RefRelationship == Sema::Ref_Related) {
5650 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5651 // we would be reference-compatible or reference-compatible with
5652 // added qualification. But that wasn't the case, so the reference
5653 // initialization fails.
5654 //
5655 // Note that we only want to check address spaces and cvr-qualifiers here.
5656 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5657 Qualifiers T1Quals = T1.getQualifiers();
5658 Qualifiers T2Quals = T2.getQualifiers();
5659 T1Quals.removeObjCGCAttr();
5660 T1Quals.removeObjCLifetime();
5661 T2Quals.removeObjCGCAttr();
5662 T2Quals.removeObjCLifetime();
5663 // MS compiler ignores __unaligned qualifier for references; do the same.
5664 T1Quals.removeUnaligned();
5665 T2Quals.removeUnaligned();
5666 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5667 return ICS;
5668 }
5669
5670 // If at least one of the types is a class type, the types are not
5671 // related, and we aren't allowed any user conversions, the
5672 // reference binding fails. This case is important for breaking
5673 // recursion, since TryImplicitConversion below will attempt to
5674 // create a temporary through the use of a copy constructor.
5675 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5676 (T1->isRecordType() || T2->isRecordType()))
5677 return ICS;
5678
5679 // If T1 is reference-related to T2 and the reference is an rvalue
5680 // reference, the initializer expression shall not be an lvalue.
5681 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5682 Init->Classify(S.Context).isLValue()) {
5684 return ICS;
5685 }
5686
5687 // C++ [over.ics.ref]p2:
5688 // When a parameter of reference type is not bound directly to
5689 // an argument expression, the conversion sequence is the one
5690 // required to convert the argument expression to the
5691 // underlying type of the reference according to
5692 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5693 // to copy-initializing a temporary of the underlying type with
5694 // the argument expression. Any difference in top-level
5695 // cv-qualification is subsumed by the initialization itself
5696 // and does not constitute a conversion.
5697 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5698 AllowedExplicit::None,
5699 /*InOverloadResolution=*/false,
5700 /*CStyle=*/false,
5701 /*AllowObjCWritebackConversion=*/false,
5702 /*AllowObjCConversionOnExplicit=*/false);
5703
5704 // Of course, that's still a reference binding.
5705 if (ICS.isStandard()) {
5706 ICS.Standard.ReferenceBinding = true;
5707 ICS.Standard.IsLvalueReference = !isRValRef;
5708 ICS.Standard.BindsToFunctionLvalue = false;
5709 ICS.Standard.BindsToRvalue = true;
5712 } else if (ICS.isUserDefined()) {
5713 const ReferenceType *LValRefType =
5716
5717 // C++ [over.ics.ref]p3:
5718 // Except for an implicit object parameter, for which see 13.3.1, a
5719 // standard conversion sequence cannot be formed if it requires [...]
5720 // binding an rvalue reference to an lvalue other than a function
5721 // lvalue.
5722 // Note that the function case is not possible here.
5723 if (isRValRef && LValRefType) {
5725 return ICS;
5726 }
5727
5729 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5731 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5735 }
5736
5737 return ICS;
5738}
5739
5740static ImplicitConversionSequence
5741TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5742 bool SuppressUserConversions,
5743 bool InOverloadResolution,
5744 bool AllowObjCWritebackConversion,
5745 bool AllowExplicit = false);
5746
5747/// TryListConversion - Try to copy-initialize a value of type ToType from the
5748/// initializer list From.
5749static ImplicitConversionSequence
5751 bool SuppressUserConversions,
5752 bool InOverloadResolution,
5753 bool AllowObjCWritebackConversion) {
5754 // C++11 [over.ics.list]p1:
5755 // When an argument is an initializer list, it is not an expression and
5756 // special rules apply for converting it to a parameter type.
5757
5759 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5760
5761 // We need a complete type for what follows. With one C++20 exception,
5762 // incomplete types can never be initialized from init lists.
5763 QualType InitTy = ToType;
5764 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5765 if (AT && S.getLangOpts().CPlusPlus20)
5766 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5767 // C++20 allows list initialization of an incomplete array type.
5768 InitTy = IAT->getElementType();
5769 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5770 return Result;
5771
5772 // C++20 [over.ics.list]/2:
5773 // If the initializer list is a designated-initializer-list, a conversion
5774 // is only possible if the parameter has an aggregate type
5775 //
5776 // FIXME: The exception for reference initialization here is not part of the
5777 // language rules, but follow other compilers in adding it as a tentative DR
5778 // resolution.
5779 bool IsDesignatedInit = From->hasDesignatedInit();
5780 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5781 IsDesignatedInit)
5782 return Result;
5783
5784 // Per DR1467 and DR2137:
5785 // If the parameter type is an aggregate class X and the initializer list
5786 // has a single element of type cv U, where U is X or a class derived from
5787 // X, the implicit conversion sequence is the one required to convert the
5788 // element to the parameter type.
5789 //
5790 // Otherwise, if the parameter type is a character array [... ]
5791 // and the initializer list has a single element that is an
5792 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5793 // implicit conversion sequence is the identity conversion.
5794 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5795 if (ToType->isRecordType() && ToType->isAggregateType()) {
5796 QualType InitType = From->getInit(0)->getType();
5797 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5798 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5799 return TryCopyInitialization(S, From->getInit(0), ToType,
5800 SuppressUserConversions,
5801 InOverloadResolution,
5802 AllowObjCWritebackConversion);
5803 }
5804
5805 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5806 InitializedEntity Entity =
5808 /*Consumed=*/false);
5809 if (S.CanPerformCopyInitialization(Entity, From)) {
5810 Result.setStandard();
5811 Result.Standard.setAsIdentityConversion();
5812 Result.Standard.setFromType(ToType);
5813 Result.Standard.setAllToTypes(ToType);
5814 return Result;
5815 }
5816 }
5817 }
5818
5819 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5820 // C++11 [over.ics.list]p2:
5821 // If the parameter type is std::initializer_list<X> or "array of X" and
5822 // all the elements can be implicitly converted to X, the implicit
5823 // conversion sequence is the worst conversion necessary to convert an
5824 // element of the list to X.
5825 //
5826 // C++14 [over.ics.list]p3:
5827 // Otherwise, if the parameter type is "array of N X", if the initializer
5828 // list has exactly N elements or if it has fewer than N elements and X is
5829 // default-constructible, and if all the elements of the initializer list
5830 // can be implicitly converted to X, the implicit conversion sequence is
5831 // the worst conversion necessary to convert an element of the list to X.
5832 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5833 unsigned e = From->getNumInits();
5836 QualType());
5837 QualType ContTy = ToType;
5838 bool IsUnbounded = false;
5839 if (AT) {
5840 InitTy = AT->getElementType();
5841 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5842 if (CT->getSize().ult(e)) {
5843 // Too many inits, fatally bad
5845 ToType);
5846 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5847 return Result;
5848 }
5849 if (CT->getSize().ugt(e)) {
5850 // Need an init from empty {}, is there one?
5851 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5852 From->getEndLoc(), /*isExplicit=*/false);
5853 EmptyList.setType(S.Context.VoidTy);
5854 DfltElt = TryListConversion(
5855 S, &EmptyList, InitTy, SuppressUserConversions,
5856 InOverloadResolution, AllowObjCWritebackConversion);
5857 if (DfltElt.isBad()) {
5858 // No {} init, fatally bad
5860 ToType);
5861 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5862 return Result;
5863 }
5864 }
5865 } else {
5866 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5867 IsUnbounded = true;
5868 if (!e) {
5869 // Cannot convert to zero-sized.
5871 ToType);
5872 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5873 return Result;
5874 }
5875 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5876 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5878 }
5879 }
5880
5881 Result.setStandard();
5882 Result.Standard.setAsIdentityConversion();
5883 Result.Standard.setFromType(InitTy);
5884 Result.Standard.setAllToTypes(InitTy);
5885 for (unsigned i = 0; i < e; ++i) {
5886 Expr *Init = From->getInit(i);
5888 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5889 AllowObjCWritebackConversion);
5890
5891 // Keep the worse conversion seen so far.
5892 // FIXME: Sequences are not totally ordered, so 'worse' can be
5893 // ambiguous. CWG has been informed.
5895 Result) ==
5897 Result = ICS;
5898 // Bail as soon as we find something unconvertible.
5899 if (Result.isBad()) {
5900 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5901 return Result;
5902 }
5903 }
5904 }
5905
5906 // If we needed any implicit {} initialization, compare that now.
5907 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5908 // has been informed that this might not be the best thing.
5909 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5910 S, From->getEndLoc(), DfltElt, Result) ==
5912 Result = DfltElt;
5913 // Record the type being initialized so that we may compare sequences
5914 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5915 return Result;
5916 }
5917
5918 // C++14 [over.ics.list]p4:
5919 // C++11 [over.ics.list]p3:
5920 // Otherwise, if the parameter is a non-aggregate class X and overload
5921 // resolution chooses a single best constructor [...] the implicit
5922 // conversion sequence is a user-defined conversion sequence. If multiple
5923 // constructors are viable but none is better than the others, the
5924 // implicit conversion sequence is a user-defined conversion sequence.
5925 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5926 // This function can deal with initializer lists.
5927 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5928 AllowedExplicit::None,
5929 InOverloadResolution, /*CStyle=*/false,
5930 AllowObjCWritebackConversion,
5931 /*AllowObjCConversionOnExplicit=*/false);
5932 }
5933
5934 // C++14 [over.ics.list]p5:
5935 // C++11 [over.ics.list]p4:
5936 // Otherwise, if the parameter has an aggregate type which can be
5937 // initialized from the initializer list [...] the implicit conversion
5938 // sequence is a user-defined conversion sequence.
5939 if (ToType->isAggregateType()) {
5940 // Type is an aggregate, argument is an init list. At this point it comes
5941 // down to checking whether the initialization works.
5942 // FIXME: Find out whether this parameter is consumed or not.
5943 InitializedEntity Entity =
5945 /*Consumed=*/false);
5947 From)) {
5948 Result.setUserDefined();
5949 Result.UserDefined.Before.setAsIdentityConversion();
5950 // Initializer lists don't have a type.
5951 Result.UserDefined.Before.setFromType(QualType());
5952 Result.UserDefined.Before.setAllToTypes(QualType());
5953
5954 Result.UserDefined.After.setAsIdentityConversion();
5955 Result.UserDefined.After.setFromType(ToType);
5956 Result.UserDefined.After.setAllToTypes(ToType);
5957 Result.UserDefined.ConversionFunction = nullptr;
5958 }
5959 return Result;
5960 }
5961
5962 // C++14 [over.ics.list]p6:
5963 // C++11 [over.ics.list]p5:
5964 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5965 if (ToType->isReferenceType()) {
5966 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5967 // mention initializer lists in any way. So we go by what list-
5968 // initialization would do and try to extrapolate from that.
5969
5970 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5971
5972 // If the initializer list has a single element that is reference-related
5973 // to the parameter type, we initialize the reference from that.
5974 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5975 Expr *Init = From->getInit(0);
5976
5977 QualType T2 = Init->getType();
5978
5979 // If the initializer is the address of an overloaded function, try
5980 // to resolve the overloaded function. If all goes well, T2 is the
5981 // type of the resulting function.
5982 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5985 Init, ToType, false, Found))
5986 T2 = Fn->getType();
5987 }
5988
5989 // Compute some basic properties of the types and the initializer.
5990 Sema::ReferenceCompareResult RefRelationship =
5991 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5992
5993 if (RefRelationship >= Sema::Ref_Related) {
5994 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5995 SuppressUserConversions,
5996 /*AllowExplicit=*/false);
5997 }
5998 }
5999
6000 // Otherwise, we bind the reference to a temporary created from the
6001 // initializer list.
6002 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6003 InOverloadResolution,
6004 AllowObjCWritebackConversion);
6005 if (Result.isFailure())
6006 return Result;
6007 assert(!Result.isEllipsis() &&
6008 "Sub-initialization cannot result in ellipsis conversion.");
6009
6010 // Can we even bind to a temporary?
6011 if (ToType->isRValueReferenceType() ||
6012 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6013 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6014 Result.UserDefined.After;
6015 SCS.ReferenceBinding = true;
6017 SCS.BindsToRvalue = true;
6018 SCS.BindsToFunctionLvalue = false;
6021 SCS.FromBracedInitList = false;
6022
6023 } else
6025 From, ToType);
6026 return Result;
6027 }
6028
6029 // C++14 [over.ics.list]p7:
6030 // C++11 [over.ics.list]p6:
6031 // Otherwise, if the parameter type is not a class:
6032 if (!ToType->isRecordType()) {
6033 // - if the initializer list has one element that is not itself an
6034 // initializer list, the implicit conversion sequence is the one
6035 // required to convert the element to the parameter type.
6036 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6037 // single integer.
6038 unsigned NumInits = From->getNumInits();
6039 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6040 !isa<EmbedExpr>(From->getInit(0))) {
6042 S, From->getInit(0), ToType, SuppressUserConversions,
6043 InOverloadResolution, AllowObjCWritebackConversion);
6044 if (Result.isStandard())
6045 Result.Standard.FromBracedInitList = true;
6046 }
6047 // - if the initializer list has no elements, the implicit conversion
6048 // sequence is the identity conversion.
6049 else if (NumInits == 0) {
6050 Result.setStandard();
6051 Result.Standard.setAsIdentityConversion();
6052 Result.Standard.setFromType(ToType);
6053 Result.Standard.setAllToTypes(ToType);
6054 }
6055 return Result;
6056 }
6057
6058 // C++14 [over.ics.list]p8:
6059 // C++11 [over.ics.list]p7:
6060 // In all cases other than those enumerated above, no conversion is possible
6061 return Result;
6062}
6063
6064/// TryCopyInitialization - Try to copy-initialize a value of type
6065/// ToType from the expression From. Return the implicit conversion
6066/// sequence required to pass this argument, which may be a bad
6067/// conversion sequence (meaning that the argument cannot be passed to
6068/// a parameter of this type). If @p SuppressUserConversions, then we
6069/// do not permit any user-defined conversion sequences.
6070static ImplicitConversionSequence
6072 bool SuppressUserConversions,
6073 bool InOverloadResolution,
6074 bool AllowObjCWritebackConversion,
6075 bool AllowExplicit) {
6076 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6077 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6078 InOverloadResolution,AllowObjCWritebackConversion);
6079
6080 if (ToType->isReferenceType())
6081 return TryReferenceInit(S, From, ToType,
6082 /*FIXME:*/ From->getBeginLoc(),
6083 SuppressUserConversions, AllowExplicit);
6084
6085 return TryImplicitConversion(S, From, ToType,
6086 SuppressUserConversions,
6087 AllowedExplicit::None,
6088 InOverloadResolution,
6089 /*CStyle=*/false,
6090 AllowObjCWritebackConversion,
6091 /*AllowObjCConversionOnExplicit=*/false);
6092}
6093
6094static bool TryCopyInitialization(const CanQualType FromQTy,
6095 const CanQualType ToQTy,
6096 Sema &S,
6097 SourceLocation Loc,
6098 ExprValueKind FromVK) {
6099 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6101 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6102
6103 return !ICS.isBad();
6104}
6105
6106/// TryObjectArgumentInitialization - Try to initialize the object
6107/// parameter of the given member function (@c Method) from the
6108/// expression @p From.
6110 Sema &S, SourceLocation Loc, QualType FromType,
6111 Expr::Classification FromClassification, CXXMethodDecl *Method,
6112 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6113 QualType ExplicitParameterType = QualType(),
6114 bool SuppressUserConversion = false) {
6115
6116 // We need to have an object of class type.
6117 if (const auto *PT = FromType->getAs<PointerType>()) {
6118 FromType = PT->getPointeeType();
6119
6120 // When we had a pointer, it's implicitly dereferenced, so we
6121 // better have an lvalue.
6122 assert(FromClassification.isLValue());
6123 }
6124
6125 auto ValueKindFromClassification = [](Expr::Classification C) {
6126 if (C.isPRValue())
6127 return clang::VK_PRValue;
6128 if (C.isXValue())
6129 return VK_XValue;
6130 return clang::VK_LValue;
6131 };
6132
6133 if (Method->isExplicitObjectMemberFunction()) {
6134 if (ExplicitParameterType.isNull())
6135 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6136 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6137 ValueKindFromClassification(FromClassification));
6139 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6140 /*InOverloadResolution=*/true, false);
6141 if (ICS.isBad())
6142 ICS.Bad.FromExpr = nullptr;
6143 return ICS;
6144 }
6145
6146 assert(FromType->isRecordType());
6147
6148 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6149 // C++98 [class.dtor]p2:
6150 // A destructor can be invoked for a const, volatile or const volatile
6151 // object.
6152 // C++98 [over.match.funcs]p4:
6153 // For static member functions, the implicit object parameter is considered
6154 // to match any object (since if the function is selected, the object is
6155 // discarded).
6156 Qualifiers Quals = Method->getMethodQualifiers();
6157 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6158 Quals.addConst();
6159 Quals.addVolatile();
6160 }
6161
6162 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6163
6164 // Set up the conversion sequence as a "bad" conversion, to allow us
6165 // to exit early.
6167
6168 // C++0x [over.match.funcs]p4:
6169 // For non-static member functions, the type of the implicit object
6170 // parameter is
6171 //
6172 // - "lvalue reference to cv X" for functions declared without a
6173 // ref-qualifier or with the & ref-qualifier
6174 // - "rvalue reference to cv X" for functions declared with the &&
6175 // ref-qualifier
6176 //
6177 // where X is the class of which the function is a member and cv is the
6178 // cv-qualification on the member function declaration.
6179 //
6180 // However, when finding an implicit conversion sequence for the argument, we
6181 // are not allowed to perform user-defined conversions
6182 // (C++ [over.match.funcs]p5). We perform a simplified version of
6183 // reference binding here, that allows class rvalues to bind to
6184 // non-constant references.
6185
6186 // First check the qualifiers.
6187 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6188 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6189 if (ImplicitParamType.getCVRQualifiers() !=
6190 FromTypeCanon.getLocalCVRQualifiers() &&
6191 !ImplicitParamType.isAtLeastAsQualifiedAs(
6192 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6194 FromType, ImplicitParamType);
6195 return ICS;
6196 }
6197
6198 if (FromTypeCanon.hasAddressSpace()) {
6199 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6200 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6201 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6202 S.getASTContext())) {
6204 FromType, ImplicitParamType);
6205 return ICS;
6206 }
6207 }
6208
6209 // Check that we have either the same type or a derived type. It
6210 // affects the conversion rank.
6211 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6212 ImplicitConversionKind SecondKind;
6213 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6214 SecondKind = ICK_Identity;
6215 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6216 SecondKind = ICK_Derived_To_Base;
6217 } else if (!Method->isExplicitObjectMemberFunction()) {
6219 FromType, ImplicitParamType);
6220 return ICS;
6221 }
6222
6223 // Check the ref-qualifier.
6224 switch (Method->getRefQualifier()) {
6225 case RQ_None:
6226 // Do nothing; we don't care about lvalueness or rvalueness.
6227 break;
6228
6229 case RQ_LValue:
6230 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6231 // non-const lvalue reference cannot bind to an rvalue
6233 ImplicitParamType);
6234 return ICS;
6235 }
6236 break;
6237
6238 case RQ_RValue:
6239 if (!FromClassification.isRValue()) {
6240 // rvalue reference cannot bind to an lvalue
6242 ImplicitParamType);
6243 return ICS;
6244 }
6245 break;
6246 }
6247
6248 // Success. Mark this as a reference binding.
6249 ICS.setStandard();
6251 ICS.Standard.Second = SecondKind;
6252 ICS.Standard.setFromType(FromType);
6253 ICS.Standard.setAllToTypes(ImplicitParamType);
6254 ICS.Standard.ReferenceBinding = true;
6255 ICS.Standard.DirectBinding = true;
6256 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6257 ICS.Standard.BindsToFunctionLvalue = false;
6258 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6259 ICS.Standard.FromBracedInitList = false;
6261 = (Method->getRefQualifier() == RQ_None);
6262 return ICS;
6263}
6264
6265/// PerformObjectArgumentInitialization - Perform initialization of
6266/// the implicit object parameter for the given Method with the given
6267/// expression.
6269 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6271 QualType FromRecordType, DestType;
6272 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6273
6274 Expr::Classification FromClassification;
6275 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6276 FromRecordType = PT->getPointeeType();
6277 DestType = Method->getThisType();
6278 FromClassification = Expr::Classification::makeSimpleLValue();
6279 } else {
6280 FromRecordType = From->getType();
6281 DestType = ImplicitParamRecordType;
6282 FromClassification = From->Classify(Context);
6283
6284 // CWG2813 [expr.call]p6:
6285 // If the function is an implicit object member function, the object
6286 // expression of the class member access shall be a glvalue [...]
6287 if (From->isPRValue()) {
6288 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6289 Method->getRefQualifier() !=
6291 }
6292 }
6293
6294 // Note that we always use the true parent context when performing
6295 // the actual argument initialization.
6297 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6298 Method->getParent());
6299 if (ICS.isBad()) {
6300 switch (ICS.Bad.Kind) {
6302 Qualifiers FromQs = FromRecordType.getQualifiers();
6303 Qualifiers ToQs = DestType.getQualifiers();
6304 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6305 if (CVR) {
6306 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6307 << Method->getDeclName() << FromRecordType << (CVR - 1)
6308 << From->getSourceRange();
6309 Diag(Method->getLocation(), diag::note_previous_decl)
6310 << Method->getDeclName();
6311 return ExprError();
6312 }
6313 break;
6314 }
6315
6318 bool IsRValueQualified =
6319 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6320 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6321 << Method->getDeclName() << FromClassification.isRValue()
6322 << IsRValueQualified;
6323 Diag(Method->getLocation(), diag::note_previous_decl)
6324 << Method->getDeclName();
6325 return ExprError();
6326 }
6327
6330 break;
6331
6334 llvm_unreachable("Lists are not objects");
6335 }
6336
6337 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6338 << ImplicitParamRecordType << FromRecordType
6339 << From->getSourceRange();
6340 }
6341
6342 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6343 ExprResult FromRes =
6344 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6345 if (FromRes.isInvalid())
6346 return ExprError();
6347 From = FromRes.get();
6348 }
6349
6350 if (!Context.hasSameType(From->getType(), DestType)) {
6351 CastKind CK;
6352 QualType PteeTy = DestType->getPointeeType();
6353 LangAS DestAS =
6354 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6355 if (FromRecordType.getAddressSpace() != DestAS)
6356 CK = CK_AddressSpaceConversion;
6357 else
6358 CK = CK_NoOp;
6359 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6360 }
6361 return From;
6362}
6363
6364/// TryContextuallyConvertToBool - Attempt to contextually convert the
6365/// expression From to bool (C++0x [conv]p3).
6368 // C++ [dcl.init]/17.8:
6369 // - Otherwise, if the initialization is direct-initialization, the source
6370 // type is std::nullptr_t, and the destination type is bool, the initial
6371 // value of the object being initialized is false.
6372 if (From->getType()->isNullPtrType())
6374 S.Context.BoolTy,
6375 From->isGLValue());
6376
6377 // All other direct-initialization of bool is equivalent to an implicit
6378 // conversion to bool in which explicit conversions are permitted.
6379 return TryImplicitConversion(S, From, S.Context.BoolTy,
6380 /*SuppressUserConversions=*/false,
6381 AllowedExplicit::Conversions,
6382 /*InOverloadResolution=*/false,
6383 /*CStyle=*/false,
6384 /*AllowObjCWritebackConversion=*/false,
6385 /*AllowObjCConversionOnExplicit=*/false);
6386}
6387
6389 if (checkPlaceholderForOverload(*this, From))
6390 return ExprError();
6391 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6392 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6393
6395 if (!ICS.isBad())
6396 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6399 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6400 << From->getType() << From->getSourceRange();
6401 return ExprError();
6402}
6403
6404/// Check that the specified conversion is permitted in a converted constant
6405/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6406/// is acceptable.
6409 // Since we know that the target type is an integral or unscoped enumeration
6410 // type, most conversion kinds are impossible. All possible First and Third
6411 // conversions are fine.
6412 switch (SCS.Second) {
6413 case ICK_Identity:
6415 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6417 return true;
6418
6420 // Conversion from an integral or unscoped enumeration type to bool is
6421 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6422 // conversion, so we allow it in a converted constant expression.
6423 //
6424 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6425 // a lot of popular code. We should at least add a warning for this
6426 // (non-conforming) extension.
6428 SCS.getToType(2)->isBooleanType();
6429
6431 case ICK_Pointer_Member:
6432 // C++1z: null pointer conversions and null member pointer conversions are
6433 // only permitted if the source type is std::nullptr_t.
6434 return SCS.getFromType()->isNullPtrType();
6435
6448 case ICK_Vector_Splat:
6449 case ICK_Complex_Real:
6459 return false;
6460
6465 llvm_unreachable("found a first conversion kind in Second");
6466
6468 case ICK_Qualification:
6469 llvm_unreachable("found a third conversion kind in Second");
6470
6472 break;
6473 }
6474
6475 llvm_unreachable("unknown conversion kind");
6476}
6477
6478/// BuildConvertedConstantExpression - Check that the expression From is a
6479/// converted constant expression of type T, perform the conversion but
6480/// does not evaluate the expression
6482 QualType T, CCEKind CCE,
6483 NamedDecl *Dest,
6484 APValue &PreNarrowingValue) {
6485 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6487 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6488 "converted constant expression outside C++11 or TTP matching");
6489
6490 if (checkPlaceholderForOverload(S, From))
6491 return ExprError();
6492
6493 if (From->containsErrors()) {
6494 // The expression already has errors, so the correct cast kind can't be
6495 // determined. Use RecoveryExpr to keep the expected type T and mark the
6496 // result as invalid, preventing further cascading errors.
6497 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6498 T);
6499 }
6500
6501 // C++1z [expr.const]p3:
6502 // A converted constant expression of type T is an expression,
6503 // implicitly converted to type T, where the converted
6504 // expression is a constant expression and the implicit conversion
6505 // sequence contains only [... list of conversions ...].
6507 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6509 : TryCopyInitialization(S, From, T,
6510 /*SuppressUserConversions=*/false,
6511 /*InOverloadResolution=*/false,
6512 /*AllowObjCWritebackConversion=*/false,
6513 /*AllowExplicit=*/false);
6514 StandardConversionSequence *SCS = nullptr;
6515 switch (ICS.getKind()) {
6517 SCS = &ICS.Standard;
6518 break;
6520 if (T->isRecordType())
6521 SCS = &ICS.UserDefined.Before;
6522 else
6523 SCS = &ICS.UserDefined.After;
6524 break;
6528 return S.Diag(From->getBeginLoc(),
6529 diag::err_typecheck_converted_constant_expression)
6530 << From->getType() << From->getSourceRange() << T;
6531 return ExprError();
6532
6535 llvm_unreachable("bad conversion in converted constant expression");
6536 }
6537
6538 // Check that we would only use permitted conversions.
6539 if (!CheckConvertedConstantConversions(S, *SCS)) {
6540 return S.Diag(From->getBeginLoc(),
6541 diag::err_typecheck_converted_constant_expression_disallowed)
6542 << From->getType() << From->getSourceRange() << T;
6543 }
6544 // [...] and where the reference binding (if any) binds directly.
6545 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6546 return S.Diag(From->getBeginLoc(),
6547 diag::err_typecheck_converted_constant_expression_indirect)
6548 << From->getType() << From->getSourceRange() << T;
6549 }
6550 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6551 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6552 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6553 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6554 // case explicitly.
6555 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6556 return S.Diag(From->getBeginLoc(),
6557 diag::err_reference_bind_to_bitfield_in_cce)
6558 << From->getSourceRange();
6559 }
6560
6561 // Usually we can simply apply the ImplicitConversionSequence we formed
6562 // earlier, but that's not guaranteed to work when initializing an object of
6563 // class type.
6565 bool IsTemplateArgument =
6567 if (T->isRecordType()) {
6568 assert(IsTemplateArgument &&
6569 "unexpected class type converted constant expr");
6573 SourceLocation(), From);
6574 } else {
6575 Result =
6577 }
6578 if (Result.isInvalid())
6579 return Result;
6580
6581 // C++2a [intro.execution]p5:
6582 // A full-expression is [...] a constant-expression [...]
6583 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6584 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6585 IsTemplateArgument);
6586 if (Result.isInvalid())
6587 return Result;
6588
6589 // Check for a narrowing implicit conversion.
6590 bool ReturnPreNarrowingValue = false;
6591 QualType PreNarrowingType;
6592 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6593 PreNarrowingType)) {
6595 // Implicit conversion to a narrower type, and the value is not a constant
6596 // expression. We'll diagnose this in a moment.
6597 case NK_Not_Narrowing:
6598 break;
6599
6601 if (CCE == CCEKind::ArrayBound &&
6602 PreNarrowingType->isIntegralOrEnumerationType() &&
6603 PreNarrowingValue.isInt()) {
6604 // Don't diagnose array bound narrowing here; we produce more precise
6605 // errors by allowing the un-narrowed value through.
6606 ReturnPreNarrowingValue = true;
6607 break;
6608 }
6609 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6610 << CCE << /*Constant*/ 1
6611 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6612 // If this is an SFINAE Context, treat the result as invalid so it stops
6613 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6614 // FIXME: Should do this whenever the above diagnostic is an error, but
6615 // without further changes this would degrade some other diagnostics.
6616 if (S.isSFINAEContext())
6617 return ExprError();
6618 break;
6619
6621 // Implicit conversion to a narrower type, but the expression is
6622 // value-dependent so we can't tell whether it's actually narrowing.
6623 // For matching the parameters of a TTP, the conversion is ill-formed
6624 // if it may narrow.
6625 if (CCE != CCEKind::TempArgStrict)
6626 break;
6627 [[fallthrough]];
6628 case NK_Type_Narrowing:
6629 // FIXME: It would be better to diagnose that the expression is not a
6630 // constant expression.
6631 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6632 << CCE << /*Constant*/ 0 << From->getType() << T;
6633 if (S.isSFINAEContext())
6634 return ExprError();
6635 break;
6636 }
6637 if (!ReturnPreNarrowingValue)
6638 PreNarrowingValue = {};
6639
6640 return Result;
6641}
6642
6643/// CheckConvertedConstantExpression - Check that the expression From is a
6644/// converted constant expression of type T, perform the conversion and produce
6645/// the converted expression, per C++11 [expr.const]p3.
6648 CCEKind CCE, bool RequireInt,
6649 NamedDecl *Dest) {
6650
6651 APValue PreNarrowingValue;
6652 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6653 PreNarrowingValue);
6654 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6655 Value = APValue();
6656 return Result;
6657 }
6658 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6659 RequireInt, PreNarrowingValue);
6660}
6661
6663 CCEKind CCE,
6664 NamedDecl *Dest) {
6665 APValue PreNarrowingValue;
6666 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6667 PreNarrowingValue);
6668}
6669
6671 APValue &Value, CCEKind CCE,
6672 NamedDecl *Dest) {
6673 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6674 Dest);
6675}
6676
6678 llvm::APSInt &Value,
6679 CCEKind CCE) {
6680 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6681
6682 APValue V;
6683 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6684 /*Dest=*/nullptr);
6685 if (!R.isInvalid() && !R.get()->isValueDependent())
6686 Value = V.getInt();
6687 return R;
6688}
6689
6692 CCEKind CCE, bool RequireInt,
6693 const APValue &PreNarrowingValue) {
6694
6695 ExprResult Result = E;
6696 // Check the expression is a constant expression.
6698 Expr::EvalResult Eval;
6699 Eval.Diag = &Notes;
6700
6701 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6702
6703 ConstantExprKind Kind;
6704 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6705 Kind = ConstantExprKind::ClassTemplateArgument;
6706 else if (CCE == CCEKind::TemplateArg)
6707 Kind = ConstantExprKind::NonClassTemplateArgument;
6708 else
6709 Kind = ConstantExprKind::Normal;
6710
6711 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6712 (RequireInt && !Eval.Val.isInt())) {
6713 // The expression can't be folded, so we can't keep it at this position in
6714 // the AST.
6715 Result = ExprError();
6716 } else {
6717 Value = Eval.Val;
6718
6719 if (Notes.empty()) {
6720 // It's a constant expression.
6721 Expr *E = Result.get();
6722 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6723 // We expect a ConstantExpr to have a value associated with it
6724 // by this point.
6725 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6726 "ConstantExpr has no value associated with it");
6727 (void)CE;
6728 } else {
6730 }
6731 if (!PreNarrowingValue.isAbsent())
6732 Value = std::move(PreNarrowingValue);
6733 return E;
6734 }
6735 }
6736
6737 // It's not a constant expression. Produce an appropriate diagnostic.
6738 if (Notes.size() == 1 &&
6739 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6740 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6741 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6742 diag::note_constexpr_invalid_template_arg) {
6743 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6744 for (unsigned I = 0; I < Notes.size(); ++I)
6745 Diag(Notes[I].first, Notes[I].second);
6746 } else {
6747 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6748 << CCE << E->getSourceRange();
6749 for (unsigned I = 0; I < Notes.size(); ++I)
6750 Diag(Notes[I].first, Notes[I].second);
6751 }
6752 return ExprError();
6753}
6754
6755/// dropPointerConversions - If the given standard conversion sequence
6756/// involves any pointer conversions, remove them. This may change
6757/// the result type of the conversion sequence.
6759 if (SCS.Second == ICK_Pointer_Conversion) {
6760 SCS.Second = ICK_Identity;
6761 SCS.Dimension = ICK_Identity;
6762 SCS.Third = ICK_Identity;
6763 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6764 }
6765}
6766
6767/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6768/// convert the expression From to an Objective-C pointer type.
6769static ImplicitConversionSequence
6771 // Do an implicit conversion to 'id'.
6774 = TryImplicitConversion(S, From, Ty,
6775 // FIXME: Are these flags correct?
6776 /*SuppressUserConversions=*/false,
6777 AllowedExplicit::Conversions,
6778 /*InOverloadResolution=*/false,
6779 /*CStyle=*/false,
6780 /*AllowObjCWritebackConversion=*/false,
6781 /*AllowObjCConversionOnExplicit=*/true);
6782
6783 // Strip off any final conversions to 'id'.
6784 switch (ICS.getKind()) {
6789 break;
6790
6793 break;
6794
6797 break;
6798 }
6799
6800 return ICS;
6801}
6802
6804 if (checkPlaceholderForOverload(*this, From))
6805 return ExprError();
6806
6807 QualType Ty = Context.getObjCIdType();
6810 if (!ICS.isBad())
6811 return PerformImplicitConversion(From, Ty, ICS,
6813 return ExprResult();
6814}
6815
6816static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6817 const Expr *Base = nullptr;
6818 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6819 "expected a member expression");
6820
6821 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6822 M && !M->isImplicitAccess())
6823 Base = M->getBase();
6824 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6825 M && !M->isImplicitAccess())
6826 Base = M->getBase();
6827
6828 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6829
6830 if (T->isPointerType())
6831 T = T->getPointeeType();
6832
6833 return T;
6834}
6835
6837 const FunctionDecl *Fun) {
6838 QualType ObjType = Obj->getType();
6839 if (ObjType->isPointerType()) {
6840 ObjType = ObjType->getPointeeType();
6841 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6843 /*CanOverflow=*/false, FPOptionsOverride());
6844 }
6845 return Obj;
6846}
6847
6855
6857 Expr *Object, MultiExprArg &Args,
6858 SmallVectorImpl<Expr *> &NewArgs) {
6859 assert(Method->isExplicitObjectMemberFunction() &&
6860 "Method is not an explicit member function");
6861 assert(NewArgs.empty() && "NewArgs should be empty");
6862
6863 NewArgs.reserve(Args.size() + 1);
6864 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6865 NewArgs.push_back(This);
6866 NewArgs.append(Args.begin(), Args.end());
6867 Args = NewArgs;
6869 Method, Object->getBeginLoc());
6870}
6871
6872/// Determine whether the provided type is an integral type, or an enumeration
6873/// type of a permitted flavor.
6875 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6876 : T->isIntegralOrUnscopedEnumerationType();
6877}
6878
6879static ExprResult
6882 QualType T, UnresolvedSetImpl &ViableConversions) {
6883
6884 if (Converter.Suppress)
6885 return ExprError();
6886
6887 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6888 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6889 CXXConversionDecl *Conv =
6890 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6892 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6893 }
6894 return From;
6895}
6896
6897static bool
6900 QualType T, bool HadMultipleCandidates,
6901 UnresolvedSetImpl &ExplicitConversions) {
6902 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6903 DeclAccessPair Found = ExplicitConversions[0];
6904 CXXConversionDecl *Conversion =
6905 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6906
6907 // The user probably meant to invoke the given explicit
6908 // conversion; use it.
6909 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6910 std::string TypeStr;
6911 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6912
6913 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6915 "static_cast<" + TypeStr + ">(")
6917 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6918 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6919
6920 // If we aren't in a SFINAE context, build a call to the
6921 // explicit conversion function.
6922 if (SemaRef.isSFINAEContext())
6923 return true;
6924
6925 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6926 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6927 HadMultipleCandidates);
6928 if (Result.isInvalid())
6929 return true;
6930
6931 // Replace the conversion with a RecoveryExpr, so we don't try to
6932 // instantiate it later, but can further diagnose here.
6933 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6934 From, Result.get()->getType());
6935 if (Result.isInvalid())
6936 return true;
6937 From = Result.get();
6938 }
6939 return false;
6940}
6941
6942static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6944 QualType T, bool HadMultipleCandidates,
6946 CXXConversionDecl *Conversion =
6947 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6948 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6949
6950 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6951 if (!Converter.SuppressConversion) {
6952 if (SemaRef.isSFINAEContext())
6953 return true;
6954
6955 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6956 << From->getSourceRange();
6957 }
6958
6959 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6960 HadMultipleCandidates);
6961 if (Result.isInvalid())
6962 return true;
6963 // Record usage of conversion in an implicit cast.
6964 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6965 CK_UserDefinedConversion, Result.get(),
6966 nullptr, Result.get()->getValueKind(),
6967 SemaRef.CurFPFeatureOverrides());
6968 return false;
6969}
6970
6972 Sema &SemaRef, SourceLocation Loc, Expr *From,
6974 if (!Converter.match(From->getType()) && !Converter.Suppress)
6975 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6976 << From->getSourceRange();
6977
6978 return SemaRef.DefaultLvalueConversion(From);
6979}
6980
6981static void
6983 UnresolvedSetImpl &ViableConversions,
6984 OverloadCandidateSet &CandidateSet) {
6985 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6986 NamedDecl *D = FoundDecl.getDecl();
6987 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6988 if (isa<UsingShadowDecl>(D))
6989 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6990
6991 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6993 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6994 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6995 continue;
6996 }
6998 SemaRef.AddConversionCandidate(
6999 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7000 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7001 }
7002}
7003
7004/// Attempt to convert the given expression to a type which is accepted
7005/// by the given converter.
7006///
7007/// This routine will attempt to convert an expression of class type to a
7008/// type accepted by the specified converter. In C++11 and before, the class
7009/// must have a single non-explicit conversion function converting to a matching
7010/// type. In C++1y, there can be multiple such conversion functions, but only
7011/// one target type.
7012///
7013/// \param Loc The source location of the construct that requires the
7014/// conversion.
7015///
7016/// \param From The expression we're converting from.
7017///
7018/// \param Converter Used to control and diagnose the conversion process.
7019///
7020/// \returns The expression, converted to an integral or enumeration type if
7021/// successful.
7023 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7024 // We can't perform any more checking for type-dependent expressions.
7025 if (From->isTypeDependent())
7026 return From;
7027
7028 // Process placeholders immediately.
7029 if (From->hasPlaceholderType()) {
7030 ExprResult result = CheckPlaceholderExpr(From);
7031 if (result.isInvalid())
7032 return result;
7033 From = result.get();
7034 }
7035
7036 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7037 ExprResult Converted = DefaultLvalueConversion(From);
7038 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7039 From = Converted.isUsable() ? Converted.get() : nullptr;
7040 // If the expression already has a matching type, we're golden.
7041 if (Converter.match(T))
7042 return Converted;
7043
7044 // FIXME: Check for missing '()' if T is a function type?
7045
7046 // We can only perform contextual implicit conversions on objects of class
7047 // type.
7048 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7049 if (!RecordTy || !getLangOpts().CPlusPlus) {
7050 if (!Converter.Suppress)
7051 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7052 return From;
7053 }
7054
7055 // We must have a complete class type.
7056 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7057 ContextualImplicitConverter &Converter;
7058 Expr *From;
7059
7060 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7061 : Converter(Converter), From(From) {}
7062
7063 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7064 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7065 }
7066 } IncompleteDiagnoser(Converter, From);
7067
7068 if (Converter.Suppress ? !isCompleteType(Loc, T)
7069 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7070 return From;
7071
7072 // Look for a conversion to an integral or enumeration type.
7074 ViableConversions; // These are *potentially* viable in C++1y.
7075 UnresolvedSet<4> ExplicitConversions;
7076 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7077 ->getDefinitionOrSelf()
7078 ->getVisibleConversionFunctions();
7079
7080 bool HadMultipleCandidates =
7081 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7082
7083 // To check that there is only one target type, in C++1y:
7084 QualType ToType;
7085 bool HasUniqueTargetType = true;
7086
7087 // Collect explicit or viable (potentially in C++1y) conversions.
7088 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7089 NamedDecl *D = (*I)->getUnderlyingDecl();
7090 CXXConversionDecl *Conversion;
7091 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7092 if (ConvTemplate) {
7094 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7095 else
7096 continue; // C++11 does not consider conversion operator templates(?).
7097 } else
7098 Conversion = cast<CXXConversionDecl>(D);
7099
7100 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7101 "Conversion operator templates are considered potentially "
7102 "viable in C++1y");
7103
7104 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7105 if (Converter.match(CurToType) || ConvTemplate) {
7106
7107 if (Conversion->isExplicit()) {
7108 // FIXME: For C++1y, do we need this restriction?
7109 // cf. diagnoseNoViableConversion()
7110 if (!ConvTemplate)
7111 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7112 } else {
7113 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7114 if (ToType.isNull())
7115 ToType = CurToType.getUnqualifiedType();
7116 else if (HasUniqueTargetType &&
7117 (CurToType.getUnqualifiedType() != ToType))
7118 HasUniqueTargetType = false;
7119 }
7120 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7121 }
7122 }
7123 }
7124
7125 if (getLangOpts().CPlusPlus14) {
7126 // C++1y [conv]p6:
7127 // ... An expression e of class type E appearing in such a context
7128 // is said to be contextually implicitly converted to a specified
7129 // type T and is well-formed if and only if e can be implicitly
7130 // converted to a type T that is determined as follows: E is searched
7131 // for conversion functions whose return type is cv T or reference to
7132 // cv T such that T is allowed by the context. There shall be
7133 // exactly one such T.
7134
7135 // If no unique T is found:
7136 if (ToType.isNull()) {
7137 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7138 HadMultipleCandidates,
7139 ExplicitConversions))
7140 return ExprError();
7141 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7142 }
7143
7144 // If more than one unique Ts are found:
7145 if (!HasUniqueTargetType)
7146 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7147 ViableConversions);
7148
7149 // If one unique T is found:
7150 // First, build a candidate set from the previously recorded
7151 // potentially viable conversions.
7153 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7154 CandidateSet);
7155
7156 // Then, perform overload resolution over the candidate set.
7158 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7159 case OR_Success: {
7160 // Apply this conversion.
7162 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7163 if (recordConversion(*this, Loc, From, Converter, T,
7164 HadMultipleCandidates, Found))
7165 return ExprError();
7166 break;
7167 }
7168 case OR_Ambiguous:
7169 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7170 ViableConversions);
7172 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7173 HadMultipleCandidates,
7174 ExplicitConversions))
7175 return ExprError();
7176 [[fallthrough]];
7177 case OR_Deleted:
7178 // We'll complain below about a non-integral condition type.
7179 break;
7180 }
7181 } else {
7182 switch (ViableConversions.size()) {
7183 case 0: {
7184 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7185 HadMultipleCandidates,
7186 ExplicitConversions))
7187 return ExprError();
7188
7189 // We'll complain below about a non-integral condition type.
7190 break;
7191 }
7192 case 1: {
7193 // Apply this conversion.
7194 DeclAccessPair Found = ViableConversions[0];
7195 if (recordConversion(*this, Loc, From, Converter, T,
7196 HadMultipleCandidates, Found))
7197 return ExprError();
7198 break;
7199 }
7200 default:
7201 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7202 ViableConversions);
7203 }
7204 }
7205
7206 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7207}
7208
7209/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7210/// an acceptable non-member overloaded operator for a call whose
7211/// arguments have types T1 (and, if non-empty, T2). This routine
7212/// implements the check in C++ [over.match.oper]p3b2 concerning
7213/// enumeration types.
7215 FunctionDecl *Fn,
7216 ArrayRef<Expr *> Args) {
7217 QualType T1 = Args[0]->getType();
7218 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7219
7220 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7221 return true;
7222
7223 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7224 return true;
7225
7226 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7227 if (Proto->getNumParams() < 1)
7228 return false;
7229
7230 if (T1->isEnumeralType()) {
7231 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7232 if (Context.hasSameUnqualifiedType(T1, ArgType))
7233 return true;
7234 }
7235
7236 if (Proto->getNumParams() < 2)
7237 return false;
7238
7239 if (!T2.isNull() && T2->isEnumeralType()) {
7240 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7241 if (Context.hasSameUnqualifiedType(T2, ArgType))
7242 return true;
7243 }
7244
7245 return false;
7246}
7247
7250 return false;
7251
7252 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7253 return FD->isTargetMultiVersion();
7254
7255 if (!FD->isMultiVersion())
7256 return false;
7257
7258 // Among multiple target versions consider either the default,
7259 // or the first non-default in the absence of default version.
7260 unsigned SeenAt = 0;
7261 unsigned I = 0;
7262 bool HasDefault = false;
7264 FD, [&](const FunctionDecl *CurFD) {
7265 if (FD == CurFD)
7266 SeenAt = I;
7267 else if (CurFD->isTargetMultiVersionDefault())
7268 HasDefault = true;
7269 ++I;
7270 });
7271 return HasDefault || SeenAt != 0;
7272}
7273
7276 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7277 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7278 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7279 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7280 bool StrictPackMatch) {
7281 const FunctionProtoType *Proto
7282 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7283 assert(Proto && "Functions without a prototype cannot be overloaded");
7284 assert(!Function->getDescribedFunctionTemplate() &&
7285 "Use AddTemplateOverloadCandidate for function templates");
7286
7287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7289 // If we get here, it's because we're calling a member function
7290 // that is named without a member access expression (e.g.,
7291 // "this->f") that was either written explicitly or created
7292 // implicitly. This can happen with a qualified call to a member
7293 // function, e.g., X::f(). We use an empty type for the implied
7294 // object argument (C++ [over.call.func]p3), and the acting context
7295 // is irrelevant.
7296 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7298 CandidateSet, SuppressUserConversions,
7299 PartialOverloading, EarlyConversions, PO,
7300 StrictPackMatch);
7301 return;
7302 }
7303 // We treat a constructor like a non-member function, since its object
7304 // argument doesn't participate in overload resolution.
7305 }
7306
7307 if (!CandidateSet.isNewCandidate(Function, PO))
7308 return;
7309
7310 // C++11 [class.copy]p11: [DR1402]
7311 // A defaulted move constructor that is defined as deleted is ignored by
7312 // overload resolution.
7313 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7314 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7315 Constructor->isMoveConstructor())
7316 return;
7317
7318 // Overload resolution is always an unevaluated context.
7321
7322 // C++ [over.match.oper]p3:
7323 // if no operand has a class type, only those non-member functions in the
7324 // lookup set that have a first parameter of type T1 or "reference to
7325 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7326 // is a right operand) a second parameter of type T2 or "reference to
7327 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7328 // candidate functions.
7329 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7331 return;
7332
7333 // Add this candidate
7334 OverloadCandidate &Candidate =
7335 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7336 Candidate.FoundDecl = FoundDecl;
7337 Candidate.Function = Function;
7338 Candidate.Viable = true;
7339 Candidate.RewriteKind =
7340 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7341 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7342 Candidate.ExplicitCallArguments = Args.size();
7343 Candidate.StrictPackMatch = StrictPackMatch;
7344
7345 // Explicit functions are not actually candidates at all if we're not
7346 // allowing them in this context, but keep them around so we can point
7347 // to them in diagnostics.
7348 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7349 Candidate.Viable = false;
7350 Candidate.FailureKind = ovl_fail_explicit;
7351 return;
7352 }
7353
7354 // Functions with internal linkage are only viable in the same module unit.
7355 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7356 /// FIXME: Currently, the semantics of linkage in clang is slightly
7357 /// different from the semantics in C++ spec. In C++ spec, only names
7358 /// have linkage. So that all entities of the same should share one
7359 /// linkage. But in clang, different entities of the same could have
7360 /// different linkage.
7361 const NamedDecl *ND = Function;
7362 bool IsImplicitlyInstantiated = false;
7363 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7364 ND = SpecInfo->getTemplate();
7365 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7367 }
7368
7369 /// Don't remove inline functions with internal linkage from the overload
7370 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7371 /// However:
7372 /// - Inline functions with internal linkage are a common pattern in
7373 /// headers to avoid ODR issues.
7374 /// - The global module is meant to be a transition mechanism for C and C++
7375 /// headers, and the current rules as written work against that goal.
7376 const bool IsInlineFunctionInGMF =
7377 Function->isFromGlobalModule() &&
7378 (IsImplicitlyInstantiated || Function->isInlined());
7379
7380 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7381 Candidate.Viable = false;
7383 return;
7384 }
7385 }
7386
7388 Candidate.Viable = false;
7390 return;
7391 }
7392
7393 if (Constructor) {
7394 // C++ [class.copy]p3:
7395 // A member function template is never instantiated to perform the copy
7396 // of a class object to an object of its class type.
7397 CanQualType ClassType =
7398 Context.getCanonicalTagType(Constructor->getParent());
7399 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7400 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7401 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7402 ClassType))) {
7403 Candidate.Viable = false;
7405 return;
7406 }
7407
7408 // C++ [over.match.funcs]p8: (proposed DR resolution)
7409 // A constructor inherited from class type C that has a first parameter
7410 // of type "reference to P" (including such a constructor instantiated
7411 // from a template) is excluded from the set of candidate functions when
7412 // constructing an object of type cv D if the argument list has exactly
7413 // one argument and D is reference-related to P and P is reference-related
7414 // to C.
7415 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7416 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7417 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7418 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7419 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7420 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7421 SourceLocation Loc = Args.front()->getExprLoc();
7422 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7423 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7424 Candidate.Viable = false;
7426 return;
7427 }
7428 }
7429
7430 // Check that the constructor is capable of constructing an object in the
7431 // destination address space.
7433 Constructor->getMethodQualifiers().getAddressSpace(),
7434 CandidateSet.getDestAS(), getASTContext())) {
7435 Candidate.Viable = false;
7437 }
7438 }
7439
7440 unsigned NumParams = Proto->getNumParams();
7441
7442 // (C++ 13.3.2p2): A candidate function having fewer than m
7443 // parameters is viable only if it has an ellipsis in its parameter
7444 // list (8.3.5).
7445 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7446 !Proto->isVariadic() &&
7447 shouldEnforceArgLimit(PartialOverloading, Function)) {
7448 Candidate.Viable = false;
7450 return;
7451 }
7452
7453 // (C++ 13.3.2p2): A candidate function having more than m parameters
7454 // is viable only if the (m+1)st parameter has a default argument
7455 // (8.3.6). For the purposes of overload resolution, the
7456 // parameter list is truncated on the right, so that there are
7457 // exactly m parameters.
7458 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7459 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7460 !PartialOverloading) {
7461 // Not enough arguments.
7462 Candidate.Viable = false;
7464 return;
7465 }
7466
7467 // (CUDA B.1): Check for invalid calls between targets.
7468 if (getLangOpts().CUDA) {
7469 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7470 // Skip the check for callers that are implicit members, because in this
7471 // case we may not yet know what the member's target is; the target is
7472 // inferred for the member automatically, based on the bases and fields of
7473 // the class.
7474 if (!(Caller && Caller->isImplicit()) &&
7475 !CUDA().IsAllowedCall(Caller, Function)) {
7476 Candidate.Viable = false;
7477 Candidate.FailureKind = ovl_fail_bad_target;
7478 return;
7479 }
7480 }
7481
7482 if (Function->getTrailingRequiresClause()) {
7483 ConstraintSatisfaction Satisfaction;
7484 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7485 /*ForOverloadResolution*/ true) ||
7486 !Satisfaction.IsSatisfied) {
7487 Candidate.Viable = false;
7489 return;
7490 }
7491 }
7492
7493 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7494 // Determine the implicit conversion sequences for each of the
7495 // arguments.
7496 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7497 unsigned ConvIdx =
7498 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7499 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7500 // We already formed a conversion sequence for this parameter during
7501 // template argument deduction.
7502 } else if (ArgIdx < NumParams) {
7503 // (C++ 13.3.2p3): for F to be a viable function, there shall
7504 // exist for each argument an implicit conversion sequence
7505 // (13.3.3.1) that converts that argument to the corresponding
7506 // parameter of F.
7507 QualType ParamType = Proto->getParamType(ArgIdx);
7508 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7509 if (ParamABI == ParameterABI::HLSLOut ||
7510 ParamABI == ParameterABI::HLSLInOut) {
7511 ParamType = ParamType.getNonReferenceType();
7512 if (ParamABI == ParameterABI::HLSLInOut &&
7513 Args[ArgIdx]->getType().getAddressSpace() ==
7515 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7516 }
7517 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7518 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7519 /*InOverloadResolution=*/true,
7520 /*AllowObjCWritebackConversion=*/
7521 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7522 if (Candidate.Conversions[ConvIdx].isBad()) {
7523 Candidate.Viable = false;
7525 return;
7526 }
7527 } else {
7528 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7529 // argument for which there is no corresponding parameter is
7530 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7531 Candidate.Conversions[ConvIdx].setEllipsis();
7532 }
7533 }
7534
7535 if (EnableIfAttr *FailedAttr =
7536 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7537 Candidate.Viable = false;
7538 Candidate.FailureKind = ovl_fail_enable_if;
7539 Candidate.DeductionFailure.Data = FailedAttr;
7540 return;
7541 }
7542}
7543
7547 if (Methods.size() <= 1)
7548 return nullptr;
7549
7550 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7551 bool Match = true;
7552 ObjCMethodDecl *Method = Methods[b];
7553 unsigned NumNamedArgs = Sel.getNumArgs();
7554 // Method might have more arguments than selector indicates. This is due
7555 // to addition of c-style arguments in method.
7556 if (Method->param_size() > NumNamedArgs)
7557 NumNamedArgs = Method->param_size();
7558 if (Args.size() < NumNamedArgs)
7559 continue;
7560
7561 for (unsigned i = 0; i < NumNamedArgs; i++) {
7562 // We can't do any type-checking on a type-dependent argument.
7563 if (Args[i]->isTypeDependent()) {
7564 Match = false;
7565 break;
7566 }
7567
7568 ParmVarDecl *param = Method->parameters()[i];
7569 Expr *argExpr = Args[i];
7570 assert(argExpr && "SelectBestMethod(): missing expression");
7571
7572 // Strip the unbridged-cast placeholder expression off unless it's
7573 // a consumed argument.
7574 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7575 !param->hasAttr<CFConsumedAttr>())
7576 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7577
7578 // If the parameter is __unknown_anytype, move on to the next method.
7579 if (param->getType() == Context.UnknownAnyTy) {
7580 Match = false;
7581 break;
7582 }
7583
7584 ImplicitConversionSequence ConversionState
7585 = TryCopyInitialization(*this, argExpr, param->getType(),
7586 /*SuppressUserConversions*/false,
7587 /*InOverloadResolution=*/true,
7588 /*AllowObjCWritebackConversion=*/
7589 getLangOpts().ObjCAutoRefCount,
7590 /*AllowExplicit*/false);
7591 // This function looks for a reasonably-exact match, so we consider
7592 // incompatible pointer conversions to be a failure here.
7593 if (ConversionState.isBad() ||
7594 (ConversionState.isStandard() &&
7595 ConversionState.Standard.Second ==
7597 Match = false;
7598 break;
7599 }
7600 }
7601 // Promote additional arguments to variadic methods.
7602 if (Match && Method->isVariadic()) {
7603 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7604 if (Args[i]->isTypeDependent()) {
7605 Match = false;
7606 break;
7607 }
7609 Args[i], VariadicCallType::Method, nullptr);
7610 if (Arg.isInvalid()) {
7611 Match = false;
7612 break;
7613 }
7614 }
7615 } else {
7616 // Check for extra arguments to non-variadic methods.
7617 if (Args.size() != NumNamedArgs)
7618 Match = false;
7619 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7620 // Special case when selectors have no argument. In this case, select
7621 // one with the most general result type of 'id'.
7622 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7623 QualType ReturnT = Methods[b]->getReturnType();
7624 if (ReturnT->isObjCIdType())
7625 return Methods[b];
7626 }
7627 }
7628 }
7629
7630 if (Match)
7631 return Method;
7632 }
7633 return nullptr;
7634}
7635
7637 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7638 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7639 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7640 if (ThisArg) {
7641 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7642 assert(!isa<CXXConstructorDecl>(Method) &&
7643 "Shouldn't have `this` for ctors!");
7644 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7646 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7647 if (R.isInvalid())
7648 return false;
7649 ConvertedThis = R.get();
7650 } else {
7651 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7652 (void)MD;
7653 assert((MissingImplicitThis || MD->isStatic() ||
7655 "Expected `this` for non-ctor instance methods");
7656 }
7657 ConvertedThis = nullptr;
7658 }
7659
7660 // Ignore any variadic arguments. Converting them is pointless, since the
7661 // user can't refer to them in the function condition.
7662 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7663
7664 // Convert the arguments.
7665 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7666 ExprResult R;
7668 S.Context, Function->getParamDecl(I)),
7669 SourceLocation(), Args[I]);
7670
7671 if (R.isInvalid())
7672 return false;
7673
7674 ConvertedArgs.push_back(R.get());
7675 }
7676
7677 if (Trap.hasErrorOccurred())
7678 return false;
7679
7680 // Push default arguments if needed.
7681 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7682 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7683 ParmVarDecl *P = Function->getParamDecl(i);
7684 if (!P->hasDefaultArg())
7685 return false;
7686 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7687 if (R.isInvalid())
7688 return false;
7689 ConvertedArgs.push_back(R.get());
7690 }
7691
7692 if (Trap.hasErrorOccurred())
7693 return false;
7694 }
7695 return true;
7696}
7697
7699 SourceLocation CallLoc,
7700 ArrayRef<Expr *> Args,
7701 bool MissingImplicitThis) {
7702 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7703 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7704 return nullptr;
7705
7706 SFINAETrap Trap(*this);
7707 // Perform the access checking immediately so any access diagnostics are
7708 // caught by the SFINAE trap.
7709 llvm::scope_exit UndelayDiags(
7710 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7711 DelayedDiagnostics.popUndelayed(CurrentState);
7712 });
7713 SmallVector<Expr *, 16> ConvertedArgs;
7714 // FIXME: We should look into making enable_if late-parsed.
7715 Expr *DiscardedThis;
7717 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7718 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7719 return *EnableIfAttrs.begin();
7720
7721 for (auto *EIA : EnableIfAttrs) {
7723 // FIXME: This doesn't consider value-dependent cases, because doing so is
7724 // very difficult. Ideally, we should handle them more gracefully.
7725 if (EIA->getCond()->isValueDependent() ||
7726 !EIA->getCond()->EvaluateWithSubstitution(
7727 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7728 return EIA;
7729
7730 if (!Result.isInt() || !Result.getInt().getBoolValue())
7731 return EIA;
7732 }
7733 return nullptr;
7734}
7735
7736template <typename CheckFn>
7738 bool ArgDependent, SourceLocation Loc,
7739 CheckFn &&IsSuccessful) {
7741 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7742 if (ArgDependent == DIA->getArgDependent())
7743 Attrs.push_back(DIA);
7744 }
7745
7746 // Common case: No diagnose_if attributes, so we can quit early.
7747 if (Attrs.empty())
7748 return false;
7749
7750 auto WarningBegin = std::stable_partition(
7751 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7752 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7753 DIA->getWarningGroup().empty();
7754 });
7755
7756 // Note that diagnose_if attributes are late-parsed, so they appear in the
7757 // correct order (unlike enable_if attributes).
7758 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7759 IsSuccessful);
7760 if (ErrAttr != WarningBegin) {
7761 const DiagnoseIfAttr *DIA = *ErrAttr;
7762 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7763 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7764 << DIA->getParent() << DIA->getCond()->getSourceRange();
7765 return true;
7766 }
7767
7768 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7769 switch (Sev) {
7770 case DiagnoseIfAttr::DS_warning:
7772 case DiagnoseIfAttr::DS_error:
7773 return diag::Severity::Error;
7774 }
7775 llvm_unreachable("Fully covered switch above!");
7776 };
7777
7778 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7779 if (IsSuccessful(DIA)) {
7780 if (DIA->getWarningGroup().empty() &&
7781 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7782 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7783 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7784 << DIA->getParent() << DIA->getCond()->getSourceRange();
7785 } else {
7786 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7787 DIA->getWarningGroup());
7788 assert(DiagGroup);
7789 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7790 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7791 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7792 S.Diag(Loc, DiagID) << DIA->getMessage();
7793 }
7794 }
7795
7796 return false;
7797}
7798
7800 const Expr *ThisArg,
7802 SourceLocation Loc) {
7804 *this, Function, /*ArgDependent=*/true, Loc,
7805 [&](const DiagnoseIfAttr *DIA) {
7807 // It's sane to use the same Args for any redecl of this function, since
7808 // EvaluateWithSubstitution only cares about the position of each
7809 // argument in the arg list, not the ParmVarDecl* it maps to.
7810 if (!DIA->getCond()->EvaluateWithSubstitution(
7811 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7812 return false;
7813 return Result.isInt() && Result.getInt().getBoolValue();
7814 });
7815}
7816
7818 SourceLocation Loc) {
7820 *this, ND, /*ArgDependent=*/false, Loc,
7821 [&](const DiagnoseIfAttr *DIA) {
7822 bool Result;
7823 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7824 Result;
7825 });
7826}
7827
7829 ArrayRef<Expr *> Args,
7830 OverloadCandidateSet &CandidateSet,
7831 TemplateArgumentListInfo *ExplicitTemplateArgs,
7832 bool SuppressUserConversions,
7833 bool PartialOverloading,
7834 bool FirstArgumentIsBase) {
7835 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7836 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7837 ArrayRef<Expr *> FunctionArgs = Args;
7838
7839 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7840 FunctionDecl *FD =
7841 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7842
7843 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7844 QualType ObjectType;
7845 Expr::Classification ObjectClassification;
7846 if (Args.size() > 0) {
7847 if (Expr *E = Args[0]) {
7848 // Use the explicit base to restrict the lookup:
7849 ObjectType = E->getType();
7850 // Pointers in the object arguments are implicitly dereferenced, so we
7851 // always classify them as l-values.
7852 if (!ObjectType.isNull() && ObjectType->isPointerType())
7853 ObjectClassification = Expr::Classification::makeSimpleLValue();
7854 else
7855 ObjectClassification = E->Classify(Context);
7856 } // .. else there is an implicit base.
7857 FunctionArgs = Args.slice(1);
7858 }
7859 if (FunTmpl) {
7861 FunTmpl, F.getPair(),
7863 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7864 FunctionArgs, CandidateSet, SuppressUserConversions,
7865 PartialOverloading);
7866 } else {
7867 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7868 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7869 ObjectClassification, FunctionArgs, CandidateSet,
7870 SuppressUserConversions, PartialOverloading);
7871 }
7872 } else {
7873 // This branch handles both standalone functions and static methods.
7874
7875 // Slice the first argument (which is the base) when we access
7876 // static method as non-static.
7877 if (Args.size() > 0 &&
7878 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7879 !isa<CXXConstructorDecl>(FD)))) {
7880 assert(cast<CXXMethodDecl>(FD)->isStatic());
7881 FunctionArgs = Args.slice(1);
7882 }
7883 if (FunTmpl) {
7884 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7885 ExplicitTemplateArgs, FunctionArgs,
7886 CandidateSet, SuppressUserConversions,
7887 PartialOverloading);
7888 } else {
7889 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7890 SuppressUserConversions, PartialOverloading);
7891 }
7892 }
7893 }
7894}
7895
7897 Expr::Classification ObjectClassification,
7898 ArrayRef<Expr *> Args,
7899 OverloadCandidateSet &CandidateSet,
7900 bool SuppressUserConversions,
7902 NamedDecl *Decl = FoundDecl.getDecl();
7904
7906 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7907
7908 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7909 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7910 "Expected a member function template");
7911 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7912 /*ExplicitArgs*/ nullptr, ObjectType,
7913 ObjectClassification, Args, CandidateSet,
7914 SuppressUserConversions, false, PO);
7915 } else {
7916 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7917 ObjectType, ObjectClassification, Args, CandidateSet,
7918 SuppressUserConversions, false, {}, PO);
7919 }
7920}
7921
7924 CXXRecordDecl *ActingContext, QualType ObjectType,
7925 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7926 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7927 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7928 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7929 const FunctionProtoType *Proto
7930 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7931 assert(Proto && "Methods without a prototype cannot be overloaded");
7933 "Use AddOverloadCandidate for constructors");
7934
7935 if (!CandidateSet.isNewCandidate(Method, PO))
7936 return;
7937
7938 // C++11 [class.copy]p23: [DR1402]
7939 // A defaulted move assignment operator that is defined as deleted is
7940 // ignored by overload resolution.
7941 if (Method->isDefaulted() && Method->isDeleted() &&
7942 Method->isMoveAssignmentOperator())
7943 return;
7944
7945 // Overload resolution is always an unevaluated context.
7948
7949 bool IgnoreExplicitObject =
7950 (Method->isExplicitObjectMemberFunction() &&
7951 CandidateSet.getKind() ==
7953 bool ImplicitObjectMethodTreatedAsStatic =
7954 CandidateSet.getKind() ==
7956 Method->isImplicitObjectMemberFunction();
7957
7958 unsigned ExplicitOffset =
7959 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7960
7961 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7962 int(ImplicitObjectMethodTreatedAsStatic);
7963
7964 unsigned ExtraArgs =
7966 ? 0
7967 : 1;
7968
7969 // Add this candidate
7970 OverloadCandidate &Candidate =
7971 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7972 Candidate.FoundDecl = FoundDecl;
7973 Candidate.Function = Method;
7974 Candidate.RewriteKind =
7975 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7976 Candidate.TookAddressOfOverload =
7978 Candidate.ExplicitCallArguments = Args.size();
7979 Candidate.StrictPackMatch = StrictPackMatch;
7980
7981 // (C++ 13.3.2p2): A candidate function having fewer than m
7982 // parameters is viable only if it has an ellipsis in its parameter
7983 // list (8.3.5).
7984 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7985 !Proto->isVariadic() &&
7986 shouldEnforceArgLimit(PartialOverloading, Method)) {
7987 Candidate.Viable = false;
7989 return;
7990 }
7991
7992 // (C++ 13.3.2p2): A candidate function having more than m parameters
7993 // is viable only if the (m+1)st parameter has a default argument
7994 // (8.3.6). For the purposes of overload resolution, the
7995 // parameter list is truncated on the right, so that there are
7996 // exactly m parameters.
7997 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7998 ExplicitOffset +
7999 int(ImplicitObjectMethodTreatedAsStatic);
8000
8001 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8002 // Not enough arguments.
8003 Candidate.Viable = false;
8005 return;
8006 }
8007
8008 Candidate.Viable = true;
8009
8010 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8011 if (!IgnoreExplicitObject) {
8012 if (ObjectType.isNull())
8013 Candidate.IgnoreObjectArgument = true;
8014 else if (Method->isStatic()) {
8015 // [over.best.ics.general]p8
8016 // When the parameter is the implicit object parameter of a static member
8017 // function, the implicit conversion sequence is a standard conversion
8018 // sequence that is neither better nor worse than any other standard
8019 // conversion sequence.
8020 //
8021 // This is a rule that was introduced in C++23 to support static lambdas.
8022 // We apply it retroactively because we want to support static lambdas as
8023 // an extension and it doesn't hurt previous code.
8024 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8025 } else {
8026 // Determine the implicit conversion sequence for the object
8027 // parameter.
8028 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8029 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8030 Method, ActingContext, /*InOverloadResolution=*/true);
8031 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8032 Candidate.Viable = false;
8034 return;
8035 }
8036 }
8037 }
8038
8039 // (CUDA B.1): Check for invalid calls between targets.
8040 if (getLangOpts().CUDA)
8041 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8042 Method)) {
8043 Candidate.Viable = false;
8044 Candidate.FailureKind = ovl_fail_bad_target;
8045 return;
8046 }
8047
8048 if (Method->getTrailingRequiresClause()) {
8049 ConstraintSatisfaction Satisfaction;
8050 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8051 /*ForOverloadResolution*/ true) ||
8052 !Satisfaction.IsSatisfied) {
8053 Candidate.Viable = false;
8055 return;
8056 }
8057 }
8058
8059 // Determine the implicit conversion sequences for each of the
8060 // arguments.
8061 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8062 unsigned ConvIdx =
8063 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8064 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8065 // We already formed a conversion sequence for this parameter during
8066 // template argument deduction.
8067 } else if (ArgIdx < NumParams) {
8068 // (C++ 13.3.2p3): for F to be a viable function, there shall
8069 // exist for each argument an implicit conversion sequence
8070 // (13.3.3.1) that converts that argument to the corresponding
8071 // parameter of F.
8072 QualType ParamType;
8073 if (ImplicitObjectMethodTreatedAsStatic) {
8074 ParamType = ArgIdx == 0
8075 ? Method->getFunctionObjectParameterReferenceType()
8076 : Proto->getParamType(ArgIdx - 1);
8077 } else {
8078 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8079 }
8080 Candidate.Conversions[ConvIdx]
8081 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8082 SuppressUserConversions,
8083 /*InOverloadResolution=*/true,
8084 /*AllowObjCWritebackConversion=*/
8085 getLangOpts().ObjCAutoRefCount);
8086 if (Candidate.Conversions[ConvIdx].isBad()) {
8087 Candidate.Viable = false;
8089 return;
8090 }
8091 } else {
8092 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8093 // argument for which there is no corresponding parameter is
8094 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8095 Candidate.Conversions[ConvIdx].setEllipsis();
8096 }
8097 }
8098
8099 if (EnableIfAttr *FailedAttr =
8100 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8101 Candidate.Viable = false;
8102 Candidate.FailureKind = ovl_fail_enable_if;
8103 Candidate.DeductionFailure.Data = FailedAttr;
8104 return;
8105 }
8106
8108 Candidate.Viable = false;
8110 }
8111}
8112
8114 Sema &S, OverloadCandidateSet &CandidateSet,
8115 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8116 CXXRecordDecl *ActingContext,
8117 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8118 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8119 bool SuppressUserConversions, bool PartialOverloading,
8121
8122 // C++ [over.match.funcs]p7:
8123 // In each case where a candidate is a function template, candidate
8124 // function template specializations are generated using template argument
8125 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8126 // candidate functions in the usual way.113) A given name can refer to one
8127 // or more function templates and also to a set of overloaded non-template
8128 // functions. In such a case, the candidate functions generated from each
8129 // function template are combined with the set of non-template candidate
8130 // functions.
8131 TemplateDeductionInfo Info(CandidateSet.getLocation());
8132 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8133 FunctionDecl *Specialization = nullptr;
8134 ConversionSequenceList Conversions;
8136 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8137 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8138 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8139 CandidateSet.getKind() ==
8141 [&](ArrayRef<QualType> ParamTypes,
8142 bool OnlyInitializeNonUserDefinedConversions) {
8143 return S.CheckNonDependentConversions(
8144 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8145 Sema::CheckNonDependentConversionsFlag(
8146 SuppressUserConversions,
8147 OnlyInitializeNonUserDefinedConversions),
8148 ActingContext, ObjectType, ObjectClassification, PO);
8149 });
8151 OverloadCandidate &Candidate =
8152 CandidateSet.addCandidate(Conversions.size(), Conversions);
8153 Candidate.FoundDecl = FoundDecl;
8154 Candidate.Function = Method;
8155 Candidate.Viable = false;
8156 Candidate.RewriteKind =
8157 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8158 Candidate.IsSurrogate = false;
8159 Candidate.TookAddressOfOverload =
8160 CandidateSet.getKind() ==
8162
8163 Candidate.IgnoreObjectArgument =
8164 Method->isStatic() ||
8165 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8166 Candidate.ExplicitCallArguments = Args.size();
8169 else {
8171 Candidate.DeductionFailure =
8173 }
8174 return;
8175 }
8176
8177 // Add the function template specialization produced by template argument
8178 // deduction as a candidate.
8179 assert(Specialization && "Missing member function template specialization?");
8181 "Specialization is not a member function?");
8183 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8184 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8185 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8186}
8187
8189 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8190 CXXRecordDecl *ActingContext,
8191 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8192 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8193 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8194 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8195 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8196 return;
8197
8198 if (ExplicitTemplateArgs ||
8199 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8201 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8202 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8203 SuppressUserConversions, PartialOverloading, PO);
8204 return;
8205 }
8206
8208 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8209 Args, SuppressUserConversions, PartialOverloading, PO);
8210}
8211
8212/// Determine whether a given function template has a simple explicit specifier
8213/// or a non-value-dependent explicit-specification that evaluates to true.
8217
8222
8224 Sema &S, OverloadCandidateSet &CandidateSet,
8226 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8227 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8229 bool AggregateCandidateDeduction) {
8230
8231 // If the function template has a non-dependent explicit specification,
8232 // exclude it now if appropriate; we are not permitted to perform deduction
8233 // and substitution in this case.
8234 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8235 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8236 Candidate.FoundDecl = FoundDecl;
8237 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8238 Candidate.Viable = false;
8239 Candidate.FailureKind = ovl_fail_explicit;
8240 return;
8241 }
8242
8243 // C++ [over.match.funcs]p7:
8244 // In each case where a candidate is a function template, candidate
8245 // function template specializations are generated using template argument
8246 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8247 // candidate functions in the usual way.113) A given name can refer to one
8248 // or more function templates and also to a set of overloaded non-template
8249 // functions. In such a case, the candidate functions generated from each
8250 // function template are combined with the set of non-template candidate
8251 // functions.
8252 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8253 FunctionTemplate->getTemplateDepth());
8254 FunctionDecl *Specialization = nullptr;
8255 ConversionSequenceList Conversions;
8257 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8258 PartialOverloading, AggregateCandidateDeduction,
8259 /*PartialOrdering=*/false,
8260 /*ObjectType=*/QualType(),
8261 /*ObjectClassification=*/Expr::Classification(),
8262 CandidateSet.getKind() ==
8264 [&](ArrayRef<QualType> ParamTypes,
8265 bool OnlyInitializeNonUserDefinedConversions) {
8266 return S.CheckNonDependentConversions(
8267 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8268 Sema::CheckNonDependentConversionsFlag(
8269 SuppressUserConversions,
8270 OnlyInitializeNonUserDefinedConversions),
8271 nullptr, QualType(), {}, PO);
8272 });
8274 OverloadCandidate &Candidate =
8275 CandidateSet.addCandidate(Conversions.size(), Conversions);
8276 Candidate.FoundDecl = FoundDecl;
8277 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8278 Candidate.Viable = false;
8279 Candidate.RewriteKind =
8280 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8281 Candidate.IsSurrogate = false;
8282 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8283 // Ignore the object argument if there is one, since we don't have an object
8284 // type.
8285 Candidate.TookAddressOfOverload =
8286 CandidateSet.getKind() ==
8288
8289 Candidate.IgnoreObjectArgument =
8290 isa<CXXMethodDecl>(Candidate.Function) &&
8291 !cast<CXXMethodDecl>(Candidate.Function)
8292 ->isExplicitObjectMemberFunction() &&
8294
8295 Candidate.ExplicitCallArguments = Args.size();
8298 else {
8300 Candidate.DeductionFailure =
8302 }
8303 return;
8304 }
8305
8306 // Add the function template specialization produced by template argument
8307 // deduction as a candidate.
8308 assert(Specialization && "Missing function template specialization?");
8310 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8311 PartialOverloading, AllowExplicit,
8312 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8313 Info.AggregateDeductionCandidateHasMismatchedArity,
8314 Info.hasStrictPackMatch());
8315}
8316
8319 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8320 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8321 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8322 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8323 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8324 return;
8325
8326 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8327
8328 if (ExplicitTemplateArgs ||
8329 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8330 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8331 DependentExplicitSpecifier)) {
8332
8334 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8335 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8336 IsADLCandidate, PO, AggregateCandidateDeduction);
8337
8338 if (DependentExplicitSpecifier)
8340 return;
8341 }
8342
8343 CandidateSet.AddDeferredTemplateCandidate(
8344 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8345 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8346 AggregateCandidateDeduction);
8347}
8348
8351 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8353 CheckNonDependentConversionsFlag UserConversionFlag,
8354 CXXRecordDecl *ActingContext, QualType ObjectType,
8355 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8356 // FIXME: The cases in which we allow explicit conversions for constructor
8357 // arguments never consider calling a constructor template. It's not clear
8358 // that is correct.
8359 const bool AllowExplicit = false;
8360
8361 bool ForOverloadSetAddressResolution =
8363 auto *FD = FunctionTemplate->getTemplatedDecl();
8364 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8365 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8367 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8368
8369 if (Conversions.empty())
8370 Conversions =
8371 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8372
8373 // Overload resolution is always an unevaluated context.
8376
8377 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8378 // require that, but this check should never result in a hard error, and
8379 // overload resolution is permitted to sidestep instantiations.
8380 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8381 !ObjectType.isNull()) {
8382 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8383 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8384 !ParamTypes[0]->isDependentType()) {
8386 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8387 Method, ActingContext, /*InOverloadResolution=*/true,
8388 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8389 : QualType());
8390 if (Conversions[ConvIdx].isBad())
8391 return true;
8392 }
8393 }
8394
8395 // A speculative workaround for self-dependent constraint bugs that manifest
8396 // after CWG2369.
8397 // FIXME: Add references to the standard once P3606 is adopted.
8398 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8399 QualType ArgType) {
8400 ParamType = ParamType.getNonReferenceType();
8401 ArgType = ArgType.getNonReferenceType();
8402 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8403 if (PointerConv) {
8404 ParamType = ParamType->getPointeeType();
8405 ArgType = ArgType->getPointeeType();
8406 }
8407
8408 if (auto *RD = ParamType->getAsCXXRecordDecl();
8409 RD && RD->hasDefinition() &&
8410 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8411 auto Info = getConstructorInfo(ND);
8412 if (!Info)
8413 return false;
8414 CXXConstructorDecl *Ctor = Info.Constructor;
8415 /// isConvertingConstructor takes copy/move constructors into
8416 /// account!
8417 return !Ctor->isCopyOrMoveConstructor() &&
8419 /*AllowExplicit=*/true);
8420 }))
8421 return true;
8422 if (auto *RD = ArgType->getAsCXXRecordDecl();
8423 RD && RD->hasDefinition() &&
8424 !RD->getVisibleConversionFunctions().empty())
8425 return true;
8426
8427 return false;
8428 };
8429
8430 unsigned Offset =
8431 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8432 : 0;
8433
8434 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8435 I != N; ++I) {
8436 QualType ParamType = ParamTypes[I + Offset];
8437 if (!ParamType->isDependentType()) {
8438 unsigned ConvIdx;
8440 ConvIdx = Args.size() - 1 - I;
8441 assert(Args.size() + ThisConversions == 2 &&
8442 "number of args (including 'this') must be exactly 2 for "
8443 "reversed order");
8444 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8445 // would also be 0. 'this' got ConvIdx = 1 previously.
8446 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8447 } else {
8448 // For members, 'this' got ConvIdx = 0 previously.
8449 ConvIdx = ThisConversions + I;
8450 }
8451 if (Conversions[ConvIdx].isInitialized())
8452 continue;
8453 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8454 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8455 continue;
8457 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8458 /*InOverloadResolution=*/true,
8459 /*AllowObjCWritebackConversion=*/
8460 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8461 if (Conversions[ConvIdx].isBad())
8462 return true;
8463 }
8464 }
8465
8466 return false;
8467}
8468
8469/// Determine whether this is an allowable conversion from the result
8470/// of an explicit conversion operator to the expected type, per C++
8471/// [over.match.conv]p1 and [over.match.ref]p1.
8472///
8473/// \param ConvType The return type of the conversion function.
8474///
8475/// \param ToType The type we are converting to.
8476///
8477/// \param AllowObjCPointerConversion Allow a conversion from one
8478/// Objective-C pointer to another.
8479///
8480/// \returns true if the conversion is allowable, false otherwise.
8482 QualType ConvType, QualType ToType,
8483 bool AllowObjCPointerConversion) {
8484 QualType ToNonRefType = ToType.getNonReferenceType();
8485
8486 // Easy case: the types are the same.
8487 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8488 return true;
8489
8490 // Allow qualification conversions.
8491 bool ObjCLifetimeConversion;
8492 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8493 ObjCLifetimeConversion))
8494 return true;
8495
8496 // If we're not allowed to consider Objective-C pointer conversions,
8497 // we're done.
8498 if (!AllowObjCPointerConversion)
8499 return false;
8500
8501 // Is this an Objective-C pointer conversion?
8502 bool IncompatibleObjC = false;
8503 QualType ConvertedType;
8504 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8505 IncompatibleObjC);
8506}
8507
8509 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8510 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8511 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8512 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8513 assert(!Conversion->getDescribedFunctionTemplate() &&
8514 "Conversion function templates use AddTemplateConversionCandidate");
8515 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8516 if (!CandidateSet.isNewCandidate(Conversion))
8517 return;
8518
8519 // If the conversion function has an undeduced return type, trigger its
8520 // deduction now.
8521 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8522 if (DeduceReturnType(Conversion, From->getExprLoc()))
8523 return;
8524 ConvType = Conversion->getConversionType().getNonReferenceType();
8525 }
8526
8527 // If we don't allow any conversion of the result type, ignore conversion
8528 // functions that don't convert to exactly (possibly cv-qualified) T.
8529 if (!AllowResultConversion &&
8530 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8531 return;
8532
8533 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8534 // operator is only a candidate if its return type is the target type or
8535 // can be converted to the target type with a qualification conversion.
8536 //
8537 // FIXME: Include such functions in the candidate list and explain why we
8538 // can't select them.
8539 if (Conversion->isExplicit() &&
8540 !isAllowableExplicitConversion(*this, ConvType, ToType,
8541 AllowObjCConversionOnExplicit))
8542 return;
8543
8544 // Overload resolution is always an unevaluated context.
8547
8548 // Add this candidate
8549 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8550 Candidate.FoundDecl = FoundDecl;
8551 Candidate.Function = Conversion;
8553 Candidate.FinalConversion.setFromType(ConvType);
8554 Candidate.FinalConversion.setAllToTypes(ToType);
8555 Candidate.HasFinalConversion = true;
8556 Candidate.Viable = true;
8557 Candidate.ExplicitCallArguments = 1;
8558 Candidate.StrictPackMatch = StrictPackMatch;
8559
8560 // Explicit functions are not actually candidates at all if we're not
8561 // allowing them in this context, but keep them around so we can point
8562 // to them in diagnostics.
8563 if (!AllowExplicit && Conversion->isExplicit()) {
8564 Candidate.Viable = false;
8565 Candidate.FailureKind = ovl_fail_explicit;
8566 return;
8567 }
8568
8569 // C++ [over.match.funcs]p4:
8570 // For conversion functions, the function is considered to be a member of
8571 // the class of the implicit implied object argument for the purpose of
8572 // defining the type of the implicit object parameter.
8573 //
8574 // Determine the implicit conversion sequence for the implicit
8575 // object parameter.
8576 QualType ObjectType = From->getType();
8577 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8578 ObjectType = FromPtrType->getPointeeType();
8579 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8580 // C++23 [over.best.ics.general]
8581 // However, if the target is [...]
8582 // - the object parameter of a user-defined conversion function
8583 // [...] user-defined conversion sequences are not considered.
8585 *this, CandidateSet.getLocation(), From->getType(),
8586 From->Classify(Context), Conversion, ConversionContext,
8587 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8588 /*SuppressUserConversion*/ true);
8589
8590 if (Candidate.Conversions[0].isBad()) {
8591 Candidate.Viable = false;
8593 return;
8594 }
8595
8596 if (Conversion->getTrailingRequiresClause()) {
8597 ConstraintSatisfaction Satisfaction;
8598 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8599 !Satisfaction.IsSatisfied) {
8600 Candidate.Viable = false;
8602 return;
8603 }
8604 }
8605
8606 // We won't go through a user-defined type conversion function to convert a
8607 // derived to base as such conversions are given Conversion Rank. They only
8608 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8609 QualType FromCanon
8610 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8611 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8612 if (FromCanon == ToCanon ||
8613 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8614 Candidate.Viable = false;
8616 return;
8617 }
8618
8619 // To determine what the conversion from the result of calling the
8620 // conversion function to the type we're eventually trying to
8621 // convert to (ToType), we need to synthesize a call to the
8622 // conversion function and attempt copy initialization from it. This
8623 // makes sure that we get the right semantics with respect to
8624 // lvalues/rvalues and the type. Fortunately, we can allocate this
8625 // call on the stack and we don't need its arguments to be
8626 // well-formed.
8627 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8628 VK_LValue, From->getBeginLoc());
8630 Context.getPointerType(Conversion->getType()),
8631 CK_FunctionToPointerDecay, &ConversionRef,
8633
8634 QualType ConversionType = Conversion->getConversionType();
8635 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8636 Candidate.Viable = false;
8638 return;
8639 }
8640
8641 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8642
8643 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8644
8645 // Introduce a temporary expression with the right type and value category
8646 // that we can use for deduction purposes.
8647 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8648
8650 TryCopyInitialization(*this, &FakeCall, ToType,
8651 /*SuppressUserConversions=*/true,
8652 /*InOverloadResolution=*/false,
8653 /*AllowObjCWritebackConversion=*/false);
8654
8655 switch (ICS.getKind()) {
8657 Candidate.FinalConversion = ICS.Standard;
8658 Candidate.HasFinalConversion = true;
8659
8660 // C++ [over.ics.user]p3:
8661 // If the user-defined conversion is specified by a specialization of a
8662 // conversion function template, the second standard conversion sequence
8663 // shall have exact match rank.
8664 if (Conversion->getPrimaryTemplate() &&
8666 Candidate.Viable = false;
8668 return;
8669 }
8670
8671 // C++0x [dcl.init.ref]p5:
8672 // In the second case, if the reference is an rvalue reference and
8673 // the second standard conversion sequence of the user-defined
8674 // conversion sequence includes an lvalue-to-rvalue conversion, the
8675 // program is ill-formed.
8676 if (ToType->isRValueReferenceType() &&
8678 Candidate.Viable = false;
8680 return;
8681 }
8682 break;
8683
8685 Candidate.Viable = false;
8687 return;
8688
8689 default:
8690 llvm_unreachable(
8691 "Can only end up with a standard conversion sequence or failure");
8692 }
8693
8694 if (EnableIfAttr *FailedAttr =
8695 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8696 Candidate.Viable = false;
8697 Candidate.FailureKind = ovl_fail_enable_if;
8698 Candidate.DeductionFailure.Data = FailedAttr;
8699 return;
8700 }
8701
8702 if (isNonViableMultiVersionOverload(Conversion)) {
8703 Candidate.Viable = false;
8705 }
8706}
8707
8709 Sema &S, OverloadCandidateSet &CandidateSet,
8711 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8712 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8713 bool AllowResultConversion) {
8714
8715 // If the function template has a non-dependent explicit specification,
8716 // exclude it now if appropriate; we are not permitted to perform deduction
8717 // and substitution in this case.
8718 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8719 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8720 Candidate.FoundDecl = FoundDecl;
8721 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8722 Candidate.Viable = false;
8723 Candidate.FailureKind = ovl_fail_explicit;
8724 return;
8725 }
8726
8727 QualType ObjectType = From->getType();
8728 Expr::Classification ObjectClassification = From->Classify(S.Context);
8729
8730 TemplateDeductionInfo Info(CandidateSet.getLocation());
8733 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8734 Specialization, Info);
8736 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8737 Candidate.FoundDecl = FoundDecl;
8738 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8739 Candidate.Viable = false;
8741 Candidate.ExplicitCallArguments = 1;
8742 Candidate.DeductionFailure =
8744 return;
8745 }
8746
8747 // Add the conversion function template specialization produced by
8748 // template argument deduction as a candidate.
8749 assert(Specialization && "Missing function template specialization?");
8750 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8751 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8752 AllowExplicit, AllowResultConversion,
8753 Info.hasStrictPackMatch());
8754}
8755
8758 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8759 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8760 bool AllowExplicit, bool AllowResultConversion) {
8761 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8762 "Only conversion function templates permitted here");
8763
8764 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8765 return;
8766
8767 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8768 CandidateSet.getKind() ==
8772 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8773 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8774 AllowResultConversion);
8775
8777 return;
8778 }
8779
8781 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8782 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8783}
8784
8786 DeclAccessPair FoundDecl,
8787 CXXRecordDecl *ActingContext,
8788 const FunctionProtoType *Proto,
8789 Expr *Object,
8790 ArrayRef<Expr *> Args,
8791 OverloadCandidateSet& CandidateSet) {
8792 if (!CandidateSet.isNewCandidate(Conversion))
8793 return;
8794
8795 // Overload resolution is always an unevaluated context.
8798
8799 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8800 Candidate.FoundDecl = FoundDecl;
8801 Candidate.Function = nullptr;
8802 Candidate.Surrogate = Conversion;
8803 Candidate.IsSurrogate = true;
8804 Candidate.Viable = true;
8805 Candidate.ExplicitCallArguments = Args.size();
8806
8807 // Determine the implicit conversion sequence for the implicit
8808 // object parameter.
8809 ImplicitConversionSequence ObjectInit;
8810 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8811 ObjectInit = TryCopyInitialization(*this, Object,
8812 Conversion->getParamDecl(0)->getType(),
8813 /*SuppressUserConversions=*/false,
8814 /*InOverloadResolution=*/true, false);
8815 } else {
8817 *this, CandidateSet.getLocation(), Object->getType(),
8818 Object->Classify(Context), Conversion, ActingContext);
8819 }
8820
8821 if (ObjectInit.isBad()) {
8822 Candidate.Viable = false;
8824 Candidate.Conversions[0] = ObjectInit;
8825 return;
8826 }
8827
8828 // The first conversion is actually a user-defined conversion whose
8829 // first conversion is ObjectInit's standard conversion (which is
8830 // effectively a reference binding). Record it as such.
8831 Candidate.Conversions[0].setUserDefined();
8832 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8833 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8834 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8835 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8836 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8837 Candidate.Conversions[0].UserDefined.After
8838 = Candidate.Conversions[0].UserDefined.Before;
8839 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8840
8841 // Find the
8842 unsigned NumParams = Proto->getNumParams();
8843
8844 // (C++ 13.3.2p2): A candidate function having fewer than m
8845 // parameters is viable only if it has an ellipsis in its parameter
8846 // list (8.3.5).
8847 if (Args.size() > NumParams && !Proto->isVariadic()) {
8848 Candidate.Viable = false;
8850 return;
8851 }
8852
8853 // Function types don't have any default arguments, so just check if
8854 // we have enough arguments.
8855 if (Args.size() < NumParams) {
8856 // Not enough arguments.
8857 Candidate.Viable = false;
8859 return;
8860 }
8861
8862 // Determine the implicit conversion sequences for each of the
8863 // arguments.
8864 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8865 if (ArgIdx < NumParams) {
8866 // (C++ 13.3.2p3): for F to be a viable function, there shall
8867 // exist for each argument an implicit conversion sequence
8868 // (13.3.3.1) that converts that argument to the corresponding
8869 // parameter of F.
8870 QualType ParamType = Proto->getParamType(ArgIdx);
8871 Candidate.Conversions[ArgIdx + 1]
8872 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8873 /*SuppressUserConversions=*/false,
8874 /*InOverloadResolution=*/false,
8875 /*AllowObjCWritebackConversion=*/
8876 getLangOpts().ObjCAutoRefCount);
8877 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8878 Candidate.Viable = false;
8880 return;
8881 }
8882 } else {
8883 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8884 // argument for which there is no corresponding parameter is
8885 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8886 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8887 }
8888 }
8889
8890 if (Conversion->getTrailingRequiresClause()) {
8891 ConstraintSatisfaction Satisfaction;
8892 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8893 /*ForOverloadResolution*/ true) ||
8894 !Satisfaction.IsSatisfied) {
8895 Candidate.Viable = false;
8897 return;
8898 }
8899 }
8900
8901 if (EnableIfAttr *FailedAttr =
8902 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8903 Candidate.Viable = false;
8904 Candidate.FailureKind = ovl_fail_enable_if;
8905 Candidate.DeductionFailure.Data = FailedAttr;
8906 return;
8907 }
8908}
8909
8911 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8912 OverloadCandidateSet &CandidateSet,
8913 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8914 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8915 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8916 ArrayRef<Expr *> FunctionArgs = Args;
8917
8918 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8919 FunctionDecl *FD =
8920 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8921
8922 // Don't consider rewritten functions if we're not rewriting.
8923 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8924 continue;
8925
8926 assert(!isa<CXXMethodDecl>(FD) &&
8927 "unqualified operator lookup found a member function");
8928
8929 if (FunTmpl) {
8930 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8931 FunctionArgs, CandidateSet);
8932 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8933
8934 // As template candidates are not deduced immediately,
8935 // persist the array in the overload set.
8937 FunctionArgs[1], FunctionArgs[0]);
8938 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8939 Reversed, CandidateSet, false, false, true,
8940 ADLCallKind::NotADL,
8942 }
8943 } else {
8944 if (ExplicitTemplateArgs)
8945 continue;
8946 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8947 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8948 AddOverloadCandidate(FD, F.getPair(),
8949 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8950 false, false, true, false, ADLCallKind::NotADL, {},
8952 }
8953 }
8954}
8955
8957 SourceLocation OpLoc,
8958 ArrayRef<Expr *> Args,
8959 OverloadCandidateSet &CandidateSet,
8961 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8962
8963 // C++ [over.match.oper]p3:
8964 // For a unary operator @ with an operand of a type whose
8965 // cv-unqualified version is T1, and for a binary operator @ with
8966 // a left operand of a type whose cv-unqualified version is T1 and
8967 // a right operand of a type whose cv-unqualified version is T2,
8968 // three sets of candidate functions, designated member
8969 // candidates, non-member candidates and built-in candidates, are
8970 // constructed as follows:
8971 QualType T1 = Args[0]->getType();
8972
8973 // -- If T1 is a complete class type or a class currently being
8974 // defined, the set of member candidates is the result of the
8975 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8976 // the set of member candidates is empty.
8977 if (T1->isRecordType()) {
8978 bool IsComplete = isCompleteType(OpLoc, T1);
8979 auto *T1RD = T1->getAsCXXRecordDecl();
8980 // Complete the type if it can be completed.
8981 // If the type is neither complete nor being defined, bail out now.
8982 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8983 return;
8984
8985 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8986 LookupQualifiedName(Operators, T1RD);
8987 Operators.suppressAccessDiagnostics();
8988
8989 for (LookupResult::iterator Oper = Operators.begin(),
8990 OperEnd = Operators.end();
8991 Oper != OperEnd; ++Oper) {
8992 if (Oper->getAsFunction() &&
8994 !CandidateSet.getRewriteInfo().shouldAddReversed(
8995 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8996 continue;
8997 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8998 Args[0]->Classify(Context), Args.slice(1),
8999 CandidateSet, /*SuppressUserConversion=*/false, PO);
9000 }
9001 }
9002}
9003
9005 OverloadCandidateSet& CandidateSet,
9006 bool IsAssignmentOperator,
9007 unsigned NumContextualBoolArguments) {
9008 // Overload resolution is always an unevaluated context.
9011
9012 // Add this candidate
9013 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9014 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9015 Candidate.Function = nullptr;
9016 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9017
9018 // Determine the implicit conversion sequences for each of the
9019 // arguments.
9020 Candidate.Viable = true;
9021 Candidate.ExplicitCallArguments = Args.size();
9022 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9023 // C++ [over.match.oper]p4:
9024 // For the built-in assignment operators, conversions of the
9025 // left operand are restricted as follows:
9026 // -- no temporaries are introduced to hold the left operand, and
9027 // -- no user-defined conversions are applied to the left
9028 // operand to achieve a type match with the left-most
9029 // parameter of a built-in candidate.
9030 //
9031 // We block these conversions by turning off user-defined
9032 // conversions, since that is the only way that initialization of
9033 // a reference to a non-class type can occur from something that
9034 // is not of the same type.
9035 if (ArgIdx < NumContextualBoolArguments) {
9036 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9037 "Contextual conversion to bool requires bool type");
9038 Candidate.Conversions[ArgIdx]
9039 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9040 } else {
9041 Candidate.Conversions[ArgIdx]
9042 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9043 ArgIdx == 0 && IsAssignmentOperator,
9044 /*InOverloadResolution=*/false,
9045 /*AllowObjCWritebackConversion=*/
9046 getLangOpts().ObjCAutoRefCount);
9047 }
9048 if (Candidate.Conversions[ArgIdx].isBad()) {
9049 Candidate.Viable = false;
9051 break;
9052 }
9053 }
9054}
9055
9056namespace {
9057
9058/// BuiltinCandidateTypeSet - A set of types that will be used for the
9059/// candidate operator functions for built-in operators (C++
9060/// [over.built]). The types are separated into pointer types and
9061/// enumeration types.
9062class BuiltinCandidateTypeSet {
9063 /// TypeSet - A set of types.
9064 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9065
9066 /// PointerTypes - The set of pointer types that will be used in the
9067 /// built-in candidates.
9068 TypeSet PointerTypes;
9069
9070 /// MemberPointerTypes - The set of member pointer types that will be
9071 /// used in the built-in candidates.
9072 TypeSet MemberPointerTypes;
9073
9074 /// EnumerationTypes - The set of enumeration types that will be
9075 /// used in the built-in candidates.
9076 TypeSet EnumerationTypes;
9077
9078 /// The set of vector types that will be used in the built-in
9079 /// candidates.
9080 TypeSet VectorTypes;
9081
9082 /// The set of matrix types that will be used in the built-in
9083 /// candidates.
9084 TypeSet MatrixTypes;
9085
9086 /// The set of _BitInt types that will be used in the built-in candidates.
9087 TypeSet BitIntTypes;
9088
9089 /// A flag indicating non-record types are viable candidates
9090 bool HasNonRecordTypes;
9091
9092 /// A flag indicating whether either arithmetic or enumeration types
9093 /// were present in the candidate set.
9094 bool HasArithmeticOrEnumeralTypes;
9095
9096 /// A flag indicating whether the nullptr type was present in the
9097 /// candidate set.
9098 bool HasNullPtrType;
9099
9100 /// Sema - The semantic analysis instance where we are building the
9101 /// candidate type set.
9102 Sema &SemaRef;
9103
9104 /// Context - The AST context in which we will build the type sets.
9105 ASTContext &Context;
9106
9107 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9108 const Qualifiers &VisibleQuals);
9109 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9110
9111public:
9112 /// iterator - Iterates through the types that are part of the set.
9113 typedef TypeSet::iterator iterator;
9114
9115 BuiltinCandidateTypeSet(Sema &SemaRef)
9116 : HasNonRecordTypes(false),
9117 HasArithmeticOrEnumeralTypes(false),
9118 HasNullPtrType(false),
9119 SemaRef(SemaRef),
9120 Context(SemaRef.Context) { }
9121
9122 void AddTypesConvertedFrom(QualType Ty,
9123 SourceLocation Loc,
9124 bool AllowUserConversions,
9125 bool AllowExplicitConversions,
9126 const Qualifiers &VisibleTypeConversionsQuals);
9127
9128 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9129 llvm::iterator_range<iterator> member_pointer_types() {
9130 return MemberPointerTypes;
9131 }
9132 llvm::iterator_range<iterator> enumeration_types() {
9133 return EnumerationTypes;
9134 }
9135 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9136 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9137 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9138
9139 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9140 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9141 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9142 bool hasNullPtrType() const { return HasNullPtrType; }
9143};
9144
9145} // end anonymous namespace
9146
9147/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9148/// the set of pointer types along with any more-qualified variants of
9149/// that type. For example, if @p Ty is "int const *", this routine
9150/// will add "int const *", "int const volatile *", "int const
9151/// restrict *", and "int const volatile restrict *" to the set of
9152/// pointer types. Returns true if the add of @p Ty itself succeeded,
9153/// false otherwise.
9154///
9155/// FIXME: what to do about extended qualifiers?
9156bool
9157BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9158 const Qualifiers &VisibleQuals) {
9159
9160 // Insert this type.
9161 if (!PointerTypes.insert(Ty))
9162 return false;
9163
9164 QualType PointeeTy;
9165 const PointerType *PointerTy = Ty->getAs<PointerType>();
9166 bool buildObjCPtr = false;
9167 if (!PointerTy) {
9168 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9169 PointeeTy = PTy->getPointeeType();
9170 buildObjCPtr = true;
9171 } else {
9172 PointeeTy = PointerTy->getPointeeType();
9173 }
9174
9175 // Don't add qualified variants of arrays. For one, they're not allowed
9176 // (the qualifier would sink to the element type), and for another, the
9177 // only overload situation where it matters is subscript or pointer +- int,
9178 // and those shouldn't have qualifier variants anyway.
9179 if (PointeeTy->isArrayType())
9180 return true;
9181
9182 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9183 bool hasVolatile = VisibleQuals.hasVolatile();
9184 bool hasRestrict = VisibleQuals.hasRestrict();
9185
9186 // Iterate through all strict supersets of BaseCVR.
9187 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9188 if ((CVR | BaseCVR) != CVR) continue;
9189 // Skip over volatile if no volatile found anywhere in the types.
9190 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9191
9192 // Skip over restrict if no restrict found anywhere in the types, or if
9193 // the type cannot be restrict-qualified.
9194 if ((CVR & Qualifiers::Restrict) &&
9195 (!hasRestrict ||
9196 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9197 continue;
9198
9199 // Build qualified pointee type.
9200 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9201
9202 // Build qualified pointer type.
9203 QualType QPointerTy;
9204 if (!buildObjCPtr)
9205 QPointerTy = Context.getPointerType(QPointeeTy);
9206 else
9207 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9208
9209 // Insert qualified pointer type.
9210 PointerTypes.insert(QPointerTy);
9211 }
9212
9213 return true;
9214}
9215
9216/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9217/// to the set of pointer types along with any more-qualified variants of
9218/// that type. For example, if @p Ty is "int const *", this routine
9219/// will add "int const *", "int const volatile *", "int const
9220/// restrict *", and "int const volatile restrict *" to the set of
9221/// pointer types. Returns true if the add of @p Ty itself succeeded,
9222/// false otherwise.
9223///
9224/// FIXME: what to do about extended qualifiers?
9225bool
9226BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9227 QualType Ty) {
9228 // Insert this type.
9229 if (!MemberPointerTypes.insert(Ty))
9230 return false;
9231
9232 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9233 assert(PointerTy && "type was not a member pointer type!");
9234
9235 QualType PointeeTy = PointerTy->getPointeeType();
9236 // Don't add qualified variants of arrays. For one, they're not allowed
9237 // (the qualifier would sink to the element type), and for another, the
9238 // only overload situation where it matters is subscript or pointer +- int,
9239 // and those shouldn't have qualifier variants anyway.
9240 if (PointeeTy->isArrayType())
9241 return true;
9242 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9243
9244 // Iterate through all strict supersets of the pointee type's CVR
9245 // qualifiers.
9246 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9247 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9248 if ((CVR | BaseCVR) != CVR) continue;
9249
9250 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9251 MemberPointerTypes.insert(Context.getMemberPointerType(
9252 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9253 }
9254
9255 return true;
9256}
9257
9258/// AddTypesConvertedFrom - Add each of the types to which the type @p
9259/// Ty can be implicit converted to the given set of @p Types. We're
9260/// primarily interested in pointer types and enumeration types. We also
9261/// take member pointer types, for the conditional operator.
9262/// AllowUserConversions is true if we should look at the conversion
9263/// functions of a class type, and AllowExplicitConversions if we
9264/// should also include the explicit conversion functions of a class
9265/// type.
9266void
9267BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9268 SourceLocation Loc,
9269 bool AllowUserConversions,
9270 bool AllowExplicitConversions,
9271 const Qualifiers &VisibleQuals) {
9272 // Only deal with canonical types.
9273 Ty = Context.getCanonicalType(Ty);
9274
9275 // Look through reference types; they aren't part of the type of an
9276 // expression for the purposes of conversions.
9277 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9278 Ty = RefTy->getPointeeType();
9279
9280 // If we're dealing with an array type, decay to the pointer.
9281 if (Ty->isArrayType())
9282 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9283
9284 // Otherwise, we don't care about qualifiers on the type.
9285 Ty = Ty.getLocalUnqualifiedType();
9286
9287 // Flag if we ever add a non-record type.
9288 bool TyIsRec = Ty->isRecordType();
9289 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9290
9291 // Flag if we encounter an arithmetic type.
9292 HasArithmeticOrEnumeralTypes =
9293 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9294
9295 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9296 PointerTypes.insert(Ty);
9297 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9298 // Insert our type, and its more-qualified variants, into the set
9299 // of types.
9300 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9301 return;
9302 } else if (Ty->isMemberPointerType()) {
9303 // Member pointers are far easier, since the pointee can't be converted.
9304 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9305 return;
9306 } else if (Ty->isEnumeralType()) {
9307 HasArithmeticOrEnumeralTypes = true;
9308 EnumerationTypes.insert(Ty);
9309 } else if (Ty->isBitIntType()) {
9310 HasArithmeticOrEnumeralTypes = true;
9311 BitIntTypes.insert(Ty);
9312 } else if (Ty->isVectorType()) {
9313 // We treat vector types as arithmetic types in many contexts as an
9314 // extension.
9315 HasArithmeticOrEnumeralTypes = true;
9316 VectorTypes.insert(Ty);
9317 } else if (Ty->isMatrixType()) {
9318 // Similar to vector types, we treat vector types as arithmetic types in
9319 // many contexts as an extension.
9320 HasArithmeticOrEnumeralTypes = true;
9321 MatrixTypes.insert(Ty);
9322 } else if (Ty->isNullPtrType()) {
9323 HasNullPtrType = true;
9324 } else if (AllowUserConversions && TyIsRec) {
9325 // No conversion functions in incomplete types.
9326 if (!SemaRef.isCompleteType(Loc, Ty))
9327 return;
9328
9329 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9330 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9331 if (isa<UsingShadowDecl>(D))
9332 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9333
9334 // Skip conversion function templates; they don't tell us anything
9335 // about which builtin types we can convert to.
9337 continue;
9338
9339 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9340 if (AllowExplicitConversions || !Conv->isExplicit()) {
9341 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9342 VisibleQuals);
9343 }
9344 }
9345 }
9346}
9347/// Helper function for adjusting address spaces for the pointer or reference
9348/// operands of builtin operators depending on the argument.
9353
9354/// Helper function for AddBuiltinOperatorCandidates() that adds
9355/// the volatile- and non-volatile-qualified assignment operators for the
9356/// given type to the candidate set.
9358 QualType T,
9359 ArrayRef<Expr *> Args,
9360 OverloadCandidateSet &CandidateSet) {
9361 QualType ParamTypes[2];
9362
9363 // T& operator=(T&, T)
9364 ParamTypes[0] = S.Context.getLValueReferenceType(
9366 ParamTypes[1] = T;
9367 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9368 /*IsAssignmentOperator=*/true);
9369
9371 // volatile T& operator=(volatile T&, T)
9372 ParamTypes[0] = S.Context.getLValueReferenceType(
9374 Args[0]));
9375 ParamTypes[1] = T;
9376 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9377 /*IsAssignmentOperator=*/true);
9378 }
9379}
9380
9381/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9382/// if any, found in visible type conversion functions found in ArgExpr's type.
9383static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9384 Qualifiers VRQuals;
9385 CXXRecordDecl *ClassDecl;
9386 if (const MemberPointerType *RHSMPType =
9387 ArgExpr->getType()->getAs<MemberPointerType>())
9388 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9389 else
9390 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9391 if (!ClassDecl) {
9392 // Just to be safe, assume the worst case.
9393 VRQuals.addVolatile();
9394 VRQuals.addRestrict();
9395 return VRQuals;
9396 }
9397 if (!ClassDecl->hasDefinition())
9398 return VRQuals;
9399
9400 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9401 if (isa<UsingShadowDecl>(D))
9402 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9403 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9404 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9405 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9406 CanTy = ResTypeRef->getPointeeType();
9407 // Need to go down the pointer/mempointer chain and add qualifiers
9408 // as see them.
9409 bool done = false;
9410 while (!done) {
9411 if (CanTy.isRestrictQualified())
9412 VRQuals.addRestrict();
9413 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9414 CanTy = ResTypePtr->getPointeeType();
9415 else if (const MemberPointerType *ResTypeMPtr =
9416 CanTy->getAs<MemberPointerType>())
9417 CanTy = ResTypeMPtr->getPointeeType();
9418 else
9419 done = true;
9420 if (CanTy.isVolatileQualified())
9421 VRQuals.addVolatile();
9422 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9423 return VRQuals;
9424 }
9425 }
9426 }
9427 return VRQuals;
9428}
9429
9430// Note: We're currently only handling qualifiers that are meaningful for the
9431// LHS of compound assignment overloading.
9433 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9434 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9435 // _Atomic
9436 if (Available.hasAtomic()) {
9437 Available.removeAtomic();
9438 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9439 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9440 return;
9441 }
9442
9443 // volatile
9444 if (Available.hasVolatile()) {
9445 Available.removeVolatile();
9446 assert(!Applied.hasVolatile());
9447 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9448 Callback);
9449 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9450 return;
9451 }
9452
9453 Callback(Applied);
9454}
9455
9457 QualifiersAndAtomic Quals,
9458 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9460 Callback);
9461}
9462
9464 QualifiersAndAtomic Quals,
9465 Sema &S) {
9466 if (Quals.hasAtomic())
9468 if (Quals.hasVolatile())
9471}
9472
9473namespace {
9474
9475/// Helper class to manage the addition of builtin operator overload
9476/// candidates. It provides shared state and utility methods used throughout
9477/// the process, as well as a helper method to add each group of builtin
9478/// operator overloads from the standard to a candidate set.
9479class BuiltinOperatorOverloadBuilder {
9480 // Common instance state available to all overload candidate addition methods.
9481 Sema &S;
9482 ArrayRef<Expr *> Args;
9483 QualifiersAndAtomic VisibleTypeConversionsQuals;
9484 bool HasArithmeticOrEnumeralCandidateType;
9485 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9486 OverloadCandidateSet &CandidateSet;
9487
9488 static constexpr int ArithmeticTypesCap = 26;
9489 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9490
9491 // Define some indices used to iterate over the arithmetic types in
9492 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9493 // types are that preserved by promotion (C++ [over.built]p2).
9494 unsigned FirstIntegralType,
9495 LastIntegralType;
9496 unsigned FirstPromotedIntegralType,
9497 LastPromotedIntegralType;
9498 unsigned FirstPromotedArithmeticType,
9499 LastPromotedArithmeticType;
9500 unsigned NumArithmeticTypes;
9501
9502 void InitArithmeticTypes() {
9503 // Start of promoted types.
9504 FirstPromotedArithmeticType = 0;
9505 ArithmeticTypes.push_back(S.Context.FloatTy);
9506 ArithmeticTypes.push_back(S.Context.DoubleTy);
9507 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9509 ArithmeticTypes.push_back(S.Context.Float128Ty);
9511 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9512
9513 // Start of integral types.
9514 FirstIntegralType = ArithmeticTypes.size();
9515 FirstPromotedIntegralType = ArithmeticTypes.size();
9516 ArithmeticTypes.push_back(S.Context.IntTy);
9517 ArithmeticTypes.push_back(S.Context.LongTy);
9518 ArithmeticTypes.push_back(S.Context.LongLongTy);
9522 ArithmeticTypes.push_back(S.Context.Int128Ty);
9523 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9524 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9525 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9529 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9530
9531 /// We add candidates for the unique, unqualified _BitInt types present in
9532 /// the candidate type set. The candidate set already handled ensuring the
9533 /// type is unqualified and canonical, but because we're adding from N
9534 /// different sets, we need to do some extra work to unique things. Insert
9535 /// the candidates into a unique set, then move from that set into the list
9536 /// of arithmetic types.
9537 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9538 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9539 for (QualType BitTy : Candidate.bitint_types())
9540 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9541 }
9542 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9543 LastPromotedIntegralType = ArithmeticTypes.size();
9544 LastPromotedArithmeticType = ArithmeticTypes.size();
9545 // End of promoted types.
9546
9547 ArithmeticTypes.push_back(S.Context.BoolTy);
9548 ArithmeticTypes.push_back(S.Context.CharTy);
9549 ArithmeticTypes.push_back(S.Context.WCharTy);
9550 if (S.Context.getLangOpts().Char8)
9551 ArithmeticTypes.push_back(S.Context.Char8Ty);
9552 ArithmeticTypes.push_back(S.Context.Char16Ty);
9553 ArithmeticTypes.push_back(S.Context.Char32Ty);
9554 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9555 ArithmeticTypes.push_back(S.Context.ShortTy);
9556 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9557 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9558 LastIntegralType = ArithmeticTypes.size();
9559 NumArithmeticTypes = ArithmeticTypes.size();
9560 // End of integral types.
9561 // FIXME: What about complex? What about half?
9562
9563 // We don't know for sure how many bit-precise candidates were involved, so
9564 // we subtract those from the total when testing whether we're under the
9565 // cap or not.
9566 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9567 ArithmeticTypesCap &&
9568 "Enough inline storage for all arithmetic types.");
9569 }
9570
9571 /// Helper method to factor out the common pattern of adding overloads
9572 /// for '++' and '--' builtin operators.
9573 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9574 bool HasVolatile,
9575 bool HasRestrict) {
9576 QualType ParamTypes[2] = {
9577 S.Context.getLValueReferenceType(CandidateTy),
9578 S.Context.IntTy
9579 };
9580
9581 // Non-volatile version.
9582 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9583
9584 // Use a heuristic to reduce number of builtin candidates in the set:
9585 // add volatile version only if there are conversions to a volatile type.
9586 if (HasVolatile) {
9587 ParamTypes[0] =
9589 S.Context.getVolatileType(CandidateTy));
9590 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9591 }
9592
9593 // Add restrict version only if there are conversions to a restrict type
9594 // and our candidate type is a non-restrict-qualified pointer.
9595 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9596 !CandidateTy.isRestrictQualified()) {
9597 ParamTypes[0]
9600 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9601
9602 if (HasVolatile) {
9603 ParamTypes[0]
9605 S.Context.getCVRQualifiedType(CandidateTy,
9608 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9609 }
9610 }
9611
9612 }
9613
9614 /// Helper to add an overload candidate for a binary builtin with types \p L
9615 /// and \p R.
9616 void AddCandidate(QualType L, QualType R) {
9617 QualType LandR[2] = {L, R};
9618 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9619 }
9620
9621public:
9622 BuiltinOperatorOverloadBuilder(
9623 Sema &S, ArrayRef<Expr *> Args,
9624 QualifiersAndAtomic VisibleTypeConversionsQuals,
9625 bool HasArithmeticOrEnumeralCandidateType,
9626 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9627 OverloadCandidateSet &CandidateSet)
9628 : S(S), Args(Args),
9629 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9630 HasArithmeticOrEnumeralCandidateType(
9631 HasArithmeticOrEnumeralCandidateType),
9632 CandidateTypes(CandidateTypes),
9633 CandidateSet(CandidateSet) {
9634
9635 InitArithmeticTypes();
9636 }
9637
9638 // Increment is deprecated for bool since C++17.
9639 //
9640 // C++ [over.built]p3:
9641 //
9642 // For every pair (T, VQ), where T is an arithmetic type other
9643 // than bool, and VQ is either volatile or empty, there exist
9644 // candidate operator functions of the form
9645 //
9646 // VQ T& operator++(VQ T&);
9647 // T operator++(VQ T&, int);
9648 //
9649 // C++ [over.built]p4:
9650 //
9651 // For every pair (T, VQ), where T is an arithmetic type other
9652 // than bool, and VQ is either volatile or empty, there exist
9653 // candidate operator functions of the form
9654 //
9655 // VQ T& operator--(VQ T&);
9656 // T operator--(VQ T&, int);
9657 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9658 if (!HasArithmeticOrEnumeralCandidateType)
9659 return;
9660
9661 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9662 const auto TypeOfT = ArithmeticTypes[Arith];
9663 if (TypeOfT == S.Context.BoolTy) {
9664 if (Op == OO_MinusMinus)
9665 continue;
9666 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9667 continue;
9668 }
9669 addPlusPlusMinusMinusStyleOverloads(
9670 TypeOfT,
9671 VisibleTypeConversionsQuals.hasVolatile(),
9672 VisibleTypeConversionsQuals.hasRestrict());
9673 }
9674 }
9675
9676 // C++ [over.built]p5:
9677 //
9678 // For every pair (T, VQ), where T is a cv-qualified or
9679 // cv-unqualified object type, and VQ is either volatile or
9680 // empty, there exist candidate operator functions of the form
9681 //
9682 // T*VQ& operator++(T*VQ&);
9683 // T*VQ& operator--(T*VQ&);
9684 // T* operator++(T*VQ&, int);
9685 // T* operator--(T*VQ&, int);
9686 void addPlusPlusMinusMinusPointerOverloads() {
9687 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9688 // Skip pointer types that aren't pointers to object types.
9689 if (!PtrTy->getPointeeType()->isObjectType())
9690 continue;
9691
9692 addPlusPlusMinusMinusStyleOverloads(
9693 PtrTy,
9694 (!PtrTy.isVolatileQualified() &&
9695 VisibleTypeConversionsQuals.hasVolatile()),
9696 (!PtrTy.isRestrictQualified() &&
9697 VisibleTypeConversionsQuals.hasRestrict()));
9698 }
9699 }
9700
9701 // C++ [over.built]p6:
9702 // For every cv-qualified or cv-unqualified object type T, there
9703 // exist candidate operator functions of the form
9704 //
9705 // T& operator*(T*);
9706 //
9707 // C++ [over.built]p7:
9708 // For every function type T that does not have cv-qualifiers or a
9709 // ref-qualifier, there exist candidate operator functions of the form
9710 // T& operator*(T*);
9711 void addUnaryStarPointerOverloads() {
9712 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9713 QualType PointeeTy = ParamTy->getPointeeType();
9714 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9715 continue;
9716
9717 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9718 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9719 continue;
9720
9721 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9722 }
9723 }
9724
9725 // C++ [over.built]p9:
9726 // For every promoted arithmetic type T, there exist candidate
9727 // operator functions of the form
9728 //
9729 // T operator+(T);
9730 // T operator-(T);
9731 void addUnaryPlusOrMinusArithmeticOverloads() {
9732 if (!HasArithmeticOrEnumeralCandidateType)
9733 return;
9734
9735 for (unsigned Arith = FirstPromotedArithmeticType;
9736 Arith < LastPromotedArithmeticType; ++Arith) {
9737 QualType ArithTy = ArithmeticTypes[Arith];
9738 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9739 }
9740
9741 // Extension: We also add these operators for vector types.
9742 for (QualType VecTy : CandidateTypes[0].vector_types())
9743 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9744 }
9745
9746 // C++ [over.built]p8:
9747 // For every type T, there exist candidate operator functions of
9748 // the form
9749 //
9750 // T* operator+(T*);
9751 void addUnaryPlusPointerOverloads() {
9752 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9753 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9754 }
9755
9756 // C++ [over.built]p10:
9757 // For every promoted integral type T, there exist candidate
9758 // operator functions of the form
9759 //
9760 // T operator~(T);
9761 void addUnaryTildePromotedIntegralOverloads() {
9762 if (!HasArithmeticOrEnumeralCandidateType)
9763 return;
9764
9765 for (unsigned Int = FirstPromotedIntegralType;
9766 Int < LastPromotedIntegralType; ++Int) {
9767 QualType IntTy = ArithmeticTypes[Int];
9768 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9769 }
9770
9771 // Extension: We also add this operator for vector types.
9772 for (QualType VecTy : CandidateTypes[0].vector_types())
9773 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9774 }
9775
9776 // C++ [over.match.oper]p16:
9777 // For every pointer to member type T or type std::nullptr_t, there
9778 // exist candidate operator functions of the form
9779 //
9780 // bool operator==(T,T);
9781 // bool operator!=(T,T);
9782 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9783 /// Set of (canonical) types that we've already handled.
9784 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9785
9786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9787 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9788 // Don't add the same builtin candidate twice.
9789 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9790 continue;
9791
9792 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9793 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9794 }
9795
9796 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9798 if (AddedTypes.insert(NullPtrTy).second) {
9799 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9801 }
9802 }
9803 }
9804 }
9805
9806 // C++ [over.built]p15:
9807 //
9808 // For every T, where T is an enumeration type or a pointer type,
9809 // there exist candidate operator functions of the form
9810 //
9811 // bool operator<(T, T);
9812 // bool operator>(T, T);
9813 // bool operator<=(T, T);
9814 // bool operator>=(T, T);
9815 // bool operator==(T, T);
9816 // bool operator!=(T, T);
9817 // R operator<=>(T, T)
9818 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9819 // C++ [over.match.oper]p3:
9820 // [...]the built-in candidates include all of the candidate operator
9821 // functions defined in 13.6 that, compared to the given operator, [...]
9822 // do not have the same parameter-type-list as any non-template non-member
9823 // candidate.
9824 //
9825 // Note that in practice, this only affects enumeration types because there
9826 // aren't any built-in candidates of record type, and a user-defined operator
9827 // must have an operand of record or enumeration type. Also, the only other
9828 // overloaded operator with enumeration arguments, operator=,
9829 // cannot be overloaded for enumeration types, so this is the only place
9830 // where we must suppress candidates like this.
9831 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9832 UserDefinedBinaryOperators;
9833
9834 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9835 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9836 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9837 CEnd = CandidateSet.end();
9838 C != CEnd; ++C) {
9839 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9840 continue;
9841
9842 if (C->Function->isFunctionTemplateSpecialization())
9843 continue;
9844
9845 // We interpret "same parameter-type-list" as applying to the
9846 // "synthesized candidate, with the order of the two parameters
9847 // reversed", not to the original function.
9848 bool Reversed = C->isReversed();
9849 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9850 ->getType()
9851 .getUnqualifiedType();
9852 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9853 ->getType()
9854 .getUnqualifiedType();
9855
9856 // Skip if either parameter isn't of enumeral type.
9857 if (!FirstParamType->isEnumeralType() ||
9858 !SecondParamType->isEnumeralType())
9859 continue;
9860
9861 // Add this operator to the set of known user-defined operators.
9862 UserDefinedBinaryOperators.insert(
9863 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9864 S.Context.getCanonicalType(SecondParamType)));
9865 }
9866 }
9867 }
9868
9869 /// Set of (canonical) types that we've already handled.
9870 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9871
9872 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9873 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9874 // Don't add the same builtin candidate twice.
9875 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9876 continue;
9877 if (IsSpaceship && PtrTy->isFunctionPointerType())
9878 continue;
9879
9880 QualType ParamTypes[2] = {PtrTy, PtrTy};
9881 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9882 }
9883 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9884 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9885
9886 // Don't add the same builtin candidate twice, or if a user defined
9887 // candidate exists.
9888 if (!AddedTypes.insert(CanonType).second ||
9889 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9890 CanonType)))
9891 continue;
9892 QualType ParamTypes[2] = {EnumTy, EnumTy};
9893 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9894 }
9895 }
9896 }
9897
9898 // C++ [over.built]p13:
9899 //
9900 // For every cv-qualified or cv-unqualified object type T
9901 // there exist candidate operator functions of the form
9902 //
9903 // T* operator+(T*, ptrdiff_t);
9904 // T& operator[](T*, ptrdiff_t); [BELOW]
9905 // T* operator-(T*, ptrdiff_t);
9906 // T* operator+(ptrdiff_t, T*);
9907 // T& operator[](ptrdiff_t, T*); [BELOW]
9908 //
9909 // C++ [over.built]p14:
9910 //
9911 // For every T, where T is a pointer to object type, there
9912 // exist candidate operator functions of the form
9913 //
9914 // ptrdiff_t operator-(T, T);
9915 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9916 /// Set of (canonical) types that we've already handled.
9917 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9918
9919 for (int Arg = 0; Arg < 2; ++Arg) {
9920 QualType AsymmetricParamTypes[2] = {
9923 };
9924 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9925 QualType PointeeTy = PtrTy->getPointeeType();
9926 if (!PointeeTy->isObjectType())
9927 continue;
9928
9929 AsymmetricParamTypes[Arg] = PtrTy;
9930 if (Arg == 0 || Op == OO_Plus) {
9931 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9932 // T* operator+(ptrdiff_t, T*);
9933 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9934 }
9935 if (Op == OO_Minus) {
9936 // ptrdiff_t operator-(T, T);
9937 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9938 continue;
9939
9940 QualType ParamTypes[2] = {PtrTy, PtrTy};
9941 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9942 }
9943 }
9944 }
9945 }
9946
9947 // C++ [over.built]p12:
9948 //
9949 // For every pair of promoted arithmetic types L and R, there
9950 // exist candidate operator functions of the form
9951 //
9952 // LR operator*(L, R);
9953 // LR operator/(L, R);
9954 // LR operator+(L, R);
9955 // LR operator-(L, R);
9956 // bool operator<(L, R);
9957 // bool operator>(L, R);
9958 // bool operator<=(L, R);
9959 // bool operator>=(L, R);
9960 // bool operator==(L, R);
9961 // bool operator!=(L, R);
9962 //
9963 // where LR is the result of the usual arithmetic conversions
9964 // between types L and R.
9965 //
9966 // C++ [over.built]p24:
9967 //
9968 // For every pair of promoted arithmetic types L and R, there exist
9969 // candidate operator functions of the form
9970 //
9971 // LR operator?(bool, L, R);
9972 //
9973 // where LR is the result of the usual arithmetic conversions
9974 // between types L and R.
9975 // Our candidates ignore the first parameter.
9976 void addGenericBinaryArithmeticOverloads() {
9977 if (!HasArithmeticOrEnumeralCandidateType)
9978 return;
9979
9980 for (unsigned Left = FirstPromotedArithmeticType;
9981 Left < LastPromotedArithmeticType; ++Left) {
9982 for (unsigned Right = FirstPromotedArithmeticType;
9983 Right < LastPromotedArithmeticType; ++Right) {
9984 QualType LandR[2] = { ArithmeticTypes[Left],
9985 ArithmeticTypes[Right] };
9986 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9987 }
9988 }
9989
9990 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9991 // conditional operator for vector types.
9992 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9993 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9994 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9995 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9996 }
9997 }
9998
9999 /// Add binary operator overloads for each candidate matrix type M1, M2:
10000 /// * (M1, M1) -> M1
10001 /// * (M1, M1.getElementType()) -> M1
10002 /// * (M2.getElementType(), M2) -> M2
10003 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10004 void addMatrixBinaryArithmeticOverloads() {
10005 if (!HasArithmeticOrEnumeralCandidateType)
10006 return;
10007
10008 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10009 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10010 AddCandidate(M1, M1);
10011 }
10012
10013 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10014 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10015 if (!CandidateTypes[0].containsMatrixType(M2))
10016 AddCandidate(M2, M2);
10017 }
10018 }
10019
10020 // C++2a [over.built]p14:
10021 //
10022 // For every integral type T there exists a candidate operator function
10023 // of the form
10024 //
10025 // std::strong_ordering operator<=>(T, T)
10026 //
10027 // C++2a [over.built]p15:
10028 //
10029 // For every pair of floating-point types L and R, there exists a candidate
10030 // operator function of the form
10031 //
10032 // std::partial_ordering operator<=>(L, R);
10033 //
10034 // FIXME: The current specification for integral types doesn't play nice with
10035 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10036 // comparisons. Under the current spec this can lead to ambiguity during
10037 // overload resolution. For example:
10038 //
10039 // enum A : int {a};
10040 // auto x = (a <=> (long)42);
10041 //
10042 // error: call is ambiguous for arguments 'A' and 'long'.
10043 // note: candidate operator<=>(int, int)
10044 // note: candidate operator<=>(long, long)
10045 //
10046 // To avoid this error, this function deviates from the specification and adds
10047 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10048 // arithmetic types (the same as the generic relational overloads).
10049 //
10050 // For now this function acts as a placeholder.
10051 void addThreeWayArithmeticOverloads() {
10052 addGenericBinaryArithmeticOverloads();
10053 }
10054
10055 // C++ [over.built]p17:
10056 //
10057 // For every pair of promoted integral types L and R, there
10058 // exist candidate operator functions of the form
10059 //
10060 // LR operator%(L, R);
10061 // LR operator&(L, R);
10062 // LR operator^(L, R);
10063 // LR operator|(L, R);
10064 // L operator<<(L, R);
10065 // L operator>>(L, R);
10066 //
10067 // where LR is the result of the usual arithmetic conversions
10068 // between types L and R.
10069 void addBinaryBitwiseArithmeticOverloads() {
10070 if (!HasArithmeticOrEnumeralCandidateType)
10071 return;
10072
10073 for (unsigned Left = FirstPromotedIntegralType;
10074 Left < LastPromotedIntegralType; ++Left) {
10075 for (unsigned Right = FirstPromotedIntegralType;
10076 Right < LastPromotedIntegralType; ++Right) {
10077 QualType LandR[2] = { ArithmeticTypes[Left],
10078 ArithmeticTypes[Right] };
10079 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10080 }
10081 }
10082 }
10083
10084 // C++ [over.built]p20:
10085 //
10086 // For every pair (T, VQ), where T is an enumeration or
10087 // pointer to member type and VQ is either volatile or
10088 // empty, there exist candidate operator functions of the form
10089 //
10090 // VQ T& operator=(VQ T&, T);
10091 void addAssignmentMemberPointerOrEnumeralOverloads() {
10092 /// Set of (canonical) types that we've already handled.
10093 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10094
10095 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10096 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10097 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10098 continue;
10099
10100 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10101 }
10102
10103 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10104 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10105 continue;
10106
10107 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10108 }
10109 }
10110 }
10111
10112 // C++ [over.built]p19:
10113 //
10114 // For every pair (T, VQ), where T is any type and VQ is either
10115 // volatile or empty, there exist candidate operator functions
10116 // of the form
10117 //
10118 // T*VQ& operator=(T*VQ&, T*);
10119 //
10120 // C++ [over.built]p21:
10121 //
10122 // For every pair (T, VQ), where T is a cv-qualified or
10123 // cv-unqualified object type and VQ is either volatile or
10124 // empty, there exist candidate operator functions of the form
10125 //
10126 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10127 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10128 void addAssignmentPointerOverloads(bool isEqualOp) {
10129 /// Set of (canonical) types that we've already handled.
10130 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10131
10132 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10133 // If this is operator=, keep track of the builtin candidates we added.
10134 if (isEqualOp)
10135 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10136 else if (!PtrTy->getPointeeType()->isObjectType())
10137 continue;
10138
10139 // non-volatile version
10140 QualType ParamTypes[2] = {
10142 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10143 };
10144 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10145 /*IsAssignmentOperator=*/ isEqualOp);
10146
10147 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10148 VisibleTypeConversionsQuals.hasVolatile();
10149 if (NeedVolatile) {
10150 // volatile version
10151 ParamTypes[0] =
10153 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10154 /*IsAssignmentOperator=*/isEqualOp);
10155 }
10156
10157 if (!PtrTy.isRestrictQualified() &&
10158 VisibleTypeConversionsQuals.hasRestrict()) {
10159 // restrict version
10160 ParamTypes[0] =
10162 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10163 /*IsAssignmentOperator=*/isEqualOp);
10164
10165 if (NeedVolatile) {
10166 // volatile restrict version
10167 ParamTypes[0] =
10170 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10171 /*IsAssignmentOperator=*/isEqualOp);
10172 }
10173 }
10174 }
10175
10176 if (isEqualOp) {
10177 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10178 // Make sure we don't add the same candidate twice.
10179 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10180 continue;
10181
10182 QualType ParamTypes[2] = {
10184 PtrTy,
10185 };
10186
10187 // non-volatile version
10188 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10189 /*IsAssignmentOperator=*/true);
10190
10191 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10192 VisibleTypeConversionsQuals.hasVolatile();
10193 if (NeedVolatile) {
10194 // volatile version
10195 ParamTypes[0] = S.Context.getLValueReferenceType(
10196 S.Context.getVolatileType(PtrTy));
10197 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10198 /*IsAssignmentOperator=*/true);
10199 }
10200
10201 if (!PtrTy.isRestrictQualified() &&
10202 VisibleTypeConversionsQuals.hasRestrict()) {
10203 // restrict version
10204 ParamTypes[0] = S.Context.getLValueReferenceType(
10205 S.Context.getRestrictType(PtrTy));
10206 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10207 /*IsAssignmentOperator=*/true);
10208
10209 if (NeedVolatile) {
10210 // volatile restrict version
10211 ParamTypes[0] =
10214 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10215 /*IsAssignmentOperator=*/true);
10216 }
10217 }
10218 }
10219 }
10220 }
10221
10222 // C++ [over.built]p18:
10223 //
10224 // For every triple (L, VQ, R), where L is an arithmetic type,
10225 // VQ is either volatile or empty, and R is a promoted
10226 // arithmetic type, there exist candidate operator functions of
10227 // the form
10228 //
10229 // VQ L& operator=(VQ L&, R);
10230 // VQ L& operator*=(VQ L&, R);
10231 // VQ L& operator/=(VQ L&, R);
10232 // VQ L& operator+=(VQ L&, R);
10233 // VQ L& operator-=(VQ L&, R);
10234 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10235 if (!HasArithmeticOrEnumeralCandidateType)
10236 return;
10237
10238 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10239 for (unsigned Right = FirstPromotedArithmeticType;
10240 Right < LastPromotedArithmeticType; ++Right) {
10241 QualType ParamTypes[2];
10242 ParamTypes[1] = ArithmeticTypes[Right];
10244 S, ArithmeticTypes[Left], Args[0]);
10245
10247 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10248 ParamTypes[0] =
10249 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10250 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10251 /*IsAssignmentOperator=*/isEqualOp);
10252 });
10253 }
10254 }
10255
10256 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10257 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10258 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10259 QualType ParamTypes[2];
10260 ParamTypes[1] = Vec2Ty;
10261 // Add this built-in operator as a candidate (VQ is empty).
10262 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10263 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10264 /*IsAssignmentOperator=*/isEqualOp);
10265
10266 // Add this built-in operator as a candidate (VQ is 'volatile').
10267 if (VisibleTypeConversionsQuals.hasVolatile()) {
10268 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10269 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10270 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10271 /*IsAssignmentOperator=*/isEqualOp);
10272 }
10273 }
10274 }
10275
10276 // C++ [over.built]p22:
10277 //
10278 // For every triple (L, VQ, R), where L is an integral type, VQ
10279 // is either volatile or empty, and R is a promoted integral
10280 // type, there exist candidate operator functions of the form
10281 //
10282 // VQ L& operator%=(VQ L&, R);
10283 // VQ L& operator<<=(VQ L&, R);
10284 // VQ L& operator>>=(VQ L&, R);
10285 // VQ L& operator&=(VQ L&, R);
10286 // VQ L& operator^=(VQ L&, R);
10287 // VQ L& operator|=(VQ L&, R);
10288 void addAssignmentIntegralOverloads() {
10289 if (!HasArithmeticOrEnumeralCandidateType)
10290 return;
10291
10292 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10293 for (unsigned Right = FirstPromotedIntegralType;
10294 Right < LastPromotedIntegralType; ++Right) {
10295 QualType ParamTypes[2];
10296 ParamTypes[1] = ArithmeticTypes[Right];
10298 S, ArithmeticTypes[Left], Args[0]);
10299
10301 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10302 ParamTypes[0] =
10303 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10304 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10305 });
10306 }
10307 }
10308 }
10309
10310 // C++ [over.operator]p23:
10311 //
10312 // There also exist candidate operator functions of the form
10313 //
10314 // bool operator!(bool);
10315 // bool operator&&(bool, bool);
10316 // bool operator||(bool, bool);
10317 void addExclaimOverload() {
10318 QualType ParamTy = S.Context.BoolTy;
10319 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10320 /*IsAssignmentOperator=*/false,
10321 /*NumContextualBoolArguments=*/1);
10322 }
10323 void addAmpAmpOrPipePipeOverload() {
10324 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10325 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10326 /*IsAssignmentOperator=*/false,
10327 /*NumContextualBoolArguments=*/2);
10328 }
10329
10330 // C++ [over.built]p13:
10331 //
10332 // For every cv-qualified or cv-unqualified object type T there
10333 // exist candidate operator functions of the form
10334 //
10335 // T* operator+(T*, ptrdiff_t); [ABOVE]
10336 // T& operator[](T*, ptrdiff_t);
10337 // T* operator-(T*, ptrdiff_t); [ABOVE]
10338 // T* operator+(ptrdiff_t, T*); [ABOVE]
10339 // T& operator[](ptrdiff_t, T*);
10340 void addSubscriptOverloads() {
10341 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10342 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10343 QualType PointeeType = PtrTy->getPointeeType();
10344 if (!PointeeType->isObjectType())
10345 continue;
10346
10347 // T& operator[](T*, ptrdiff_t)
10348 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10349 }
10350
10351 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10352 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10353 QualType PointeeType = PtrTy->getPointeeType();
10354 if (!PointeeType->isObjectType())
10355 continue;
10356
10357 // T& operator[](ptrdiff_t, T*)
10358 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10359 }
10360 }
10361
10362 // C++ [over.built]p11:
10363 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10364 // C1 is the same type as C2 or is a derived class of C2, T is an object
10365 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10366 // there exist candidate operator functions of the form
10367 //
10368 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10369 //
10370 // where CV12 is the union of CV1 and CV2.
10371 void addArrowStarOverloads() {
10372 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10373 QualType C1Ty = PtrTy;
10374 QualType C1;
10375 QualifierCollector Q1;
10376 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10377 if (!isa<RecordType>(C1))
10378 continue;
10379 // heuristic to reduce number of builtin candidates in the set.
10380 // Add volatile/restrict version only if there are conversions to a
10381 // volatile/restrict type.
10382 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10383 continue;
10384 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10385 continue;
10386 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10387 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10388 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10389 *D2 = mptr->getMostRecentCXXRecordDecl();
10390 if (!declaresSameEntity(D1, D2) &&
10391 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10392 break;
10393 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10394 // build CV12 T&
10395 QualType T = mptr->getPointeeType();
10396 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10398 continue;
10399 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10401 continue;
10402 T = Q1.apply(S.Context, T);
10403 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10404 }
10405 }
10406 }
10407
10408 // Note that we don't consider the first argument, since it has been
10409 // contextually converted to bool long ago. The candidates below are
10410 // therefore added as binary.
10411 //
10412 // C++ [over.built]p25:
10413 // For every type T, where T is a pointer, pointer-to-member, or scoped
10414 // enumeration type, there exist candidate operator functions of the form
10415 //
10416 // T operator?(bool, T, T);
10417 //
10418 void addConditionalOperatorOverloads() {
10419 /// Set of (canonical) types that we've already handled.
10420 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10421
10422 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10423 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10424 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10425 continue;
10426
10427 QualType ParamTypes[2] = {PtrTy, PtrTy};
10428 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10429 }
10430
10431 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10432 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10433 continue;
10434
10435 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10436 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10437 }
10438
10439 if (S.getLangOpts().CPlusPlus11) {
10440 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10441 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10442 continue;
10443
10444 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10445 continue;
10446
10447 QualType ParamTypes[2] = {EnumTy, EnumTy};
10448 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10449 }
10450 }
10451 }
10452 }
10453};
10454
10455} // end anonymous namespace
10456
10458 SourceLocation OpLoc,
10459 ArrayRef<Expr *> Args,
10460 OverloadCandidateSet &CandidateSet) {
10461 // Find all of the types that the arguments can convert to, but only
10462 // if the operator we're looking at has built-in operator candidates
10463 // that make use of these types. Also record whether we encounter non-record
10464 // candidate types or either arithmetic or enumeral candidate types.
10465 QualifiersAndAtomic VisibleTypeConversionsQuals;
10466 VisibleTypeConversionsQuals.addConst();
10467 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10468 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10469 if (Args[ArgIdx]->getType()->isAtomicType())
10470 VisibleTypeConversionsQuals.addAtomic();
10471 }
10472
10473 bool HasNonRecordCandidateType = false;
10474 bool HasArithmeticOrEnumeralCandidateType = false;
10476 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10477 CandidateTypes.emplace_back(*this);
10478 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10479 OpLoc,
10480 true,
10481 (Op == OO_Exclaim ||
10482 Op == OO_AmpAmp ||
10483 Op == OO_PipePipe),
10484 VisibleTypeConversionsQuals);
10485 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10486 CandidateTypes[ArgIdx].hasNonRecordTypes();
10487 HasArithmeticOrEnumeralCandidateType =
10488 HasArithmeticOrEnumeralCandidateType ||
10489 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10490 }
10491
10492 // Exit early when no non-record types have been added to the candidate set
10493 // for any of the arguments to the operator.
10494 //
10495 // We can't exit early for !, ||, or &&, since there we have always have
10496 // 'bool' overloads.
10497 if (!HasNonRecordCandidateType &&
10498 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10499 return;
10500
10501 // Setup an object to manage the common state for building overloads.
10502 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10503 VisibleTypeConversionsQuals,
10504 HasArithmeticOrEnumeralCandidateType,
10505 CandidateTypes, CandidateSet);
10506
10507 // Dispatch over the operation to add in only those overloads which apply.
10508 switch (Op) {
10509 case OO_None:
10511 llvm_unreachable("Expected an overloaded operator");
10512
10513 case OO_New:
10514 case OO_Delete:
10515 case OO_Array_New:
10516 case OO_Array_Delete:
10517 case OO_Call:
10518 llvm_unreachable(
10519 "Special operators don't use AddBuiltinOperatorCandidates");
10520
10521 case OO_Comma:
10522 case OO_Arrow:
10523 case OO_Coawait:
10524 // C++ [over.match.oper]p3:
10525 // -- For the operator ',', the unary operator '&', the
10526 // operator '->', or the operator 'co_await', the
10527 // built-in candidates set is empty.
10528 break;
10529
10530 case OO_Plus: // '+' is either unary or binary
10531 if (Args.size() == 1)
10532 OpBuilder.addUnaryPlusPointerOverloads();
10533 [[fallthrough]];
10534
10535 case OO_Minus: // '-' is either unary or binary
10536 if (Args.size() == 1) {
10537 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10538 } else {
10539 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10540 OpBuilder.addGenericBinaryArithmeticOverloads();
10541 OpBuilder.addMatrixBinaryArithmeticOverloads();
10542 }
10543 break;
10544
10545 case OO_Star: // '*' is either unary or binary
10546 if (Args.size() == 1)
10547 OpBuilder.addUnaryStarPointerOverloads();
10548 else {
10549 OpBuilder.addGenericBinaryArithmeticOverloads();
10550 OpBuilder.addMatrixBinaryArithmeticOverloads();
10551 }
10552 break;
10553
10554 case OO_Slash:
10555 OpBuilder.addGenericBinaryArithmeticOverloads();
10556 break;
10557
10558 case OO_PlusPlus:
10559 case OO_MinusMinus:
10560 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10561 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10562 break;
10563
10564 case OO_EqualEqual:
10565 case OO_ExclaimEqual:
10566 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10567 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10568 OpBuilder.addGenericBinaryArithmeticOverloads();
10569 break;
10570
10571 case OO_Less:
10572 case OO_Greater:
10573 case OO_LessEqual:
10574 case OO_GreaterEqual:
10575 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10576 OpBuilder.addGenericBinaryArithmeticOverloads();
10577 break;
10578
10579 case OO_Spaceship:
10580 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10581 OpBuilder.addThreeWayArithmeticOverloads();
10582 break;
10583
10584 case OO_Percent:
10585 case OO_Caret:
10586 case OO_Pipe:
10587 case OO_LessLess:
10588 case OO_GreaterGreater:
10589 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10590 break;
10591
10592 case OO_Amp: // '&' is either unary or binary
10593 if (Args.size() == 1)
10594 // C++ [over.match.oper]p3:
10595 // -- For the operator ',', the unary operator '&', or the
10596 // operator '->', the built-in candidates set is empty.
10597 break;
10598
10599 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10600 break;
10601
10602 case OO_Tilde:
10603 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10604 break;
10605
10606 case OO_Equal:
10607 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10608 [[fallthrough]];
10609
10610 case OO_PlusEqual:
10611 case OO_MinusEqual:
10612 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10613 [[fallthrough]];
10614
10615 case OO_StarEqual:
10616 case OO_SlashEqual:
10617 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10618 break;
10619
10620 case OO_PercentEqual:
10621 case OO_LessLessEqual:
10622 case OO_GreaterGreaterEqual:
10623 case OO_AmpEqual:
10624 case OO_CaretEqual:
10625 case OO_PipeEqual:
10626 OpBuilder.addAssignmentIntegralOverloads();
10627 break;
10628
10629 case OO_Exclaim:
10630 OpBuilder.addExclaimOverload();
10631 break;
10632
10633 case OO_AmpAmp:
10634 case OO_PipePipe:
10635 OpBuilder.addAmpAmpOrPipePipeOverload();
10636 break;
10637
10638 case OO_Subscript:
10639 if (Args.size() == 2)
10640 OpBuilder.addSubscriptOverloads();
10641 break;
10642
10643 case OO_ArrowStar:
10644 OpBuilder.addArrowStarOverloads();
10645 break;
10646
10647 case OO_Conditional:
10648 OpBuilder.addConditionalOperatorOverloads();
10649 OpBuilder.addGenericBinaryArithmeticOverloads();
10650 break;
10651 }
10652}
10653
10654void
10656 SourceLocation Loc,
10657 ArrayRef<Expr *> Args,
10658 TemplateArgumentListInfo *ExplicitTemplateArgs,
10659 OverloadCandidateSet& CandidateSet,
10660 bool PartialOverloading) {
10661 ADLResult Fns;
10662
10663 // FIXME: This approach for uniquing ADL results (and removing
10664 // redundant candidates from the set) relies on pointer-equality,
10665 // which means we need to key off the canonical decl. However,
10666 // always going back to the canonical decl might not get us the
10667 // right set of default arguments. What default arguments are
10668 // we supposed to consider on ADL candidates, anyway?
10669
10670 // FIXME: Pass in the explicit template arguments?
10671 ArgumentDependentLookup(Name, Loc, Args, Fns);
10672
10673 ArrayRef<Expr *> ReversedArgs;
10674
10675 // Erase all of the candidates we already knew about.
10676 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10677 CandEnd = CandidateSet.end();
10678 Cand != CandEnd; ++Cand)
10679 if (Cand->Function) {
10680 FunctionDecl *Fn = Cand->Function;
10681 Fns.erase(Fn);
10682 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10683 Fns.erase(FunTmpl);
10684 }
10685
10686 // For each of the ADL candidates we found, add it to the overload
10687 // set.
10688 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10690
10691 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10692 if (ExplicitTemplateArgs)
10693 continue;
10694
10696 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10697 PartialOverloading, /*AllowExplicit=*/true,
10698 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10699 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10701 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10702 /*SuppressUserConversions=*/false, PartialOverloading,
10703 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10704 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10705 }
10706 } else {
10707 auto *FTD = cast<FunctionTemplateDecl>(*I);
10709 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10710 /*SuppressUserConversions=*/false, PartialOverloading,
10711 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10712 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10713 *this, Args, FTD->getTemplatedDecl())) {
10714
10715 // As template candidates are not deduced immediately,
10716 // persist the array in the overload set.
10717 if (ReversedArgs.empty())
10718 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10719
10721 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10722 /*SuppressUserConversions=*/false, PartialOverloading,
10723 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10725 }
10726 }
10727 }
10728}
10729
10730namespace {
10731enum class Comparison { Equal, Better, Worse };
10732}
10733
10734/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10735/// overload resolution.
10736///
10737/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10738/// Cand1's first N enable_if attributes have precisely the same conditions as
10739/// Cand2's first N enable_if attributes (where N = the number of enable_if
10740/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10741///
10742/// Note that you can have a pair of candidates such that Cand1's enable_if
10743/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10744/// worse than Cand1's.
10745static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10746 const FunctionDecl *Cand2) {
10747 // Common case: One (or both) decls don't have enable_if attrs.
10748 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10749 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10750 if (!Cand1Attr || !Cand2Attr) {
10751 if (Cand1Attr == Cand2Attr)
10752 return Comparison::Equal;
10753 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10754 }
10755
10756 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10757 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10758
10759 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10760 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10761 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10762 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10763
10764 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10765 // has fewer enable_if attributes than Cand2, and vice versa.
10766 if (!Cand1A)
10767 return Comparison::Worse;
10768 if (!Cand2A)
10769 return Comparison::Better;
10770
10771 Cand1ID.clear();
10772 Cand2ID.clear();
10773
10774 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10775 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10776 if (Cand1ID != Cand2ID)
10777 return Comparison::Worse;
10778 }
10779
10780 return Comparison::Equal;
10781}
10782
10783static Comparison
10785 const OverloadCandidate &Cand2) {
10786 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10787 !Cand2.Function->isMultiVersion())
10788 return Comparison::Equal;
10789
10790 // If both are invalid, they are equal. If one of them is invalid, the other
10791 // is better.
10792 if (Cand1.Function->isInvalidDecl()) {
10793 if (Cand2.Function->isInvalidDecl())
10794 return Comparison::Equal;
10795 return Comparison::Worse;
10796 }
10797 if (Cand2.Function->isInvalidDecl())
10798 return Comparison::Better;
10799
10800 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10801 // cpu_dispatch, else arbitrarily based on the identifiers.
10802 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10803 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10804 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10805 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10806
10807 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10808 return Comparison::Equal;
10809
10810 if (Cand1CPUDisp && !Cand2CPUDisp)
10811 return Comparison::Better;
10812 if (Cand2CPUDisp && !Cand1CPUDisp)
10813 return Comparison::Worse;
10814
10815 if (Cand1CPUSpec && Cand2CPUSpec) {
10816 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10817 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10818 ? Comparison::Better
10819 : Comparison::Worse;
10820
10821 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10822 FirstDiff = std::mismatch(
10823 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10824 Cand2CPUSpec->cpus_begin(),
10825 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10826 return LHS->getName() == RHS->getName();
10827 });
10828
10829 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10830 "Two different cpu-specific versions should not have the same "
10831 "identifier list, otherwise they'd be the same decl!");
10832 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10833 ? Comparison::Better
10834 : Comparison::Worse;
10835 }
10836 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10837}
10838
10839/// Compute the type of the implicit object parameter for the given function,
10840/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10841/// null QualType if there is a 'matches anything' implicit object parameter.
10842static std::optional<QualType>
10845 return std::nullopt;
10846
10847 auto *M = cast<CXXMethodDecl>(F);
10848 // Static member functions' object parameters match all types.
10849 if (M->isStatic())
10850 return QualType();
10851 return M->getFunctionObjectParameterReferenceType();
10852}
10853
10854// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10855// represent the same entity.
10856static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10857 const FunctionDecl *F2) {
10858 if (declaresSameEntity(F1, F2))
10859 return true;
10860 auto PT1 = F1->getPrimaryTemplate();
10861 auto PT2 = F2->getPrimaryTemplate();
10862 if (PT1 && PT2) {
10863 if (declaresSameEntity(PT1, PT2) ||
10864 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10865 PT2->getInstantiatedFromMemberTemplate()))
10866 return true;
10867 }
10868 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10869 // different functions with same params). Consider removing this (as no test
10870 // fail w/o it).
10871 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10872 if (First) {
10873 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10874 return *T;
10875 }
10876 assert(I < F->getNumParams());
10877 return F->getParamDecl(I++)->getType();
10878 };
10879
10880 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10881 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10882
10883 if (F1NumParams != F2NumParams)
10884 return false;
10885
10886 unsigned I1 = 0, I2 = 0;
10887 for (unsigned I = 0; I != F1NumParams; ++I) {
10888 QualType T1 = NextParam(F1, I1, I == 0);
10889 QualType T2 = NextParam(F2, I2, I == 0);
10890 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10891 if (!Context.hasSameUnqualifiedType(T1, T2))
10892 return false;
10893 }
10894 return true;
10895}
10896
10897/// We're allowed to use constraints partial ordering only if the candidates
10898/// have the same parameter types:
10899/// [over.match.best.general]p2.6
10900/// F1 and F2 are non-template functions with the same
10901/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10903 FunctionDecl *Fn2,
10904 bool IsFn1Reversed,
10905 bool IsFn2Reversed) {
10906 assert(Fn1 && Fn2);
10907 if (Fn1->isVariadic() != Fn2->isVariadic())
10908 return false;
10909
10910 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10911 IsFn1Reversed ^ IsFn2Reversed))
10912 return false;
10913
10914 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10915 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10916 if (Mem1 && Mem2) {
10917 // if they are member functions, both are direct members of the same class,
10918 // and
10919 if (Mem1->getParent() != Mem2->getParent())
10920 return false;
10921 // if both are non-static member functions, they have the same types for
10922 // their object parameters
10923 if (Mem1->isInstance() && Mem2->isInstance() &&
10925 Mem1->getFunctionObjectParameterReferenceType(),
10926 Mem1->getFunctionObjectParameterReferenceType()))
10927 return false;
10928 }
10929 return true;
10930}
10931
10932static FunctionDecl *
10934 bool IsFn1Reversed, bool IsFn2Reversed) {
10935 if (!Fn1 || !Fn2)
10936 return nullptr;
10937
10938 // C++ [temp.constr.order]:
10939 // A non-template function F1 is more partial-ordering-constrained than a
10940 // non-template function F2 if:
10941 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10942 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10943
10944 if (Cand1IsSpecialization || Cand2IsSpecialization)
10945 return nullptr;
10946
10947 // - they have the same non-object-parameter-type-lists, and [...]
10948 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10949 IsFn2Reversed))
10950 return nullptr;
10951
10952 // - the declaration of F1 is more constrained than the declaration of F2.
10953 return S.getMoreConstrainedFunction(Fn1, Fn2);
10954}
10955
10956/// isBetterOverloadCandidate - Determines whether the first overload
10957/// candidate is a better candidate than the second (C++ 13.3.3p1).
10959 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10961 bool PartialOverloading) {
10962 // Define viable functions to be better candidates than non-viable
10963 // functions.
10964 if (!Cand2.Viable)
10965 return Cand1.Viable;
10966 else if (!Cand1.Viable)
10967 return false;
10968
10969 // [CUDA] A function with 'never' preference is marked not viable, therefore
10970 // is never shown up here. The worst preference shown up here is 'wrong side',
10971 // e.g. an H function called by a HD function in device compilation. This is
10972 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10973 // function which is called only by an H function. A deferred diagnostic will
10974 // be triggered if it is emitted. However a wrong-sided function is still
10975 // a viable candidate here.
10976 //
10977 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10978 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10979 // can be emitted, Cand1 is not better than Cand2. This rule should have
10980 // precedence over other rules.
10981 //
10982 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10983 // other rules should be used to determine which is better. This is because
10984 // host/device based overloading resolution is mostly for determining
10985 // viability of a function. If two functions are both viable, other factors
10986 // should take precedence in preference, e.g. the standard-defined preferences
10987 // like argument conversion ranks or enable_if partial-ordering. The
10988 // preference for pass-object-size parameters is probably most similar to a
10989 // type-based-overloading decision and so should take priority.
10990 //
10991 // If other rules cannot determine which is better, CUDA preference will be
10992 // used again to determine which is better.
10993 //
10994 // TODO: Currently IdentifyPreference does not return correct values
10995 // for functions called in global variable initializers due to missing
10996 // correct context about device/host. Therefore we can only enforce this
10997 // rule when there is a caller. We should enforce this rule for functions
10998 // in global variable initializers once proper context is added.
10999 //
11000 // TODO: We can only enable the hostness based overloading resolution when
11001 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11002 // overloading resolution diagnostics.
11003 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11004 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11005 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11006 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11007 bool IsCand1ImplicitHD =
11009 bool IsCand2ImplicitHD =
11011 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11012 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11013 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11014 // The implicit HD function may be a function in a system header which
11015 // is forced by pragma. In device compilation, if we prefer HD candidates
11016 // over wrong-sided candidates, overloading resolution may change, which
11017 // may result in non-deferrable diagnostics. As a workaround, we let
11018 // implicit HD candidates take equal preference as wrong-sided candidates.
11019 // This will preserve the overloading resolution.
11020 // TODO: We still need special handling of implicit HD functions since
11021 // they may incur other diagnostics to be deferred. We should make all
11022 // host/device related diagnostics deferrable and remove special handling
11023 // of implicit HD functions.
11024 auto EmitThreshold =
11025 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11026 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11029 auto Cand1Emittable = P1 > EmitThreshold;
11030 auto Cand2Emittable = P2 > EmitThreshold;
11031 if (Cand1Emittable && !Cand2Emittable)
11032 return true;
11033 if (!Cand1Emittable && Cand2Emittable)
11034 return false;
11035 }
11036 }
11037
11038 // C++ [over.match.best]p1: (Changed in C++23)
11039 //
11040 // -- if F is a static member function, ICS1(F) is defined such
11041 // that ICS1(F) is neither better nor worse than ICS1(G) for
11042 // any function G, and, symmetrically, ICS1(G) is neither
11043 // better nor worse than ICS1(F).
11044 unsigned StartArg = 0;
11045 if (!Cand1.TookAddressOfOverload &&
11047 StartArg = 1;
11048
11049 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11050 // We don't allow incompatible pointer conversions in C++.
11051 if (!S.getLangOpts().CPlusPlus)
11052 return ICS.isStandard() &&
11053 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11054
11055 // The only ill-formed conversion we allow in C++ is the string literal to
11056 // char* conversion, which is only considered ill-formed after C++11.
11057 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11059 };
11060
11061 // Define functions that don't require ill-formed conversions for a given
11062 // argument to be better candidates than functions that do.
11063 unsigned NumArgs = Cand1.Conversions.size();
11064 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11065 bool HasBetterConversion = false;
11066 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11067 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11068 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11069 if (Cand1Bad != Cand2Bad) {
11070 if (Cand1Bad)
11071 return false;
11072 HasBetterConversion = true;
11073 }
11074 }
11075
11076 if (HasBetterConversion)
11077 return true;
11078
11079 // C++ [over.match.best]p1:
11080 // A viable function F1 is defined to be a better function than another
11081 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11082 // conversion sequence than ICSi(F2), and then...
11083 bool HasWorseConversion = false;
11084 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11086 Cand1.Conversions[ArgIdx],
11087 Cand2.Conversions[ArgIdx])) {
11089 // Cand1 has a better conversion sequence.
11090 HasBetterConversion = true;
11091 break;
11092
11094 if (Cand1.Function && Cand2.Function &&
11095 Cand1.isReversed() != Cand2.isReversed() &&
11096 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11097 // Work around large-scale breakage caused by considering reversed
11098 // forms of operator== in C++20:
11099 //
11100 // When comparing a function against a reversed function, if we have a
11101 // better conversion for one argument and a worse conversion for the
11102 // other, the implicit conversion sequences are treated as being equally
11103 // good.
11104 //
11105 // This prevents a comparison function from being considered ambiguous
11106 // with a reversed form that is written in the same way.
11107 //
11108 // We diagnose this as an extension from CreateOverloadedBinOp.
11109 HasWorseConversion = true;
11110 break;
11111 }
11112
11113 // Cand1 can't be better than Cand2.
11114 return false;
11115
11117 // Do nothing.
11118 break;
11119 }
11120 }
11121
11122 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11123 // ICSj(F2), or, if not that,
11124 if (HasBetterConversion && !HasWorseConversion)
11125 return true;
11126
11127 // -- the context is an initialization by user-defined conversion
11128 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11129 // from the return type of F1 to the destination type (i.e.,
11130 // the type of the entity being initialized) is a better
11131 // conversion sequence than the standard conversion sequence
11132 // from the return type of F2 to the destination type.
11134 Cand1.Function && Cand2.Function &&
11137
11138 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11139 // First check whether we prefer one of the conversion functions over the
11140 // other. This only distinguishes the results in non-standard, extension
11141 // cases such as the conversion from a lambda closure type to a function
11142 // pointer or block.
11147 Cand1.FinalConversion,
11148 Cand2.FinalConversion);
11149
11152
11153 // FIXME: Compare kind of reference binding if conversion functions
11154 // convert to a reference type used in direct reference binding, per
11155 // C++14 [over.match.best]p1 section 2 bullet 3.
11156 }
11157
11158 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11159 // as combined with the resolution to CWG issue 243.
11160 //
11161 // When the context is initialization by constructor ([over.match.ctor] or
11162 // either phase of [over.match.list]), a constructor is preferred over
11163 // a conversion function.
11164 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11165 Cand1.Function && Cand2.Function &&
11168 return isa<CXXConstructorDecl>(Cand1.Function);
11169
11170 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11171 return Cand2.StrictPackMatch;
11172
11173 // -- F1 is a non-template function and F2 is a function template
11174 // specialization, or, if not that,
11175 bool Cand1IsSpecialization = Cand1.Function &&
11177 bool Cand2IsSpecialization = Cand2.Function &&
11179 if (Cand1IsSpecialization != Cand2IsSpecialization)
11180 return Cand2IsSpecialization;
11181
11182 // -- F1 and F2 are function template specializations, and the function
11183 // template for F1 is more specialized than the template for F2
11184 // according to the partial ordering rules described in 14.5.5.2, or,
11185 // if not that,
11186 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11187 const auto *Obj1Context =
11188 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11189 const auto *Obj2Context =
11190 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11191 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11193 Cand2.Function->getPrimaryTemplate(), Loc,
11195 : TPOC_Call,
11197 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11198 : QualType{},
11199 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11200 : QualType{},
11201 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11202 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11203 }
11204 }
11205
11206 // -— F1 and F2 are non-template functions and F1 is more
11207 // partial-ordering-constrained than F2 [...],
11209 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11210 Cand2.isReversed());
11211 F && F == Cand1.Function)
11212 return true;
11213
11214 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11215 // class B of D, and for all arguments the corresponding parameters of
11216 // F1 and F2 have the same type.
11217 // FIXME: Implement the "all parameters have the same type" check.
11218 bool Cand1IsInherited =
11219 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11220 bool Cand2IsInherited =
11221 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11222 if (Cand1IsInherited != Cand2IsInherited)
11223 return Cand2IsInherited;
11224 else if (Cand1IsInherited) {
11225 assert(Cand2IsInherited);
11226 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11227 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11228 if (Cand1Class->isDerivedFrom(Cand2Class))
11229 return true;
11230 if (Cand2Class->isDerivedFrom(Cand1Class))
11231 return false;
11232 // Inherited from sibling base classes: still ambiguous.
11233 }
11234
11235 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11236 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11237 // with reversed order of parameters and F1 is not
11238 //
11239 // We rank reversed + different operator as worse than just reversed, but
11240 // that comparison can never happen, because we only consider reversing for
11241 // the maximally-rewritten operator (== or <=>).
11242 if (Cand1.RewriteKind != Cand2.RewriteKind)
11243 return Cand1.RewriteKind < Cand2.RewriteKind;
11244
11245 // Check C++17 tie-breakers for deduction guides.
11246 {
11247 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11248 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11249 if (Guide1 && Guide2) {
11250 // -- F1 is generated from a deduction-guide and F2 is not
11251 if (Guide1->isImplicit() != Guide2->isImplicit())
11252 return Guide2->isImplicit();
11253
11254 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11255 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11256 return true;
11257 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11258 return false;
11259
11260 // --F1 is generated from a non-template constructor and F2 is generated
11261 // from a constructor template
11262 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11263 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11264 if (Constructor1 && Constructor2) {
11265 bool isC1Templated = Constructor1->getTemplatedKind() !=
11267 bool isC2Templated = Constructor2->getTemplatedKind() !=
11269 if (isC1Templated != isC2Templated)
11270 return isC2Templated;
11271 }
11272 }
11273 }
11274
11275 // Check for enable_if value-based overload resolution.
11276 if (Cand1.Function && Cand2.Function) {
11278 if (Cmp != Comparison::Equal)
11279 return Cmp == Comparison::Better;
11280 }
11281
11282 bool HasPS1 = Cand1.Function != nullptr &&
11284 bool HasPS2 = Cand2.Function != nullptr &&
11286 if (HasPS1 != HasPS2 && HasPS1)
11287 return true;
11288
11289 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11290 if (MV == Comparison::Better)
11291 return true;
11292 if (MV == Comparison::Worse)
11293 return false;
11294
11295 // If other rules cannot determine which is better, CUDA preference is used
11296 // to determine which is better.
11297 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11298 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11299 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11300 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11301 }
11302
11303 // General member function overloading is handled above, so this only handles
11304 // constructors with address spaces.
11305 // This only handles address spaces since C++ has no other
11306 // qualifier that can be used with constructors.
11307 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11308 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11309 if (CD1 && CD2) {
11310 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11311 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11312 if (AS1 != AS2) {
11314 return true;
11316 return false;
11317 }
11318 }
11319
11320 return false;
11321}
11322
11323/// Determine whether two declarations are "equivalent" for the purposes of
11324/// name lookup and overload resolution. This applies when the same internal/no
11325/// linkage entity is defined by two modules (probably by textually including
11326/// the same header). In such a case, we don't consider the declarations to
11327/// declare the same entity, but we also don't want lookups with both
11328/// declarations visible to be ambiguous in some cases (this happens when using
11329/// a modularized libstdc++).
11331 const NamedDecl *B) {
11332 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11333 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11334 if (!VA || !VB)
11335 return false;
11336
11337 // The declarations must be declaring the same name as an internal linkage
11338 // entity in different modules.
11339 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11340 VB->getDeclContext()->getRedeclContext()) ||
11341 getOwningModule(VA) == getOwningModule(VB) ||
11342 VA->isExternallyVisible() || VB->isExternallyVisible())
11343 return false;
11344
11345 // Check that the declarations appear to be equivalent.
11346 //
11347 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11348 // For constants and functions, we should check the initializer or body is
11349 // the same. For non-constant variables, we shouldn't allow it at all.
11350 if (Context.hasSameType(VA->getType(), VB->getType()))
11351 return true;
11352
11353 // Enum constants within unnamed enumerations will have different types, but
11354 // may still be similar enough to be interchangeable for our purposes.
11355 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11356 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11357 // Only handle anonymous enums. If the enumerations were named and
11358 // equivalent, they would have been merged to the same type.
11359 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11360 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11361 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11362 !Context.hasSameType(EnumA->getIntegerType(),
11363 EnumB->getIntegerType()))
11364 return false;
11365 // Allow this only if the value is the same for both enumerators.
11366 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11367 }
11368 }
11369
11370 // Nothing else is sufficiently similar.
11371 return false;
11372}
11373
11376 assert(D && "Unknown declaration");
11377 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11378
11379 Module *M = getOwningModule(D);
11380 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11381 << !M << (M ? M->getFullModuleName() : "");
11382
11383 for (auto *E : Equiv) {
11384 Module *M = getOwningModule(E);
11385 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11386 << !M << (M ? M->getFullModuleName() : "");
11387 }
11388}
11389
11392 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11394 static_cast<CNSInfo *>(DeductionFailure.Data)
11395 ->Satisfaction.ContainsErrors;
11396}
11397
11400 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11401 bool PartialOverloading, bool AllowExplicit,
11403 bool AggregateCandidateDeduction) {
11404
11405 auto *C =
11406 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11407
11410 /*AllowObjCConversionOnExplicit=*/false,
11411 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11412 PartialOverloading, AggregateCandidateDeduction},
11414 FoundDecl,
11415 Args,
11416 IsADLCandidate,
11417 PO};
11418
11419 HasDeferredTemplateConstructors |=
11420 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11421}
11422
11424 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11425 CXXRecordDecl *ActingContext, QualType ObjectType,
11426 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11427 bool SuppressUserConversions, bool PartialOverloading,
11429
11430 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11431
11432 auto *C =
11433 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11434
11437 /*AllowObjCConversionOnExplicit=*/false,
11438 /*AllowResultConversion=*/false,
11439 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11440 /*AggregateCandidateDeduction=*/false},
11441 MethodTmpl,
11442 FoundDecl,
11443 Args,
11444 ActingContext,
11445 ObjectClassification,
11446 ObjectType,
11447 PO};
11448}
11449
11452 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11453 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11454 bool AllowResultConversion) {
11455
11456 auto *C =
11457 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11458
11461 AllowObjCConversionOnExplicit, AllowResultConversion,
11462 /*AllowExplicit=*/false,
11463 /*SuppressUserConversions=*/false,
11464 /*PartialOverloading*/ false,
11465 /*AggregateCandidateDeduction=*/false},
11467 FoundDecl,
11468 ActingContext,
11469 From,
11470 ToType};
11471}
11472
11473static void
11476
11478 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11479 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11480 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11481}
11482
11483static void
11487 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11488 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11489 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11490 C.AggregateCandidateDeduction);
11491}
11492
11493static void
11497 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11498 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11499 C.AllowResultConversion);
11500}
11501
11503 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11504 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11505 while (Cand) {
11506 switch (Cand->Kind) {
11509 S, *this,
11510 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11511 break;
11514 S, *this,
11515 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11516 break;
11519 S, *this,
11520 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11521 break;
11522 }
11523 Cand = Cand->Next;
11524 }
11525 FirstDeferredCandidate = nullptr;
11526 DeferredCandidatesCount = 0;
11527}
11528
11530OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11531 Best->Best = true;
11532 if (Best->Function && Best->Function->isDeleted())
11533 return OR_Deleted;
11534 return OR_Success;
11535}
11536
11537void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11539 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11540 // are accepted by both clang and NVCC. However, during a particular
11541 // compilation mode only one call variant is viable. We need to
11542 // exclude non-viable overload candidates from consideration based
11543 // only on their host/device attributes. Specifically, if one
11544 // candidate call is WrongSide and the other is SameSide, we ignore
11545 // the WrongSide candidate.
11546 // We only need to remove wrong-sided candidates here if
11547 // -fgpu-exclude-wrong-side-overloads is off. When
11548 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11549 // uniformly in isBetterOverloadCandidate.
11550 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11551 return;
11552 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11553
11554 bool ContainsSameSideCandidate =
11555 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11556 // Check viable function only.
11557 return Cand->Viable && Cand->Function &&
11558 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11560 });
11561
11562 if (!ContainsSameSideCandidate)
11563 return;
11564
11565 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11566 // Check viable function only to avoid unnecessary data copying/moving.
11567 return Cand->Viable && Cand->Function &&
11568 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11570 };
11571 llvm::erase_if(Candidates, IsWrongSideCandidate);
11572}
11573
11574/// Computes the best viable function (C++ 13.3.3)
11575/// within an overload candidate set.
11576///
11577/// \param Loc The location of the function name (or operator symbol) for
11578/// which overload resolution occurs.
11579///
11580/// \param Best If overload resolution was successful or found a deleted
11581/// function, \p Best points to the candidate function found.
11582///
11583/// \returns The result of overload resolution.
11585 SourceLocation Loc,
11586 iterator &Best) {
11587
11589 DeferredCandidatesCount == 0) &&
11590 "Unexpected deferred template candidates");
11591
11592 bool TwoPhaseResolution =
11593 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11594
11595 if (TwoPhaseResolution) {
11596 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11597 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11598 if (!(HasDeferredTemplateConstructors &&
11599 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11600 return Res;
11601 }
11602 }
11603
11605 return BestViableFunctionImpl(S, Loc, Best);
11606}
11607
11608OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11610
11612 Candidates.reserve(this->Candidates.size());
11613 std::transform(this->Candidates.begin(), this->Candidates.end(),
11614 std::back_inserter(Candidates),
11615 [](OverloadCandidate &Cand) { return &Cand; });
11616
11617 if (S.getLangOpts().CUDA)
11618 CudaExcludeWrongSideCandidates(S, Candidates);
11619
11620 Best = end();
11621 for (auto *Cand : Candidates) {
11622 Cand->Best = false;
11623 if (Cand->Viable) {
11624 if (Best == end() ||
11625 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11626 Best = Cand;
11627 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11628 // This candidate has constraint that we were unable to evaluate because
11629 // it referenced an expression that contained an error. Rather than fall
11630 // back onto a potentially unintended candidate (made worse by
11631 // subsuming constraints), treat this as 'no viable candidate'.
11632 Best = end();
11633 return OR_No_Viable_Function;
11634 }
11635 }
11636
11637 // If we didn't find any viable functions, abort.
11638 if (Best == end())
11639 return OR_No_Viable_Function;
11640
11641 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11642 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11643 PendingBest.push_back(&*Best);
11644 Best->Best = true;
11645
11646 // Make sure that this function is better than every other viable
11647 // function. If not, we have an ambiguity.
11648 while (!PendingBest.empty()) {
11649 auto *Curr = PendingBest.pop_back_val();
11650 for (auto *Cand : Candidates) {
11651 if (Cand->Viable && !Cand->Best &&
11652 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11653 PendingBest.push_back(Cand);
11654 Cand->Best = true;
11655
11657 Curr->Function))
11658 EquivalentCands.push_back(Cand->Function);
11659 else
11660 Best = end();
11661 }
11662 }
11663 }
11664
11665 if (Best == end())
11666 return OR_Ambiguous;
11667
11668 OverloadingResult R = ResultForBestCandidate(Best);
11669
11670 if (!EquivalentCands.empty())
11672 EquivalentCands);
11673 return R;
11674}
11675
11676namespace {
11677
11678enum OverloadCandidateKind {
11679 oc_function,
11680 oc_method,
11681 oc_reversed_binary_operator,
11682 oc_constructor,
11683 oc_implicit_default_constructor,
11684 oc_implicit_copy_constructor,
11685 oc_implicit_move_constructor,
11686 oc_implicit_copy_assignment,
11687 oc_implicit_move_assignment,
11688 oc_implicit_equality_comparison,
11689 oc_inherited_constructor
11690};
11691
11692enum OverloadCandidateSelect {
11693 ocs_non_template,
11694 ocs_template,
11695 ocs_described_template,
11696};
11697
11698static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11699ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11700 const FunctionDecl *Fn,
11702 std::string &Description) {
11703
11704 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11705 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11706 isTemplate = true;
11707 Description = S.getTemplateArgumentBindingsText(
11708 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11709 }
11710
11711 OverloadCandidateSelect Select = [&]() {
11712 if (!Description.empty())
11713 return ocs_described_template;
11714 return isTemplate ? ocs_template : ocs_non_template;
11715 }();
11716
11717 OverloadCandidateKind Kind = [&]() {
11718 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11719 return oc_implicit_equality_comparison;
11720
11721 if (CRK & CRK_Reversed)
11722 return oc_reversed_binary_operator;
11723
11724 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11725 if (!Ctor->isImplicit()) {
11727 return oc_inherited_constructor;
11728 else
11729 return oc_constructor;
11730 }
11731
11732 if (Ctor->isDefaultConstructor())
11733 return oc_implicit_default_constructor;
11734
11735 if (Ctor->isMoveConstructor())
11736 return oc_implicit_move_constructor;
11737
11738 assert(Ctor->isCopyConstructor() &&
11739 "unexpected sort of implicit constructor");
11740 return oc_implicit_copy_constructor;
11741 }
11742
11743 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11744 // This actually gets spelled 'candidate function' for now, but
11745 // it doesn't hurt to split it out.
11746 if (!Meth->isImplicit())
11747 return oc_method;
11748
11749 if (Meth->isMoveAssignmentOperator())
11750 return oc_implicit_move_assignment;
11751
11752 if (Meth->isCopyAssignmentOperator())
11753 return oc_implicit_copy_assignment;
11754
11755 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11756 return oc_method;
11757 }
11758
11759 return oc_function;
11760 }();
11761
11762 return std::make_pair(Kind, Select);
11763}
11764
11765void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11766 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11767 // set.
11768 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11769 S.Diag(FoundDecl->getLocation(),
11770 diag::note_ovl_candidate_inherited_constructor)
11771 << Shadow->getNominatedBaseClass();
11772}
11773
11774} // end anonymous namespace
11775
11777 const FunctionDecl *FD) {
11778 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11779 bool AlwaysTrue;
11780 if (EnableIf->getCond()->isValueDependent() ||
11781 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11782 return false;
11783 if (!AlwaysTrue)
11784 return false;
11785 }
11786 return true;
11787}
11788
11789/// Returns true if we can take the address of the function.
11790///
11791/// \param Complain - If true, we'll emit a diagnostic
11792/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11793/// we in overload resolution?
11794/// \param Loc - The location of the statement we're complaining about. Ignored
11795/// if we're not complaining, or if we're in overload resolution.
11797 bool Complain,
11798 bool InOverloadResolution,
11799 SourceLocation Loc) {
11800 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11801 if (Complain) {
11802 if (InOverloadResolution)
11803 S.Diag(FD->getBeginLoc(),
11804 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11805 else
11806 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11807 }
11808 return false;
11809 }
11810
11811 if (FD->getTrailingRequiresClause()) {
11812 ConstraintSatisfaction Satisfaction;
11813 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11814 return false;
11815 if (!Satisfaction.IsSatisfied) {
11816 if (Complain) {
11817 if (InOverloadResolution) {
11818 SmallString<128> TemplateArgString;
11819 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11820 TemplateArgString += " ";
11821 TemplateArgString += S.getTemplateArgumentBindingsText(
11822 FunTmpl->getTemplateParameters(),
11824 }
11825
11826 S.Diag(FD->getBeginLoc(),
11827 diag::note_ovl_candidate_unsatisfied_constraints)
11828 << TemplateArgString;
11829 } else
11830 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11831 << FD;
11832 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11833 }
11834 return false;
11835 }
11836 }
11837
11838 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11839 return P->hasAttr<PassObjectSizeAttr>();
11840 });
11841 if (I == FD->param_end())
11842 return true;
11843
11844 if (Complain) {
11845 // Add one to ParamNo because it's user-facing
11846 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11847 if (InOverloadResolution)
11848 S.Diag(FD->getLocation(),
11849 diag::note_ovl_candidate_has_pass_object_size_params)
11850 << ParamNo;
11851 else
11852 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11853 << FD << ParamNo;
11854 }
11855 return false;
11856}
11857
11859 const FunctionDecl *FD) {
11860 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11861 /*InOverloadResolution=*/true,
11862 /*Loc=*/SourceLocation());
11863}
11864
11866 bool Complain,
11867 SourceLocation Loc) {
11868 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11869 /*InOverloadResolution=*/false,
11870 Loc);
11871}
11872
11873// Don't print candidates other than the one that matches the calling
11874// convention of the call operator, since that is guaranteed to exist.
11876 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11877
11878 if (!ConvD)
11879 return false;
11880 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11881 if (!RD->isLambda())
11882 return false;
11883
11884 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11885 CallingConv CallOpCC =
11886 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11887 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11888 CallingConv ConvToCC =
11889 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11890
11891 return ConvToCC != CallOpCC;
11892}
11893
11894// Notes the location of an overload candidate.
11896 OverloadCandidateRewriteKind RewriteKind,
11897 QualType DestType, bool TakingAddress) {
11898 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11899 return;
11900 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11901 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11902 return;
11903 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11904 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11905 return;
11907 return;
11908
11909 std::string FnDesc;
11910 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11911 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11912 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11913 << (unsigned)KSPair.first << (unsigned)KSPair.second
11914 << Fn << FnDesc;
11915
11916 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11917 Diag(Fn->getLocation(), PD);
11918 MaybeEmitInheritedConstructorNote(*this, Found);
11919}
11920
11921static void
11923 // Perhaps the ambiguity was caused by two atomic constraints that are
11924 // 'identical' but not equivalent:
11925 //
11926 // void foo() requires (sizeof(T) > 4) { } // #1
11927 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11928 //
11929 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11930 // #2 to subsume #1, but these constraint are not considered equivalent
11931 // according to the subsumption rules because they are not the same
11932 // source-level construct. This behavior is quite confusing and we should try
11933 // to help the user figure out what happened.
11934
11935 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11936 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11937 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11938 if (!I->Function)
11939 continue;
11941 if (auto *Template = I->Function->getPrimaryTemplate())
11942 Template->getAssociatedConstraints(AC);
11943 else
11944 I->Function->getAssociatedConstraints(AC);
11945 if (AC.empty())
11946 continue;
11947 if (FirstCand == nullptr) {
11948 FirstCand = I->Function;
11949 FirstAC = AC;
11950 } else if (SecondCand == nullptr) {
11951 SecondCand = I->Function;
11952 SecondAC = AC;
11953 } else {
11954 // We have more than one pair of constrained functions - this check is
11955 // expensive and we'd rather not try to diagnose it.
11956 return;
11957 }
11958 }
11959 if (!SecondCand)
11960 return;
11961 // The diagnostic can only happen if there are associated constraints on
11962 // both sides (there needs to be some identical atomic constraint).
11963 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11964 SecondCand, SecondAC))
11965 // Just show the user one diagnostic, they'll probably figure it out
11966 // from here.
11967 return;
11968}
11969
11970// Notes the location of all overload candidates designated through
11971// OverloadedExpr
11972void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11973 bool TakingAddress) {
11974 assert(OverloadedExpr->getType() == Context.OverloadTy);
11975
11976 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11977 OverloadExpr *OvlExpr = Ovl.Expression;
11978
11979 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11980 IEnd = OvlExpr->decls_end();
11981 I != IEnd; ++I) {
11982 if (FunctionTemplateDecl *FunTmpl =
11983 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11984 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11985 TakingAddress);
11986 } else if (FunctionDecl *Fun
11987 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11988 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11989 }
11990 }
11991}
11992
11993/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11994/// "lead" diagnostic; it will be given two arguments, the source and
11995/// target types of the conversion.
11997 Sema &S,
11998 SourceLocation CaretLoc,
11999 const PartialDiagnostic &PDiag) const {
12000 S.Diag(CaretLoc, PDiag)
12001 << Ambiguous.getFromType() << Ambiguous.getToType();
12002 unsigned CandsShown = 0;
12004 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12005 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12006 break;
12007 ++CandsShown;
12008 S.NoteOverloadCandidate(I->first, I->second);
12009 }
12010 S.Diags.overloadCandidatesShown(CandsShown);
12011 if (I != E)
12012 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12013}
12014
12016 unsigned I, bool TakingCandidateAddress) {
12017 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12018 assert(Conv.isBad());
12019 assert(Cand->Function && "for now, candidate must be a function");
12020 FunctionDecl *Fn = Cand->Function;
12021
12022 // There's a conversion slot for the object argument if this is a
12023 // non-constructor method. Note that 'I' corresponds the
12024 // conversion-slot index.
12025 bool isObjectArgument = false;
12026 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12028 if (I == 0)
12029 isObjectArgument = true;
12030 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12031 I--;
12032 }
12033
12034 std::string FnDesc;
12035 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12036 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12037 FnDesc);
12038
12039 Expr *FromExpr = Conv.Bad.FromExpr;
12040 QualType FromTy = Conv.Bad.getFromType();
12041 QualType ToTy = Conv.Bad.getToType();
12042 SourceRange ToParamRange;
12043
12044 // FIXME: In presence of parameter packs we can't determine parameter range
12045 // reliably, as we don't have access to instantiation.
12046 bool HasParamPack =
12047 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12048 return Parm->isParameterPack();
12049 });
12050 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12051 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12052
12053 if (FromTy == S.Context.OverloadTy) {
12054 assert(FromExpr && "overload set argument came from implicit argument?");
12055 Expr *E = FromExpr->IgnoreParens();
12056 if (isa<UnaryOperator>(E))
12057 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12058 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12059
12060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12061 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12062 << ToParamRange << ToTy << Name << I + 1;
12063 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12064 return;
12065 }
12066
12067 // Do some hand-waving analysis to see if the non-viability is due
12068 // to a qualifier mismatch.
12069 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12070 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12071 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12072 CToTy = RT->getPointeeType();
12073 else {
12074 // TODO: detect and diagnose the full richness of const mismatches.
12075 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12076 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12077 CFromTy = FromPT->getPointeeType();
12078 CToTy = ToPT->getPointeeType();
12079 }
12080 }
12081
12082 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12083 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12084 Qualifiers FromQs = CFromTy.getQualifiers();
12085 Qualifiers ToQs = CToTy.getQualifiers();
12086
12087 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12088 if (isObjectArgument)
12089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12090 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12091 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12092 else
12093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12094 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12095 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12096 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12097 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12098 return;
12099 }
12100
12101 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12103 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12104 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12105 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12106 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12107 return;
12108 }
12109
12110 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12112 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12113 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12114 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12115 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12116 return;
12117 }
12118
12119 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12121 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12122 << FromTy << !!FromQs.getPointerAuth()
12123 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12124 << ToQs.getPointerAuth().getAsString() << I + 1
12125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12126 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12127 return;
12128 }
12129
12130 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12131 assert(CVR && "expected qualifiers mismatch");
12132
12133 if (isObjectArgument) {
12134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12135 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12136 << FromTy << (CVR - 1);
12137 } else {
12138 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12139 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12140 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12141 }
12142 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12143 return;
12144 }
12145
12148 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12149 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12150 << (unsigned)isObjectArgument << I + 1
12152 << ToParamRange;
12153 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12154 return;
12155 }
12156
12157 // Special diagnostic for failure to convert an initializer list, since
12158 // telling the user that it has type void is not useful.
12159 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12160 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12161 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12162 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12165 ? 2
12166 : 0);
12167 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12168 return;
12169 }
12170
12171 // Diagnose references or pointers to incomplete types differently,
12172 // since it's far from impossible that the incompleteness triggered
12173 // the failure.
12174 QualType TempFromTy = FromTy.getNonReferenceType();
12175 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12176 TempFromTy = PTy->getPointeeType();
12177 if (TempFromTy->isIncompleteType()) {
12178 // Emit the generic diagnostic and, optionally, add the hints to it.
12179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12180 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12181 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12182 << (unsigned)(Cand->Fix.Kind);
12183
12184 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12185 return;
12186 }
12187
12188 // Diagnose base -> derived pointer conversions.
12189 unsigned BaseToDerivedConversion = 0;
12190 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12191 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12192 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12193 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12194 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12195 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12196 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12197 FromPtrTy->getPointeeType()))
12198 BaseToDerivedConversion = 1;
12199 }
12200 } else if (const ObjCObjectPointerType *FromPtrTy
12201 = FromTy->getAs<ObjCObjectPointerType>()) {
12202 if (const ObjCObjectPointerType *ToPtrTy
12203 = ToTy->getAs<ObjCObjectPointerType>())
12204 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12205 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12206 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12207 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12208 FromIface->isSuperClassOf(ToIface))
12209 BaseToDerivedConversion = 2;
12210 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12211 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12212 S.getASTContext()) &&
12213 !FromTy->isIncompleteType() &&
12214 !ToRefTy->getPointeeType()->isIncompleteType() &&
12215 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12216 BaseToDerivedConversion = 3;
12217 }
12218 }
12219
12220 if (BaseToDerivedConversion) {
12221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12222 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12223 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12224 << I + 1;
12225 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12226 return;
12227 }
12228
12229 if (isa<ObjCObjectPointerType>(CFromTy) &&
12230 isa<PointerType>(CToTy)) {
12231 Qualifiers FromQs = CFromTy.getQualifiers();
12232 Qualifiers ToQs = CToTy.getQualifiers();
12233 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12234 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12235 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12236 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12237 << I + 1;
12238 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12239 return;
12240 }
12241 }
12242
12243 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12244 return;
12245
12246 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12247 // although this is almost always an error and we advise against it.
12248 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12249 ToTy == S.Context.getLogicalOperationType()) {
12250 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12251 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12252 << Conv.Bad.FromExpr << ToTy;
12253 return;
12254 }
12255
12256 // Emit the generic diagnostic and, optionally, add the hints to it.
12257 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12258 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12259 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12260 << (unsigned)(Cand->Fix.Kind);
12261
12262 // Check that location of Fn is not in system header.
12263 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12264 // If we can fix the conversion, suggest the FixIts.
12265 for (const FixItHint &HI : Cand->Fix.Hints)
12266 FDiag << HI;
12267 }
12268
12269 S.Diag(Fn->getLocation(), FDiag);
12270
12271 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12272}
12273
12274/// Additional arity mismatch diagnosis specific to a function overload
12275/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12276/// over a candidate in any candidate set.
12278 unsigned NumArgs, bool IsAddressOf = false) {
12279 assert(Cand->Function && "Candidate is required to be a function.");
12280 FunctionDecl *Fn = Cand->Function;
12281 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12282 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12283
12284 // With invalid overloaded operators, it's possible that we think we
12285 // have an arity mismatch when in fact it looks like we have the
12286 // right number of arguments, because only overloaded operators have
12287 // the weird behavior of overloading member and non-member functions.
12288 // Just don't report anything.
12289 if (Fn->isInvalidDecl() &&
12290 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12291 return true;
12292
12293 if (NumArgs < MinParams) {
12294 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12296 Cand->DeductionFailure.getResult() ==
12298 } else {
12299 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12301 Cand->DeductionFailure.getResult() ==
12303 }
12304
12305 return false;
12306}
12307
12308/// General arity mismatch diagnosis over a candidate in a candidate set.
12310 unsigned NumFormalArgs,
12311 bool IsAddressOf = false) {
12312 assert(isa<FunctionDecl>(D) &&
12313 "The templated declaration should at least be a function"
12314 " when diagnosing bad template argument deduction due to too many"
12315 " or too few arguments");
12316
12318
12319 // TODO: treat calls to a missing default constructor as a special case
12320 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12321 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12322 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12323
12324 // at least / at most / exactly
12325 bool HasExplicitObjectParam =
12326 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12327
12328 unsigned ParamCount =
12329 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12330 unsigned mode, modeCount;
12331
12332 if (NumFormalArgs < MinParams) {
12333 if (MinParams != ParamCount || FnTy->isVariadic() ||
12334 FnTy->isTemplateVariadic())
12335 mode = 0; // "at least"
12336 else
12337 mode = 2; // "exactly"
12338 modeCount = MinParams;
12339 } else {
12340 if (MinParams != ParamCount)
12341 mode = 1; // "at most"
12342 else
12343 mode = 2; // "exactly"
12344 modeCount = ParamCount;
12345 }
12346
12347 std::string Description;
12348 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12349 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12350
12351 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12352 if (modeCount == 1 && !IsAddressOf &&
12353 FirstNonObjectParamIdx < Fn->getNumParams() &&
12354 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12355 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12356 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12357 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12358 << NumFormalArgs << HasExplicitObjectParam
12359 << Fn->getParametersSourceRange();
12360 else
12361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12362 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12363 << Description << mode << modeCount << NumFormalArgs
12364 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12365
12366 MaybeEmitInheritedConstructorNote(S, Found);
12367}
12368
12369/// Arity mismatch diagnosis specific to a function overload candidate.
12371 unsigned NumFormalArgs) {
12372 assert(Cand->Function && "Candidate must be a function");
12373 FunctionDecl *Fn = Cand->Function;
12374 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12375 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12376 Cand->TookAddressOfOverload);
12377}
12378
12380 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12381 return TD;
12382 llvm_unreachable("Unsupported: Getting the described template declaration"
12383 " for bad deduction diagnosis");
12384}
12385
12386/// Diagnose a failed template-argument deduction.
12387static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12388 DeductionFailureInfo &DeductionFailure,
12389 unsigned NumArgs,
12390 bool TakingCandidateAddress) {
12391 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12392 NamedDecl *ParamD;
12393 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12394 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12395 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12396 switch (DeductionFailure.getResult()) {
12398 llvm_unreachable(
12399 "TemplateDeductionResult::Success while diagnosing bad deduction");
12401 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12402 "while diagnosing bad deduction");
12405 return;
12406
12408 assert(ParamD && "no parameter found for incomplete deduction result");
12409 S.Diag(Templated->getLocation(),
12410 diag::note_ovl_candidate_incomplete_deduction)
12411 << ParamD->getDeclName();
12412 MaybeEmitInheritedConstructorNote(S, Found);
12413 return;
12414 }
12415
12417 assert(ParamD && "no parameter found for incomplete deduction result");
12418 S.Diag(Templated->getLocation(),
12419 diag::note_ovl_candidate_incomplete_deduction_pack)
12420 << ParamD->getDeclName()
12421 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12422 << *DeductionFailure.getFirstArg();
12423 MaybeEmitInheritedConstructorNote(S, Found);
12424 return;
12425 }
12426
12428 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12430
12431 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12432
12433 // Param will have been canonicalized, but it should just be a
12434 // qualified version of ParamD, so move the qualifiers to that.
12436 Qs.strip(Param);
12437 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12438 assert(S.Context.hasSameType(Param, NonCanonParam));
12439
12440 // Arg has also been canonicalized, but there's nothing we can do
12441 // about that. It also doesn't matter as much, because it won't
12442 // have any template parameters in it (because deduction isn't
12443 // done on dependent types).
12444 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12445
12446 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12447 << ParamD->getDeclName() << Arg << NonCanonParam;
12448 MaybeEmitInheritedConstructorNote(S, Found);
12449 return;
12450 }
12451
12453 assert(ParamD && "no parameter found for inconsistent deduction result");
12454 int which = 0;
12455 if (isa<TemplateTypeParmDecl>(ParamD))
12456 which = 0;
12457 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12458 // Deduction might have failed because we deduced arguments of two
12459 // different types for a non-type template parameter.
12460 // FIXME: Use a different TDK value for this.
12461 QualType T1 =
12462 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12463 QualType T2 =
12464 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12465 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12466 S.Diag(Templated->getLocation(),
12467 diag::note_ovl_candidate_inconsistent_deduction_types)
12468 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12469 << *DeductionFailure.getSecondArg() << T2;
12470 MaybeEmitInheritedConstructorNote(S, Found);
12471 return;
12472 }
12473
12474 which = 1;
12475 } else {
12476 which = 2;
12477 }
12478
12479 // Tweak the diagnostic if the problem is that we deduced packs of
12480 // different arities. We'll print the actual packs anyway in case that
12481 // includes additional useful information.
12482 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12483 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12484 DeductionFailure.getFirstArg()->pack_size() !=
12485 DeductionFailure.getSecondArg()->pack_size()) {
12486 which = 3;
12487 }
12488
12489 S.Diag(Templated->getLocation(),
12490 diag::note_ovl_candidate_inconsistent_deduction)
12491 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12492 << *DeductionFailure.getSecondArg();
12493 MaybeEmitInheritedConstructorNote(S, Found);
12494 return;
12495 }
12496
12498 assert(ParamD && "no parameter found for invalid explicit arguments");
12499
12500 auto Diag = S.Diag(Templated->getLocation(),
12501 diag::note_ovl_candidate_explicit_arg_mismatch);
12502 if (ParamD->getDeclName())
12503 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12504 else
12505 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12506 << (getDepthAndIndex(ParamD).second + 1);
12507 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12508 SmallString<128> DiagContent;
12509 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12510 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12511 } else {
12512 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12513 }
12514
12515 MaybeEmitInheritedConstructorNote(S, Found);
12516 return;
12517 }
12519 // Format the template argument list into the argument string.
12520 SmallString<128> TemplateArgString;
12521 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12522 TemplateArgString = " ";
12523 TemplateArgString += S.getTemplateArgumentBindingsText(
12524 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12525 if (TemplateArgString.size() == 1)
12526 TemplateArgString.clear();
12527 S.Diag(Templated->getLocation(),
12528 diag::note_ovl_candidate_unsatisfied_constraints)
12529 << TemplateArgString;
12530
12532 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12533 return;
12534 }
12537 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12538 return;
12539
12541 S.Diag(Templated->getLocation(),
12542 diag::note_ovl_candidate_instantiation_depth);
12543 MaybeEmitInheritedConstructorNote(S, Found);
12544 return;
12545
12547 // Format the template argument list into the argument string.
12548 SmallString<128> TemplateArgString;
12549 if (TemplateArgumentList *Args =
12550 DeductionFailure.getTemplateArgumentList()) {
12551 TemplateArgString = " ";
12552 TemplateArgString += S.getTemplateArgumentBindingsText(
12553 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12554 if (TemplateArgString.size() == 1)
12555 TemplateArgString.clear();
12556 }
12557
12558 // If this candidate was disabled by enable_if, say so.
12559 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12560 if (PDiag && PDiag->second.getDiagID() ==
12561 diag::err_typename_nested_not_found_enable_if) {
12562 // FIXME: Use the source range of the condition, and the fully-qualified
12563 // name of the enable_if template. These are both present in PDiag.
12564 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12565 << "'enable_if'" << TemplateArgString;
12566 return;
12567 }
12568
12569 // We found a specific requirement that disabled the enable_if.
12570 if (PDiag && PDiag->second.getDiagID() ==
12571 diag::err_typename_nested_not_found_requirement) {
12572 S.Diag(Templated->getLocation(),
12573 diag::note_ovl_candidate_disabled_by_requirement)
12574 << PDiag->second.getStringArg(0) << TemplateArgString;
12575 return;
12576 }
12577
12578 // Format the SFINAE diagnostic into the argument string.
12579 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12580 // formatted message in another diagnostic.
12581 SmallString<128> SFINAEArgString;
12582 SourceRange R;
12583 if (PDiag) {
12584 SFINAEArgString = ": ";
12585 R = SourceRange(PDiag->first, PDiag->first);
12586 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12587 }
12588
12589 S.Diag(Templated->getLocation(),
12590 diag::note_ovl_candidate_substitution_failure)
12591 << TemplateArgString << SFINAEArgString << R;
12592 MaybeEmitInheritedConstructorNote(S, Found);
12593 return;
12594 }
12595
12598 // Format the template argument list into the argument string.
12599 SmallString<128> TemplateArgString;
12600 if (TemplateArgumentList *Args =
12601 DeductionFailure.getTemplateArgumentList()) {
12602 TemplateArgString = " ";
12603 TemplateArgString += S.getTemplateArgumentBindingsText(
12604 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12605 if (TemplateArgString.size() == 1)
12606 TemplateArgString.clear();
12607 }
12608
12609 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12610 << (*DeductionFailure.getCallArgIndex() + 1)
12611 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12612 << TemplateArgString
12613 << (DeductionFailure.getResult() ==
12615 break;
12616 }
12617
12619 // FIXME: Provide a source location to indicate what we couldn't match.
12620 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12621 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12622 if (FirstTA.getKind() == TemplateArgument::Template &&
12623 SecondTA.getKind() == TemplateArgument::Template) {
12624 TemplateName FirstTN = FirstTA.getAsTemplate();
12625 TemplateName SecondTN = SecondTA.getAsTemplate();
12626 if (FirstTN.getKind() == TemplateName::Template &&
12627 SecondTN.getKind() == TemplateName::Template) {
12628 if (FirstTN.getAsTemplateDecl()->getName() ==
12629 SecondTN.getAsTemplateDecl()->getName()) {
12630 // FIXME: This fixes a bad diagnostic where both templates are named
12631 // the same. This particular case is a bit difficult since:
12632 // 1) It is passed as a string to the diagnostic printer.
12633 // 2) The diagnostic printer only attempts to find a better
12634 // name for types, not decls.
12635 // Ideally, this should folded into the diagnostic printer.
12636 S.Diag(Templated->getLocation(),
12637 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12638 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12639 return;
12640 }
12641 }
12642 }
12643
12644 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12646 return;
12647
12648 // FIXME: For generic lambda parameters, check if the function is a lambda
12649 // call operator, and if so, emit a prettier and more informative
12650 // diagnostic that mentions 'auto' and lambda in addition to
12651 // (or instead of?) the canonical template type parameters.
12652 S.Diag(Templated->getLocation(),
12653 diag::note_ovl_candidate_non_deduced_mismatch)
12654 << FirstTA << SecondTA;
12655 return;
12656 }
12657 // TODO: diagnose these individually, then kill off
12658 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12660 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12661 MaybeEmitInheritedConstructorNote(S, Found);
12662 return;
12664 S.Diag(Templated->getLocation(),
12665 diag::note_cuda_ovl_candidate_target_mismatch);
12666 return;
12667 }
12668}
12669
12670/// Diagnose a failed template-argument deduction, for function calls.
12672 unsigned NumArgs,
12673 bool TakingCandidateAddress) {
12674 assert(Cand->Function && "Candidate must be a function");
12675 FunctionDecl *Fn = Cand->Function;
12679 if (CheckArityMismatch(S, Cand, NumArgs))
12680 return;
12681 }
12682 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12683 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12684}
12685
12686/// CUDA: diagnose an invalid call across targets.
12688 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12689 assert(Cand->Function && "Candidate must be a Function.");
12690 FunctionDecl *Callee = Cand->Function;
12691
12692 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12693 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12694
12695 std::string FnDesc;
12696 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12697 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12698 Cand->getRewriteKind(), FnDesc);
12699
12700 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12701 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12702 << FnDesc /* Ignored */
12703 << CalleeTarget << CallerTarget;
12704
12705 // This could be an implicit constructor for which we could not infer the
12706 // target due to a collsion. Diagnose that case.
12707 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12708 if (Meth != nullptr && Meth->isImplicit()) {
12709 CXXRecordDecl *ParentClass = Meth->getParent();
12711
12712 switch (FnKindPair.first) {
12713 default:
12714 return;
12715 case oc_implicit_default_constructor:
12717 break;
12718 case oc_implicit_copy_constructor:
12720 break;
12721 case oc_implicit_move_constructor:
12723 break;
12724 case oc_implicit_copy_assignment:
12726 break;
12727 case oc_implicit_move_assignment:
12729 break;
12730 };
12731
12732 bool ConstRHS = false;
12733 if (Meth->getNumParams()) {
12734 if (const ReferenceType *RT =
12735 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12736 ConstRHS = RT->getPointeeType().isConstQualified();
12737 }
12738 }
12739
12740 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12741 /* ConstRHS */ ConstRHS,
12742 /* Diagnose */ true);
12743 }
12744}
12745
12747 assert(Cand->Function && "Candidate must be a function");
12748 FunctionDecl *Callee = Cand->Function;
12749 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12750
12751 S.Diag(Callee->getLocation(),
12752 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12753 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12754}
12755
12757 assert(Cand->Function && "Candidate must be a function");
12758 FunctionDecl *Fn = Cand->Function;
12760 assert(ES.isExplicit() && "not an explicit candidate");
12761
12762 unsigned Kind;
12763 switch (Fn->getDeclKind()) {
12764 case Decl::Kind::CXXConstructor:
12765 Kind = 0;
12766 break;
12767 case Decl::Kind::CXXConversion:
12768 Kind = 1;
12769 break;
12770 case Decl::Kind::CXXDeductionGuide:
12771 Kind = Fn->isImplicit() ? 0 : 2;
12772 break;
12773 default:
12774 llvm_unreachable("invalid Decl");
12775 }
12776
12777 // Note the location of the first (in-class) declaration; a redeclaration
12778 // (particularly an out-of-class definition) will typically lack the
12779 // 'explicit' specifier.
12780 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12781 FunctionDecl *First = Fn->getFirstDecl();
12782 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12783 First = Pattern->getFirstDecl();
12784
12785 S.Diag(First->getLocation(),
12786 diag::note_ovl_candidate_explicit)
12787 << Kind << (ES.getExpr() ? 1 : 0)
12788 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12789}
12790
12792 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12793 if (!DG)
12794 return;
12795 TemplateDecl *OriginTemplate =
12797 // We want to always print synthesized deduction guides for type aliases.
12798 // They would retain the explicit bit of the corresponding constructor.
12799 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12800 return;
12801 std::string FunctionProto;
12802 llvm::raw_string_ostream OS(FunctionProto);
12803 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12804 if (!Template) {
12805 // This also could be an instantiation. Find out the primary template.
12806 FunctionDecl *Pattern =
12807 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12808 if (!Pattern) {
12809 // The implicit deduction guide is built on an explicit non-template
12810 // deduction guide. Currently, this might be the case only for type
12811 // aliases.
12812 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12813 // gets merged.
12814 assert(OriginTemplate->isTypeAlias() &&
12815 "Non-template implicit deduction guides are only possible for "
12816 "type aliases");
12817 DG->print(OS);
12818 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12819 << FunctionProto;
12820 return;
12821 }
12823 assert(Template && "Cannot find the associated function template of "
12824 "CXXDeductionGuideDecl?");
12825 }
12826 Template->print(OS);
12827 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12828 << FunctionProto;
12829}
12830
12831/// Generates a 'note' diagnostic for an overload candidate. We've
12832/// already generated a primary error at the call site.
12833///
12834/// It really does need to be a single diagnostic with its caret
12835/// pointed at the candidate declaration. Yes, this creates some
12836/// major challenges of technical writing. Yes, this makes pointing
12837/// out problems with specific arguments quite awkward. It's still
12838/// better than generating twenty screens of text for every failed
12839/// overload.
12840///
12841/// It would be great to be able to express per-candidate problems
12842/// more richly for those diagnostic clients that cared, but we'd
12843/// still have to be just as careful with the default diagnostics.
12844/// \param CtorDestAS Addr space of object being constructed (for ctor
12845/// candidates only).
12847 unsigned NumArgs,
12848 bool TakingCandidateAddress,
12849 LangAS CtorDestAS = LangAS::Default) {
12850 assert(Cand->Function && "Candidate must be a function");
12851 FunctionDecl *Fn = Cand->Function;
12853 return;
12854
12855 // There is no physical candidate declaration to point to for OpenCL builtins.
12856 // Except for failed conversions, the notes are identical for each candidate,
12857 // so do not generate such notes.
12858 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12860 return;
12861
12862 // Skip implicit member functions when trying to resolve
12863 // the address of a an overload set for a function pointer.
12864 if (Cand->TookAddressOfOverload &&
12865 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12866 return;
12867
12868 // Note deleted candidates, but only if they're viable.
12869 if (Cand->Viable) {
12870 if (Fn->isDeleted()) {
12871 std::string FnDesc;
12872 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12873 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12874 Cand->getRewriteKind(), FnDesc);
12875
12876 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12877 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12878 << (Fn->isDeleted()
12879 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12880 : 0);
12881 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12882 return;
12883 }
12884
12885 // We don't really have anything else to say about viable candidates.
12886 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12887 return;
12888 }
12889
12890 // If this is a synthesized deduction guide we're deducing against, add a note
12891 // for it. These deduction guides are not explicitly spelled in the source
12892 // code, so simply printing a deduction failure note mentioning synthesized
12893 // template parameters or pointing to the header of the surrounding RecordDecl
12894 // would be confusing.
12895 //
12896 // We prefer adding such notes at the end of the deduction failure because
12897 // duplicate code snippets appearing in the diagnostic would likely become
12898 // noisy.
12899 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12900
12901 switch (Cand->FailureKind) {
12904 return DiagnoseArityMismatch(S, Cand, NumArgs);
12905
12907 return DiagnoseBadDeduction(S, Cand, NumArgs,
12908 TakingCandidateAddress);
12909
12911 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12912 << (Fn->getPrimaryTemplate() ? 1 : 0);
12913 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12914 return;
12915 }
12916
12918 Qualifiers QualsForPrinting;
12919 QualsForPrinting.setAddressSpace(CtorDestAS);
12920 S.Diag(Fn->getLocation(),
12921 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12922 << QualsForPrinting;
12923 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12924 return;
12925 }
12926
12930 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12931
12933 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12934 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12935 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12936 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12937
12938 // FIXME: this currently happens when we're called from SemaInit
12939 // when user-conversion overload fails. Figure out how to handle
12940 // those conditions and diagnose them well.
12941 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12942 }
12943
12945 return DiagnoseBadTarget(S, Cand);
12946
12947 case ovl_fail_enable_if:
12948 return DiagnoseFailedEnableIfAttr(S, Cand);
12949
12950 case ovl_fail_explicit:
12951 return DiagnoseFailedExplicitSpec(S, Cand);
12952
12954 // It's generally not interesting to note copy/move constructors here.
12955 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12956 return;
12957 S.Diag(Fn->getLocation(),
12958 diag::note_ovl_candidate_inherited_constructor_slice)
12959 << (Fn->getPrimaryTemplate() ? 1 : 0)
12960 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12961 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12962 return;
12963
12965 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12966 (void)Available;
12967 assert(!Available);
12968 break;
12969 }
12971 // Do nothing, these should simply be ignored.
12972 break;
12973
12975 std::string FnDesc;
12976 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12977 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12978 Cand->getRewriteKind(), FnDesc);
12979
12980 S.Diag(Fn->getLocation(),
12981 diag::note_ovl_candidate_constraints_not_satisfied)
12982 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12983 << FnDesc /* Ignored */;
12984 ConstraintSatisfaction Satisfaction;
12985 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12986 /*ForOverloadResolution=*/true))
12987 break;
12988 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12989 }
12990 }
12991}
12992
12995 return;
12996
12997 // Desugar the type of the surrogate down to a function type,
12998 // retaining as many typedefs as possible while still showing
12999 // the function type (and, therefore, its parameter types).
13000 QualType FnType = Cand->Surrogate->getConversionType();
13001 bool isLValueReference = false;
13002 bool isRValueReference = false;
13003 bool isPointer = false;
13004 if (const LValueReferenceType *FnTypeRef =
13005 FnType->getAs<LValueReferenceType>()) {
13006 FnType = FnTypeRef->getPointeeType();
13007 isLValueReference = true;
13008 } else if (const RValueReferenceType *FnTypeRef =
13009 FnType->getAs<RValueReferenceType>()) {
13010 FnType = FnTypeRef->getPointeeType();
13011 isRValueReference = true;
13012 }
13013 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13014 FnType = FnTypePtr->getPointeeType();
13015 isPointer = true;
13016 }
13017 // Desugar down to a function type.
13018 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13019 // Reconstruct the pointer/reference as appropriate.
13020 if (isPointer) FnType = S.Context.getPointerType(FnType);
13021 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13022 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13023
13024 if (!Cand->Viable &&
13026 S.Diag(Cand->Surrogate->getLocation(),
13027 diag::note_ovl_surrogate_constraints_not_satisfied)
13028 << Cand->Surrogate;
13029 ConstraintSatisfaction Satisfaction;
13030 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13031 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13032 } else {
13033 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13034 << FnType;
13035 }
13036}
13037
13038static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13039 SourceLocation OpLoc,
13040 OverloadCandidate *Cand) {
13041 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13042 std::string TypeStr("operator");
13043 TypeStr += Opc;
13044 TypeStr += "(";
13045 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13046 if (Cand->Conversions.size() == 1) {
13047 TypeStr += ")";
13048 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13049 } else {
13050 TypeStr += ", ";
13051 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13052 TypeStr += ")";
13053 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13054 }
13055}
13056
13058 OverloadCandidate *Cand) {
13059 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13060 if (ICS.isBad()) break; // all meaningless after first invalid
13061 if (!ICS.isAmbiguous()) continue;
13062
13064 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13065 }
13066}
13067
13069 if (Cand->Function)
13070 return Cand->Function->getLocation();
13071 if (Cand->IsSurrogate)
13072 return Cand->Surrogate->getLocation();
13073 return SourceLocation();
13074}
13075
13076static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13077 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13081 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13082
13086 return 1;
13087
13090 return 2;
13091
13099 return 3;
13100
13102 return 4;
13103
13105 return 5;
13106
13109 return 6;
13110 }
13111 llvm_unreachable("Unhandled deduction result");
13112}
13113
13114namespace {
13115
13116struct CompareOverloadCandidatesForDisplay {
13117 Sema &S;
13118 SourceLocation Loc;
13119 size_t NumArgs;
13121
13122 CompareOverloadCandidatesForDisplay(
13123 Sema &S, SourceLocation Loc, size_t NArgs,
13125 : S(S), NumArgs(NArgs), CSK(CSK) {}
13126
13127 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13128 // If there are too many or too few arguments, that's the high-order bit we
13129 // want to sort by, even if the immediate failure kind was something else.
13130 if (C->FailureKind == ovl_fail_too_many_arguments ||
13131 C->FailureKind == ovl_fail_too_few_arguments)
13132 return static_cast<OverloadFailureKind>(C->FailureKind);
13133
13134 if (C->Function) {
13135 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13137 if (NumArgs < C->Function->getMinRequiredArguments())
13139 }
13140
13141 return static_cast<OverloadFailureKind>(C->FailureKind);
13142 }
13143
13144 bool operator()(const OverloadCandidate *L,
13145 const OverloadCandidate *R) {
13146 // Fast-path this check.
13147 if (L == R) return false;
13148
13149 // Order first by viability.
13150 if (L->Viable) {
13151 if (!R->Viable) return true;
13152
13153 if (int Ord = CompareConversions(*L, *R))
13154 return Ord < 0;
13155 // Use other tie breakers.
13156 } else if (R->Viable)
13157 return false;
13158
13159 assert(L->Viable == R->Viable);
13160
13161 // Criteria by which we can sort non-viable candidates:
13162 if (!L->Viable) {
13163 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13164 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13165
13166 // 1. Arity mismatches come after other candidates.
13167 if (LFailureKind == ovl_fail_too_many_arguments ||
13168 LFailureKind == ovl_fail_too_few_arguments) {
13169 if (RFailureKind == ovl_fail_too_many_arguments ||
13170 RFailureKind == ovl_fail_too_few_arguments) {
13171 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13172 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13173 if (LDist == RDist) {
13174 if (LFailureKind == RFailureKind)
13175 // Sort non-surrogates before surrogates.
13176 return !L->IsSurrogate && R->IsSurrogate;
13177 // Sort candidates requiring fewer parameters than there were
13178 // arguments given after candidates requiring more parameters
13179 // than there were arguments given.
13180 return LFailureKind == ovl_fail_too_many_arguments;
13181 }
13182 return LDist < RDist;
13183 }
13184 return false;
13185 }
13186 if (RFailureKind == ovl_fail_too_many_arguments ||
13187 RFailureKind == ovl_fail_too_few_arguments)
13188 return true;
13189
13190 // 2. Bad conversions come first and are ordered by the number
13191 // of bad conversions and quality of good conversions.
13192 if (LFailureKind == ovl_fail_bad_conversion) {
13193 if (RFailureKind != ovl_fail_bad_conversion)
13194 return true;
13195
13196 // The conversion that can be fixed with a smaller number of changes,
13197 // comes first.
13198 unsigned numLFixes = L->Fix.NumConversionsFixed;
13199 unsigned numRFixes = R->Fix.NumConversionsFixed;
13200 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13201 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13202 if (numLFixes != numRFixes) {
13203 return numLFixes < numRFixes;
13204 }
13205
13206 // If there's any ordering between the defined conversions...
13207 if (int Ord = CompareConversions(*L, *R))
13208 return Ord < 0;
13209 } else if (RFailureKind == ovl_fail_bad_conversion)
13210 return false;
13211
13212 if (LFailureKind == ovl_fail_bad_deduction) {
13213 if (RFailureKind != ovl_fail_bad_deduction)
13214 return true;
13215
13216 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13217 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13218 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13219 if (LRank != RRank)
13220 return LRank < RRank;
13221 }
13222 } else if (RFailureKind == ovl_fail_bad_deduction)
13223 return false;
13224
13225 // TODO: others?
13226 }
13227
13228 // Sort everything else by location.
13229 SourceLocation LLoc = GetLocationForCandidate(L);
13230 SourceLocation RLoc = GetLocationForCandidate(R);
13231
13232 // Put candidates without locations (e.g. builtins) at the end.
13233 if (LLoc.isValid() && RLoc.isValid())
13234 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13235 if (LLoc.isValid() && !RLoc.isValid())
13236 return true;
13237 if (RLoc.isValid() && !LLoc.isValid())
13238 return false;
13239 assert(!LLoc.isValid() && !RLoc.isValid());
13240 // For builtins and other functions without locations, fallback to the order
13241 // in which they were added into the candidate set.
13242 return L < R;
13243 }
13244
13245private:
13246 struct ConversionSignals {
13247 unsigned KindRank = 0;
13249
13250 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13251 ConversionSignals Sig;
13252 Sig.KindRank = Seq.getKindRank();
13253 if (Seq.isStandard())
13254 Sig.Rank = Seq.Standard.getRank();
13255 else if (Seq.isUserDefined())
13256 Sig.Rank = Seq.UserDefined.After.getRank();
13257 // We intend StaticObjectArgumentConversion to compare the same as
13258 // StandardConversion with ICR_ExactMatch rank.
13259 return Sig;
13260 }
13261
13262 static ConversionSignals ForObjectArgument() {
13263 // We intend StaticObjectArgumentConversion to compare the same as
13264 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13265 return {};
13266 }
13267 };
13268
13269 // Returns -1 if conversions in L are considered better.
13270 // 0 if they are considered indistinguishable.
13271 // 1 if conversions in R are better.
13272 int CompareConversions(const OverloadCandidate &L,
13273 const OverloadCandidate &R) {
13274 // We cannot use `isBetterOverloadCandidate` because it is defined
13275 // according to the C++ standard and provides a partial order, but we need
13276 // a total order as this function is used in sort.
13277 assert(L.Conversions.size() == R.Conversions.size());
13278 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13279 auto LS = L.IgnoreObjectArgument && I == 0
13280 ? ConversionSignals::ForObjectArgument()
13281 : ConversionSignals::ForSequence(L.Conversions[I]);
13282 auto RS = R.IgnoreObjectArgument
13283 ? ConversionSignals::ForObjectArgument()
13284 : ConversionSignals::ForSequence(R.Conversions[I]);
13285 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13286 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13287 ? -1
13288 : 1;
13289 }
13290 // FIXME: find a way to compare templates for being more or less
13291 // specialized that provides a strict weak ordering.
13292 return 0;
13293 }
13294};
13295}
13296
13297/// CompleteNonViableCandidate - Normally, overload resolution only
13298/// computes up to the first bad conversion. Produces the FixIt set if
13299/// possible.
13300static void
13302 ArrayRef<Expr *> Args,
13304 assert(!Cand->Viable);
13305
13306 // Don't do anything on failures other than bad conversion.
13308 return;
13309
13310 // We only want the FixIts if all the arguments can be corrected.
13311 bool Unfixable = false;
13312 // Use a implicit copy initialization to check conversion fixes.
13314
13315 // Attempt to fix the bad conversion.
13316 unsigned ConvCount = Cand->Conversions.size();
13317 for (unsigned ConvIdx =
13318 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13319 : 0);
13320 /**/; ++ConvIdx) {
13321 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13322 if (Cand->Conversions[ConvIdx].isInitialized() &&
13323 Cand->Conversions[ConvIdx].isBad()) {
13324 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13325 break;
13326 }
13327 }
13328
13329 // FIXME: this should probably be preserved from the overload
13330 // operation somehow.
13331 bool SuppressUserConversions = false;
13332
13333 unsigned ConvIdx = 0;
13334 unsigned ArgIdx = 0;
13335 ArrayRef<QualType> ParamTypes;
13336 bool Reversed = Cand->isReversed();
13337
13338 if (Cand->IsSurrogate) {
13339 QualType ConvType
13341 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13342 ConvType = ConvPtrType->getPointeeType();
13343 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13344 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13345 ConvIdx = 1;
13346 } else if (Cand->Function) {
13347 ParamTypes =
13348 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13349 if (isa<CXXMethodDecl>(Cand->Function) &&
13352 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13353 ConvIdx = 1;
13355 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13357 OO_Subscript)
13358 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13359 ArgIdx = 1;
13360 }
13361 } else {
13362 // Builtin operator.
13363 assert(ConvCount <= 3);
13364 ParamTypes = Cand->BuiltinParamTypes;
13365 }
13366
13367 // Fill in the rest of the conversions.
13368 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13369 ConvIdx != ConvCount && ArgIdx < Args.size();
13370 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13371 if (Cand->Conversions[ConvIdx].isInitialized()) {
13372 // We've already checked this conversion.
13373 } else if (ParamIdx < ParamTypes.size()) {
13374 if (ParamTypes[ParamIdx]->isDependentType())
13375 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13376 Args[ArgIdx]->getType());
13377 else {
13378 Cand->Conversions[ConvIdx] =
13379 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13380 SuppressUserConversions,
13381 /*InOverloadResolution=*/true,
13382 /*AllowObjCWritebackConversion=*/
13383 S.getLangOpts().ObjCAutoRefCount);
13384 // Store the FixIt in the candidate if it exists.
13385 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13386 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13387 }
13388 } else
13389 Cand->Conversions[ConvIdx].setEllipsis();
13390 }
13391}
13392
13395 SourceLocation OpLoc,
13396 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13397
13399
13400 // Sort the candidates by viability and position. Sorting directly would
13401 // be prohibitive, so we make a set of pointers and sort those.
13403 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13404 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13405 Cand != LastCand; ++Cand) {
13406 if (!Filter(*Cand))
13407 continue;
13408 switch (OCD) {
13409 case OCD_AllCandidates:
13410 if (!Cand->Viable) {
13411 if (!Cand->Function && !Cand->IsSurrogate) {
13412 // This a non-viable builtin candidate. We do not, in general,
13413 // want to list every possible builtin candidate.
13414 continue;
13415 }
13416 CompleteNonViableCandidate(S, Cand, Args, Kind);
13417 }
13418 break;
13419
13421 if (!Cand->Viable)
13422 continue;
13423 break;
13424
13426 if (!Cand->Best)
13427 continue;
13428 break;
13429 }
13430
13431 Cands.push_back(Cand);
13432 }
13433
13434 llvm::stable_sort(
13435 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13436
13437 return Cands;
13438}
13439
13441 SourceLocation OpLoc) {
13442 bool DeferHint = false;
13443 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13444 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13445 // host device candidates.
13446 auto WrongSidedCands =
13447 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13448 return (Cand.Viable == false &&
13450 (Cand.Function &&
13451 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13452 Cand.Function->template hasAttr<CUDADeviceAttr>());
13453 });
13454 DeferHint = !WrongSidedCands.empty();
13455 }
13456 return DeferHint;
13457}
13458
13459/// When overload resolution fails, prints diagnostic messages containing the
13460/// candidates in the candidate set.
13463 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13464 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13465
13466 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13467
13468 {
13469 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13470 S.Diag(PD.first, PD.second);
13471 }
13472
13473 // In WebAssembly we don't want to emit further diagnostics if a table is
13474 // passed as an argument to a function.
13475 bool NoteCands = true;
13476 for (const Expr *Arg : Args) {
13477 if (Arg->getType()->isWebAssemblyTableType())
13478 NoteCands = false;
13479 }
13480
13481 if (NoteCands)
13482 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13483
13484 if (OCD == OCD_AmbiguousCandidates)
13486 {Candidates.begin(), Candidates.end()});
13487}
13488
13491 StringRef Opc, SourceLocation OpLoc) {
13492 bool ReportedAmbiguousConversions = false;
13493
13494 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13495 unsigned CandsShown = 0;
13496 auto I = Cands.begin(), E = Cands.end();
13497 for (; I != E; ++I) {
13498 OverloadCandidate *Cand = *I;
13499
13500 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13501 ShowOverloads == Ovl_Best) {
13502 break;
13503 }
13504 ++CandsShown;
13505
13506 if (Cand->Function)
13507 NoteFunctionCandidate(S, Cand, Args.size(),
13508 Kind == CSK_AddressOfOverloadSet, DestAS);
13509 else if (Cand->IsSurrogate)
13510 NoteSurrogateCandidate(S, Cand);
13511 else {
13512 assert(Cand->Viable &&
13513 "Non-viable built-in candidates are not added to Cands.");
13514 // Generally we only see ambiguities including viable builtin
13515 // operators if overload resolution got screwed up by an
13516 // ambiguous user-defined conversion.
13517 //
13518 // FIXME: It's quite possible for different conversions to see
13519 // different ambiguities, though.
13520 if (!ReportedAmbiguousConversions) {
13521 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13522 ReportedAmbiguousConversions = true;
13523 }
13524
13525 // If this is a viable builtin, print it.
13526 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13527 }
13528 }
13529
13530 // Inform S.Diags that we've shown an overload set with N elements. This may
13531 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13532 S.Diags.overloadCandidatesShown(CandsShown);
13533
13534 if (I != E) {
13535 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13536 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13537 }
13538}
13539
13541 const Sema &S) const {
13542 if (S.getLangOpts().CUDA) {
13543 auto *Caller = S.getCurFunctionDecl(true);
13544 // Overloading based on __host__ and __device__ attributes takes
13545 // higher priority, HD functions may favor template candidates even when a
13546 // non-template candidate would be a perfect match.
13547 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13548 Caller->hasAttr<CUDADeviceAttr>())
13549 return false;
13550 }
13551
13552 return
13553 // For user defined conversion we need to check against different
13554 // combination of CV qualifiers and look at any explicit specifier, so
13555 // always deduce template candidates.
13557 // When doing code completion, we want to see all the
13558 // viable candidates.
13559 && Kind != CSK_CodeCompletion;
13560}
13561
13562static SourceLocation
13564 return Cand->Specialization ? Cand->Specialization->getLocation()
13565 : SourceLocation();
13566}
13567
13568namespace {
13569struct CompareTemplateSpecCandidatesForDisplay {
13570 Sema &S;
13571 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13572
13573 bool operator()(const TemplateSpecCandidate *L,
13574 const TemplateSpecCandidate *R) {
13575 // Fast-path this check.
13576 if (L == R)
13577 return false;
13578
13579 // Assuming that both candidates are not matches...
13580
13581 // Sort by the ranking of deduction failures.
13582 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13584 RankDeductionFailure(R->DeductionFailure);
13585
13586 // Sort everything else by location.
13587 SourceLocation LLoc = GetLocationForCandidate(L);
13588 SourceLocation RLoc = GetLocationForCandidate(R);
13589
13590 // Put candidates without locations (e.g. builtins) at the end.
13591 if (LLoc.isInvalid())
13592 return false;
13593 if (RLoc.isInvalid())
13594 return true;
13595
13596 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13597 }
13598};
13599}
13600
13601/// Diagnose a template argument deduction failure.
13602/// We are treating these failures as overload failures due to bad
13603/// deductions.
13605 bool ForTakingAddress) {
13607 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13608}
13609
13610void TemplateSpecCandidateSet::destroyCandidates() {
13611 for (iterator i = begin(), e = end(); i != e; ++i) {
13612 i->DeductionFailure.Destroy();
13613 }
13614}
13615
13617 destroyCandidates();
13618 Candidates.clear();
13619}
13620
13621/// NoteCandidates - When no template specialization match is found, prints
13622/// diagnostic messages containing the non-matching specializations that form
13623/// the candidate set.
13624/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13625/// OCD == OCD_AllCandidates and Cand->Viable == false.
13627 // Sort the candidates by position (assuming no candidate is a match).
13628 // Sorting directly would be prohibitive, so we make a set of pointers
13629 // and sort those.
13631 Cands.reserve(size());
13632 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13633 if (Cand->Specialization)
13634 Cands.push_back(Cand);
13635 // Otherwise, this is a non-matching builtin candidate. We do not,
13636 // in general, want to list every possible builtin candidate.
13637 }
13638
13639 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13640
13641 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13642 // for generalization purposes (?).
13643 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13644
13646 unsigned CandsShown = 0;
13647 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13648 TemplateSpecCandidate *Cand = *I;
13649
13650 // Set an arbitrary limit on the number of candidates we'll spam
13651 // the user with. FIXME: This limit should depend on details of the
13652 // candidate list.
13653 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13654 break;
13655 ++CandsShown;
13656
13657 assert(Cand->Specialization &&
13658 "Non-matching built-in candidates are not added to Cands.");
13659 Cand->NoteDeductionFailure(S, ForTakingAddress);
13660 }
13661
13662 if (I != E)
13663 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13664}
13665
13666// [PossiblyAFunctionType] --> [Return]
13667// NonFunctionType --> NonFunctionType
13668// R (A) --> R(A)
13669// R (*)(A) --> R (A)
13670// R (&)(A) --> R (A)
13671// R (S::*)(A) --> R (A)
13673 QualType Ret = PossiblyAFunctionType;
13674 if (const PointerType *ToTypePtr =
13675 PossiblyAFunctionType->getAs<PointerType>())
13676 Ret = ToTypePtr->getPointeeType();
13677 else if (const ReferenceType *ToTypeRef =
13678 PossiblyAFunctionType->getAs<ReferenceType>())
13679 Ret = ToTypeRef->getPointeeType();
13680 else if (const MemberPointerType *MemTypePtr =
13681 PossiblyAFunctionType->getAs<MemberPointerType>())
13682 Ret = MemTypePtr->getPointeeType();
13683 Ret =
13684 Context.getCanonicalType(Ret).getUnqualifiedType();
13685 return Ret;
13686}
13687
13689 bool Complain = true) {
13690 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13691 S.DeduceReturnType(FD, Loc, Complain))
13692 return true;
13693
13694 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13695 if (S.getLangOpts().CPlusPlus17 &&
13696 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13697 !S.ResolveExceptionSpec(Loc, FPT))
13698 return true;
13699
13700 return false;
13701}
13702
13703namespace {
13704// A helper class to help with address of function resolution
13705// - allows us to avoid passing around all those ugly parameters
13706class AddressOfFunctionResolver {
13707 Sema& S;
13708 Expr* SourceExpr;
13709 const QualType& TargetType;
13710 QualType TargetFunctionType; // Extracted function type from target type
13711
13712 bool Complain;
13713 //DeclAccessPair& ResultFunctionAccessPair;
13714 ASTContext& Context;
13715
13716 bool TargetTypeIsNonStaticMemberFunction;
13717 bool FoundNonTemplateFunction;
13718 bool StaticMemberFunctionFromBoundPointer;
13719 bool HasComplained;
13720
13721 OverloadExpr::FindResult OvlExprInfo;
13722 OverloadExpr *OvlExpr;
13723 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13724 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13725 TemplateSpecCandidateSet FailedCandidates;
13726
13727public:
13728 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13729 const QualType &TargetType, bool Complain)
13730 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13731 Complain(Complain), Context(S.getASTContext()),
13732 TargetTypeIsNonStaticMemberFunction(
13733 !!TargetType->getAs<MemberPointerType>()),
13734 FoundNonTemplateFunction(false),
13735 StaticMemberFunctionFromBoundPointer(false),
13736 HasComplained(false),
13737 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13738 OvlExpr(OvlExprInfo.Expression),
13739 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13740 ExtractUnqualifiedFunctionTypeFromTargetType();
13741
13742 if (TargetFunctionType->isFunctionType()) {
13743 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13744 if (!UME->isImplicitAccess() &&
13746 StaticMemberFunctionFromBoundPointer = true;
13747 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13748 DeclAccessPair dap;
13749 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13750 OvlExpr, false, &dap)) {
13751 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13752 if (!Method->isStatic()) {
13753 // If the target type is a non-function type and the function found
13754 // is a non-static member function, pretend as if that was the
13755 // target, it's the only possible type to end up with.
13756 TargetTypeIsNonStaticMemberFunction = true;
13757
13758 // And skip adding the function if its not in the proper form.
13759 // We'll diagnose this due to an empty set of functions.
13760 if (!OvlExprInfo.HasFormOfMemberPointer)
13761 return;
13762 }
13763
13764 Matches.push_back(std::make_pair(dap, Fn));
13765 }
13766 return;
13767 }
13768
13769 if (OvlExpr->hasExplicitTemplateArgs())
13770 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13771
13772 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13773 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13774 EliminateSuboptimalCudaMatches();
13775
13776 // C++ [over.over]p4:
13777 // If more than one function is selected, [...]
13778 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13779 if (FoundNonTemplateFunction) {
13780 EliminateAllTemplateMatches();
13781 EliminateLessPartialOrderingConstrainedMatches();
13782 } else
13783 EliminateAllExceptMostSpecializedTemplate();
13784 }
13785 }
13786 }
13787
13788 bool hasComplained() const { return HasComplained; }
13789
13790private:
13791 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13792 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13793 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13794 }
13795
13796 /// \return true if A is considered a better overload candidate for the
13797 /// desired type than B.
13798 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13799 // If A doesn't have exactly the correct type, we don't want to classify it
13800 // as "better" than anything else. This way, the user is required to
13801 // disambiguate for us if there are multiple candidates and no exact match.
13802 return candidateHasExactlyCorrectType(A) &&
13803 (!candidateHasExactlyCorrectType(B) ||
13804 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13805 }
13806
13807 /// \return true if we were able to eliminate all but one overload candidate,
13808 /// false otherwise.
13809 bool eliminiateSuboptimalOverloadCandidates() {
13810 // Same algorithm as overload resolution -- one pass to pick the "best",
13811 // another pass to be sure that nothing is better than the best.
13812 auto Best = Matches.begin();
13813 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13814 if (isBetterCandidate(I->second, Best->second))
13815 Best = I;
13816
13817 const FunctionDecl *BestFn = Best->second;
13818 auto IsBestOrInferiorToBest = [this, BestFn](
13819 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13820 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13821 };
13822
13823 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13824 // option, so we can potentially give the user a better error
13825 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13826 return false;
13827 Matches[0] = *Best;
13828 Matches.resize(1);
13829 return true;
13830 }
13831
13832 bool isTargetTypeAFunction() const {
13833 return TargetFunctionType->isFunctionType();
13834 }
13835
13836 // [ToType] [Return]
13837
13838 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13839 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13840 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13841 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13842 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13843 }
13844
13845 // return true if any matching specializations were found
13846 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13847 const DeclAccessPair& CurAccessFunPair) {
13848 if (CXXMethodDecl *Method
13849 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13850 // Skip non-static function templates when converting to pointer, and
13851 // static when converting to member pointer.
13852 bool CanConvertToFunctionPointer =
13853 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13854 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13855 return false;
13856 }
13857 else if (TargetTypeIsNonStaticMemberFunction)
13858 return false;
13859
13860 // C++ [over.over]p2:
13861 // If the name is a function template, template argument deduction is
13862 // done (14.8.2.2), and if the argument deduction succeeds, the
13863 // resulting template argument list is used to generate a single
13864 // function template specialization, which is added to the set of
13865 // overloaded functions considered.
13866 FunctionDecl *Specialization = nullptr;
13867 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13869 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13870 Specialization, Info, /*IsAddressOfFunction*/ true);
13871 Result != TemplateDeductionResult::Success) {
13872 // Make a note of the failed deduction for diagnostics.
13873 FailedCandidates.addCandidate()
13874 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13875 MakeDeductionFailureInfo(Context, Result, Info));
13876 return false;
13877 }
13878
13879 // Template argument deduction ensures that we have an exact match or
13880 // compatible pointer-to-function arguments that would be adjusted by ICS.
13881 // This function template specicalization works.
13883 Context.getCanonicalType(Specialization->getType()),
13884 Context.getCanonicalType(TargetFunctionType)));
13885
13887 return false;
13888
13889 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13890 return true;
13891 }
13892
13893 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13894 const DeclAccessPair& CurAccessFunPair) {
13895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13896 // Skip non-static functions when converting to pointer, and static
13897 // when converting to member pointer.
13898 bool CanConvertToFunctionPointer =
13899 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13900 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13901 return false;
13902 }
13903 else if (TargetTypeIsNonStaticMemberFunction)
13904 return false;
13905
13906 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13907 if (S.getLangOpts().CUDA) {
13908 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13909 if (!(Caller && Caller->isImplicit()) &&
13910 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13911 return false;
13912 }
13913 if (FunDecl->isMultiVersion()) {
13914 const auto *TA = FunDecl->getAttr<TargetAttr>();
13915 if (TA && !TA->isDefaultVersion())
13916 return false;
13917 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13918 if (TVA && !TVA->isDefaultVersion())
13919 return false;
13920 }
13921
13922 // If any candidate has a placeholder return type, trigger its deduction
13923 // now.
13924 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13925 Complain)) {
13926 HasComplained |= Complain;
13927 return false;
13928 }
13929
13930 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13931 return false;
13932
13933 // If we're in C, we need to support types that aren't exactly identical.
13934 if (!S.getLangOpts().CPlusPlus ||
13935 candidateHasExactlyCorrectType(FunDecl)) {
13936 Matches.push_back(std::make_pair(
13937 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13938 FoundNonTemplateFunction = true;
13939 return true;
13940 }
13941 }
13942
13943 return false;
13944 }
13945
13946 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13947 bool Ret = false;
13948
13949 // If the overload expression doesn't have the form of a pointer to
13950 // member, don't try to convert it to a pointer-to-member type.
13951 if (IsInvalidFormOfPointerToMemberFunction())
13952 return false;
13953
13954 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13955 E = OvlExpr->decls_end();
13956 I != E; ++I) {
13957 // Look through any using declarations to find the underlying function.
13958 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13959
13960 // C++ [over.over]p3:
13961 // Non-member functions and static member functions match
13962 // targets of type "pointer-to-function" or "reference-to-function."
13963 // Nonstatic member functions match targets of
13964 // type "pointer-to-member-function."
13965 // Note that according to DR 247, the containing class does not matter.
13966 if (FunctionTemplateDecl *FunctionTemplate
13967 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13968 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13969 Ret = true;
13970 }
13971 // If we have explicit template arguments supplied, skip non-templates.
13972 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13973 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13974 Ret = true;
13975 }
13976 assert(Ret || Matches.empty());
13977 return Ret;
13978 }
13979
13980 void EliminateAllExceptMostSpecializedTemplate() {
13981 // [...] and any given function template specialization F1 is
13982 // eliminated if the set contains a second function template
13983 // specialization whose function template is more specialized
13984 // than the function template of F1 according to the partial
13985 // ordering rules of 14.5.5.2.
13986
13987 // The algorithm specified above is quadratic. We instead use a
13988 // two-pass algorithm (similar to the one used to identify the
13989 // best viable function in an overload set) that identifies the
13990 // best function template (if it exists).
13991
13992 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13993 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13994 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13995
13996 // TODO: It looks like FailedCandidates does not serve much purpose
13997 // here, since the no_viable diagnostic has index 0.
13998 UnresolvedSetIterator Result = S.getMostSpecialized(
13999 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14000 SourceExpr->getBeginLoc(), S.PDiag(),
14001 S.PDiag(diag::err_addr_ovl_ambiguous)
14002 << Matches[0].second->getDeclName(),
14003 S.PDiag(diag::note_ovl_candidate)
14004 << (unsigned)oc_function << (unsigned)ocs_described_template,
14005 Complain, TargetFunctionType);
14006
14007 if (Result != MatchesCopy.end()) {
14008 // Make it the first and only element
14009 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14010 Matches[0].second = cast<FunctionDecl>(*Result);
14011 Matches.resize(1);
14012 } else
14013 HasComplained |= Complain;
14014 }
14015
14016 void EliminateAllTemplateMatches() {
14017 // [...] any function template specializations in the set are
14018 // eliminated if the set also contains a non-template function, [...]
14019 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14020 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14021 ++I;
14022 else {
14023 Matches[I] = Matches[--N];
14024 Matches.resize(N);
14025 }
14026 }
14027 }
14028
14029 void EliminateLessPartialOrderingConstrainedMatches() {
14030 // C++ [over.over]p5:
14031 // [...] Any given non-template function F0 is eliminated if the set
14032 // contains a second non-template function that is more
14033 // partial-ordering-constrained than F0. [...]
14034 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14035 "Call EliminateAllTemplateMatches() first");
14036 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14037 Results.push_back(Matches[0]);
14038 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14039 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14040 FunctionDecl *F = getMorePartialOrderingConstrained(
14041 S, Matches[I].second, Results[0].second,
14042 /*IsFn1Reversed=*/false,
14043 /*IsFn2Reversed=*/false);
14044 if (!F) {
14045 Results.push_back(Matches[I]);
14046 continue;
14047 }
14048 if (F == Matches[I].second) {
14049 Results.clear();
14050 Results.push_back(Matches[I]);
14051 }
14052 }
14053 std::swap(Matches, Results);
14054 }
14055
14056 void EliminateSuboptimalCudaMatches() {
14057 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14058 Matches);
14059 }
14060
14061public:
14062 void ComplainNoMatchesFound() const {
14063 assert(Matches.empty());
14064 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14065 << OvlExpr->getName() << TargetFunctionType
14066 << OvlExpr->getSourceRange();
14067 if (FailedCandidates.empty())
14068 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14069 /*TakingAddress=*/true);
14070 else {
14071 // We have some deduction failure messages. Use them to diagnose
14072 // the function templates, and diagnose the non-template candidates
14073 // normally.
14074 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14075 IEnd = OvlExpr->decls_end();
14076 I != IEnd; ++I)
14077 if (FunctionDecl *Fun =
14078 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14080 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14081 /*TakingAddress=*/true);
14082 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14083 }
14084 }
14085
14086 bool IsInvalidFormOfPointerToMemberFunction() const {
14087 return TargetTypeIsNonStaticMemberFunction &&
14088 !OvlExprInfo.HasFormOfMemberPointer;
14089 }
14090
14091 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14092 // TODO: Should we condition this on whether any functions might
14093 // have matched, or is it more appropriate to do that in callers?
14094 // TODO: a fixit wouldn't hurt.
14095 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14096 << TargetType << OvlExpr->getSourceRange();
14097 }
14098
14099 bool IsStaticMemberFunctionFromBoundPointer() const {
14100 return StaticMemberFunctionFromBoundPointer;
14101 }
14102
14103 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14104 S.Diag(OvlExpr->getBeginLoc(),
14105 diag::err_invalid_form_pointer_member_function)
14106 << OvlExpr->getSourceRange();
14107 }
14108
14109 void ComplainOfInvalidConversion() const {
14110 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14111 << OvlExpr->getName() << TargetType;
14112 }
14113
14114 void ComplainMultipleMatchesFound() const {
14115 assert(Matches.size() > 1);
14116 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14117 << OvlExpr->getName() << OvlExpr->getSourceRange();
14118 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14119 /*TakingAddress=*/true);
14120 }
14121
14122 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14123
14124 int getNumMatches() const { return Matches.size(); }
14125
14126 FunctionDecl* getMatchingFunctionDecl() const {
14127 if (Matches.size() != 1) return nullptr;
14128 return Matches[0].second;
14129 }
14130
14131 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14132 if (Matches.size() != 1) return nullptr;
14133 return &Matches[0].first;
14134 }
14135};
14136}
14137
14138FunctionDecl *
14140 QualType TargetType,
14141 bool Complain,
14142 DeclAccessPair &FoundResult,
14143 bool *pHadMultipleCandidates) {
14144 assert(AddressOfExpr->getType() == Context.OverloadTy);
14145
14146 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14147 Complain);
14148 int NumMatches = Resolver.getNumMatches();
14149 FunctionDecl *Fn = nullptr;
14150 bool ShouldComplain = Complain && !Resolver.hasComplained();
14151 if (NumMatches == 0 && ShouldComplain) {
14152 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14153 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14154 else
14155 Resolver.ComplainNoMatchesFound();
14156 }
14157 else if (NumMatches > 1 && ShouldComplain)
14158 Resolver.ComplainMultipleMatchesFound();
14159 else if (NumMatches == 1) {
14160 Fn = Resolver.getMatchingFunctionDecl();
14161 assert(Fn);
14162 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14163 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14164 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14165 if (Complain) {
14166 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14167 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14168 else
14169 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14170 }
14171 }
14172
14173 if (pHadMultipleCandidates)
14174 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14175 return Fn;
14176}
14177
14181 OverloadExpr *Ovl = R.Expression;
14182 bool IsResultAmbiguous = false;
14183 FunctionDecl *Result = nullptr;
14184 DeclAccessPair DAP;
14185 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14186
14187 // Return positive for better, negative for worse, 0 for equal preference.
14188 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14189 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14190 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14191 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14192 };
14193
14194 // Don't use the AddressOfResolver because we're specifically looking for
14195 // cases where we have one overload candidate that lacks
14196 // enable_if/pass_object_size/...
14197 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14198 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14199 if (!FD)
14200 return nullptr;
14201
14203 continue;
14204
14205 // If we found a better result, update Result.
14206 auto FoundBetter = [&]() {
14207 IsResultAmbiguous = false;
14208 DAP = I.getPair();
14209 Result = FD;
14210 };
14211
14212 // We have more than one result - see if it is more
14213 // partial-ordering-constrained than the previous one.
14214 if (Result) {
14215 // Check CUDA preference first. If the candidates have differennt CUDA
14216 // preference, choose the one with higher CUDA preference. Otherwise,
14217 // choose the one with more constraints.
14218 if (getLangOpts().CUDA) {
14219 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14220 // FD has different preference than Result.
14221 if (PreferenceByCUDA != 0) {
14222 // FD is more preferable than Result.
14223 if (PreferenceByCUDA > 0)
14224 FoundBetter();
14225 continue;
14226 }
14227 }
14228 // FD has the same CUDA preference than Result. Continue to check
14229 // constraints.
14230
14231 // C++ [over.over]p5:
14232 // [...] Any given non-template function F0 is eliminated if the set
14233 // contains a second non-template function that is more
14234 // partial-ordering-constrained than F0 [...]
14235 FunctionDecl *MoreConstrained =
14237 /*IsFn1Reversed=*/false,
14238 /*IsFn2Reversed=*/false);
14239 if (MoreConstrained != FD) {
14240 if (!MoreConstrained) {
14241 IsResultAmbiguous = true;
14242 AmbiguousDecls.push_back(FD);
14243 }
14244 continue;
14245 }
14246 // FD is more constrained - replace Result with it.
14247 }
14248 FoundBetter();
14249 }
14250
14251 if (IsResultAmbiguous)
14252 return nullptr;
14253
14254 if (Result) {
14255 // We skipped over some ambiguous declarations which might be ambiguous with
14256 // the selected result.
14257 for (FunctionDecl *Skipped : AmbiguousDecls) {
14258 // If skipped candidate has different CUDA preference than the result,
14259 // there is no ambiguity. Otherwise check whether they have different
14260 // constraints.
14261 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14262 continue;
14263 if (!getMoreConstrainedFunction(Skipped, Result))
14264 return nullptr;
14265 }
14266 Pair = DAP;
14267 }
14268 return Result;
14269}
14270
14272 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14273 Expr *E = SrcExpr.get();
14274 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14275
14276 DeclAccessPair DAP;
14278 if (!Found || Found->isCPUDispatchMultiVersion() ||
14279 Found->isCPUSpecificMultiVersion())
14280 return false;
14281
14282 // Emitting multiple diagnostics for a function that is both inaccessible and
14283 // unavailable is consistent with our behavior elsewhere. So, always check
14284 // for both.
14288 if (Res.isInvalid())
14289 return false;
14290 Expr *Fixed = Res.get();
14291 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14292 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14293 else
14294 SrcExpr = Fixed;
14295 return true;
14296}
14297
14299 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14300 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14301 // C++ [over.over]p1:
14302 // [...] [Note: any redundant set of parentheses surrounding the
14303 // overloaded function name is ignored (5.1). ]
14304 // C++ [over.over]p1:
14305 // [...] The overloaded function name can be preceded by the &
14306 // operator.
14307
14308 // If we didn't actually find any template-ids, we're done.
14309 if (!ovl->hasExplicitTemplateArgs())
14310 return nullptr;
14311
14312 TemplateArgumentListInfo ExplicitTemplateArgs;
14313 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14314
14315 // Look through all of the overloaded functions, searching for one
14316 // whose type matches exactly.
14317 FunctionDecl *Matched = nullptr;
14318 for (UnresolvedSetIterator I = ovl->decls_begin(),
14319 E = ovl->decls_end(); I != E; ++I) {
14320 // C++0x [temp.arg.explicit]p3:
14321 // [...] In contexts where deduction is done and fails, or in contexts
14322 // where deduction is not done, if a template argument list is
14323 // specified and it, along with any default template arguments,
14324 // identifies a single function template specialization, then the
14325 // template-id is an lvalue for the function template specialization.
14327 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14328 if (!FunctionTemplate)
14329 continue;
14330
14331 // C++ [over.over]p2:
14332 // If the name is a function template, template argument deduction is
14333 // done (14.8.2.2), and if the argument deduction succeeds, the
14334 // resulting template argument list is used to generate a single
14335 // function template specialization, which is added to the set of
14336 // overloaded functions considered.
14337 FunctionDecl *Specialization = nullptr;
14338 TemplateDeductionInfo Info(ovl->getNameLoc());
14340 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14341 /*IsAddressOfFunction*/ true);
14343 // Make a note of the failed deduction for diagnostics.
14344 if (FailedTSC)
14345 FailedTSC->addCandidate().set(
14346 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14348 continue;
14349 }
14350
14351 assert(Specialization && "no specialization and no error?");
14352
14353 // C++ [temp.deduct.call]p6:
14354 // [...] If all successful deductions yield the same deduced A, that
14355 // deduced A is the result of deduction; otherwise, the parameter is
14356 // treated as a non-deduced context.
14357 if (Matched) {
14358 if (ForTypeDeduction &&
14360 Specialization->getType()))
14361 continue;
14362 // Multiple matches; we can't resolve to a single declaration.
14363 if (Complain) {
14364 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14365 << ovl->getName();
14367 }
14368 return nullptr;
14369 }
14370
14371 Matched = Specialization;
14372 if (FoundResult) *FoundResult = I.getPair();
14373 }
14374
14375 if (Matched &&
14376 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14377 return nullptr;
14378
14379 return Matched;
14380}
14381
14383 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14384 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14385 unsigned DiagIDForComplaining) {
14386 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14387
14389
14390 DeclAccessPair found;
14391 ExprResult SingleFunctionExpression;
14393 ovl.Expression, /*complain*/ false, &found)) {
14394 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14395 SrcExpr = ExprError();
14396 return true;
14397 }
14398
14399 // It is only correct to resolve to an instance method if we're
14400 // resolving a form that's permitted to be a pointer to member.
14401 // Otherwise we'll end up making a bound member expression, which
14402 // is illegal in all the contexts we resolve like this.
14403 if (!ovl.HasFormOfMemberPointer &&
14404 isa<CXXMethodDecl>(fn) &&
14405 cast<CXXMethodDecl>(fn)->isInstance()) {
14406 if (!complain) return false;
14407
14408 Diag(ovl.Expression->getExprLoc(),
14409 diag::err_bound_member_function)
14410 << 0 << ovl.Expression->getSourceRange();
14411
14412 // TODO: I believe we only end up here if there's a mix of
14413 // static and non-static candidates (otherwise the expression
14414 // would have 'bound member' type, not 'overload' type).
14415 // Ideally we would note which candidate was chosen and why
14416 // the static candidates were rejected.
14417 SrcExpr = ExprError();
14418 return true;
14419 }
14420
14421 // Fix the expression to refer to 'fn'.
14422 SingleFunctionExpression =
14423 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14424
14425 // If desired, do function-to-pointer decay.
14426 if (doFunctionPointerConversion) {
14427 SingleFunctionExpression =
14428 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14429 if (SingleFunctionExpression.isInvalid()) {
14430 SrcExpr = ExprError();
14431 return true;
14432 }
14433 }
14434 }
14435
14436 if (!SingleFunctionExpression.isUsable()) {
14437 if (complain) {
14438 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14439 << ovl.Expression->getName()
14440 << DestTypeForComplaining
14441 << OpRangeForComplaining
14443 NoteAllOverloadCandidates(SrcExpr.get());
14444
14445 SrcExpr = ExprError();
14446 return true;
14447 }
14448
14449 return false;
14450 }
14451
14452 SrcExpr = SingleFunctionExpression;
14453 return true;
14454}
14455
14456/// Add a single candidate to the overload set.
14458 DeclAccessPair FoundDecl,
14459 TemplateArgumentListInfo *ExplicitTemplateArgs,
14460 ArrayRef<Expr *> Args,
14461 OverloadCandidateSet &CandidateSet,
14462 bool PartialOverloading,
14463 bool KnownValid) {
14464 NamedDecl *Callee = FoundDecl.getDecl();
14465 if (isa<UsingShadowDecl>(Callee))
14466 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14467
14468 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14469 if (ExplicitTemplateArgs) {
14470 assert(!KnownValid && "Explicit template arguments?");
14471 return;
14472 }
14473 // Prevent ill-formed function decls to be added as overload candidates.
14474 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14475 return;
14476
14477 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14478 /*SuppressUserConversions=*/false,
14479 PartialOverloading);
14480 return;
14481 }
14482
14483 if (FunctionTemplateDecl *FuncTemplate
14484 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14485 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14486 ExplicitTemplateArgs, Args, CandidateSet,
14487 /*SuppressUserConversions=*/false,
14488 PartialOverloading);
14489 return;
14490 }
14491
14492 assert(!KnownValid && "unhandled case in overloaded call candidate");
14493}
14494
14496 ArrayRef<Expr *> Args,
14497 OverloadCandidateSet &CandidateSet,
14498 bool PartialOverloading) {
14499
14500#ifndef NDEBUG
14501 // Verify that ArgumentDependentLookup is consistent with the rules
14502 // in C++0x [basic.lookup.argdep]p3:
14503 //
14504 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14505 // and let Y be the lookup set produced by argument dependent
14506 // lookup (defined as follows). If X contains
14507 //
14508 // -- a declaration of a class member, or
14509 //
14510 // -- a block-scope function declaration that is not a
14511 // using-declaration, or
14512 //
14513 // -- a declaration that is neither a function or a function
14514 // template
14515 //
14516 // then Y is empty.
14517
14518 if (ULE->requiresADL()) {
14520 E = ULE->decls_end(); I != E; ++I) {
14521 assert(!(*I)->getDeclContext()->isRecord());
14522 assert(isa<UsingShadowDecl>(*I) ||
14523 !(*I)->getDeclContext()->isFunctionOrMethod());
14524 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14525 }
14526 }
14527#endif
14528
14529 // It would be nice to avoid this copy.
14530 TemplateArgumentListInfo TABuffer;
14531 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14532 if (ULE->hasExplicitTemplateArgs()) {
14533 ULE->copyTemplateArgumentsInto(TABuffer);
14534 ExplicitTemplateArgs = &TABuffer;
14535 }
14536
14538 E = ULE->decls_end(); I != E; ++I)
14539 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14540 CandidateSet, PartialOverloading,
14541 /*KnownValid*/ true);
14542
14543 if (ULE->requiresADL())
14545 Args, ExplicitTemplateArgs,
14546 CandidateSet, PartialOverloading);
14547}
14548
14550 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14551 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14552 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14553 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14554 CandidateSet, false, /*KnownValid*/ false);
14555}
14556
14557/// Determine whether a declaration with the specified name could be moved into
14558/// a different namespace.
14560 switch (Name.getCXXOverloadedOperator()) {
14561 case OO_New: case OO_Array_New:
14562 case OO_Delete: case OO_Array_Delete:
14563 return false;
14564
14565 default:
14566 return true;
14567 }
14568}
14569
14570/// Attempt to recover from an ill-formed use of a non-dependent name in a
14571/// template, where the non-dependent name was declared after the template
14572/// was defined. This is common in code written for a compilers which do not
14573/// correctly implement two-stage name lookup.
14574///
14575/// Returns true if a viable candidate was found and a diagnostic was issued.
14577 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14579 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14580 CXXRecordDecl **FoundInClass = nullptr) {
14581 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14582 return false;
14583
14584 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14585 if (DC->isTransparentContext())
14586 continue;
14587
14588 SemaRef.LookupQualifiedName(R, DC);
14589
14590 if (!R.empty()) {
14591 R.suppressDiagnostics();
14592
14593 OverloadCandidateSet Candidates(FnLoc, CSK);
14594 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14595 Candidates);
14596
14599 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14600
14601 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14602 // We either found non-function declarations or a best viable function
14603 // at class scope. A class-scope lookup result disables ADL. Don't
14604 // look past this, but let the caller know that we found something that
14605 // either is, or might be, usable in this class.
14606 if (FoundInClass) {
14607 *FoundInClass = RD;
14608 if (OR == OR_Success) {
14609 R.clear();
14610 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14611 R.resolveKind();
14612 }
14613 }
14614 return false;
14615 }
14616
14617 if (OR != OR_Success) {
14618 // There wasn't a unique best function or function template.
14619 return false;
14620 }
14621
14622 // Find the namespaces where ADL would have looked, and suggest
14623 // declaring the function there instead.
14624 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14625 Sema::AssociatedClassSet AssociatedClasses;
14626 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14627 AssociatedNamespaces,
14628 AssociatedClasses);
14629 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14630 if (canBeDeclaredInNamespace(R.getLookupName())) {
14631 DeclContext *Std = SemaRef.getStdNamespace();
14632 for (Sema::AssociatedNamespaceSet::iterator
14633 it = AssociatedNamespaces.begin(),
14634 end = AssociatedNamespaces.end(); it != end; ++it) {
14635 // Never suggest declaring a function within namespace 'std'.
14636 if (Std && Std->Encloses(*it))
14637 continue;
14638
14639 // Never suggest declaring a function within a namespace with a
14640 // reserved name, like __gnu_cxx.
14641 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14642 if (NS &&
14643 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14644 continue;
14645
14646 SuggestedNamespaces.insert(*it);
14647 }
14648 }
14649
14650 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14651 << R.getLookupName();
14652 if (SuggestedNamespaces.empty()) {
14653 SemaRef.Diag(Best->Function->getLocation(),
14654 diag::note_not_found_by_two_phase_lookup)
14655 << R.getLookupName() << 0;
14656 } else if (SuggestedNamespaces.size() == 1) {
14657 SemaRef.Diag(Best->Function->getLocation(),
14658 diag::note_not_found_by_two_phase_lookup)
14659 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14660 } else {
14661 // FIXME: It would be useful to list the associated namespaces here,
14662 // but the diagnostics infrastructure doesn't provide a way to produce
14663 // a localized representation of a list of items.
14664 SemaRef.Diag(Best->Function->getLocation(),
14665 diag::note_not_found_by_two_phase_lookup)
14666 << R.getLookupName() << 2;
14667 }
14668
14669 // Try to recover by calling this function.
14670 return true;
14671 }
14672
14673 R.clear();
14674 }
14675
14676 return false;
14677}
14678
14679/// Attempt to recover from ill-formed use of a non-dependent operator in a
14680/// template, where the non-dependent operator was declared after the template
14681/// was defined.
14682///
14683/// Returns true if a viable candidate was found and a diagnostic was issued.
14684static bool
14686 SourceLocation OpLoc,
14687 ArrayRef<Expr *> Args) {
14688 DeclarationName OpName =
14690 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14691 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14693 /*ExplicitTemplateArgs=*/nullptr, Args);
14694}
14695
14696namespace {
14697class BuildRecoveryCallExprRAII {
14698 Sema &SemaRef;
14699 Sema::SatisfactionStackResetRAII SatStack;
14700
14701public:
14702 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14703 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14704 SemaRef.IsBuildingRecoveryCallExpr = true;
14705 }
14706
14707 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14708};
14709}
14710
14711/// Attempts to recover from a call where no functions were found.
14712///
14713/// This function will do one of three things:
14714/// * Diagnose, recover, and return a recovery expression.
14715/// * Diagnose, fail to recover, and return ExprError().
14716/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14717/// expected to diagnose as appropriate.
14718static ExprResult
14721 SourceLocation LParenLoc,
14723 SourceLocation RParenLoc,
14724 bool EmptyLookup, bool AllowTypoCorrection) {
14725 // Do not try to recover if it is already building a recovery call.
14726 // This stops infinite loops for template instantiations like
14727 //
14728 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14729 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14730 if (SemaRef.IsBuildingRecoveryCallExpr)
14731 return ExprResult();
14732 BuildRecoveryCallExprRAII RCE(SemaRef);
14733
14734 CXXScopeSpec SS;
14735 SS.Adopt(ULE->getQualifierLoc());
14736 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14737
14738 TemplateArgumentListInfo TABuffer;
14739 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14740 if (ULE->hasExplicitTemplateArgs()) {
14741 ULE->copyTemplateArgumentsInto(TABuffer);
14742 ExplicitTemplateArgs = &TABuffer;
14743 }
14744
14745 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14747 CXXRecordDecl *FoundInClass = nullptr;
14748 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14750 ExplicitTemplateArgs, Args, &FoundInClass)) {
14751 // OK, diagnosed a two-phase lookup issue.
14752 } else if (EmptyLookup) {
14753 // Try to recover from an empty lookup with typo correction.
14754 R.clear();
14755 NoTypoCorrectionCCC NoTypoValidator{};
14756 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14757 ExplicitTemplateArgs != nullptr,
14758 dyn_cast<MemberExpr>(Fn));
14759 CorrectionCandidateCallback &Validator =
14760 AllowTypoCorrection
14761 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14762 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14763 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14764 Args))
14765 return ExprError();
14766 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14767 // We found a usable declaration of the name in a dependent base of some
14768 // enclosing class.
14769 // FIXME: We should also explain why the candidates found by name lookup
14770 // were not viable.
14771 if (SemaRef.DiagnoseDependentMemberLookup(R))
14772 return ExprError();
14773 } else {
14774 // We had viable candidates and couldn't recover; let the caller diagnose
14775 // this.
14776 return ExprResult();
14777 }
14778
14779 // If we get here, we should have issued a diagnostic and formed a recovery
14780 // lookup result.
14781 assert(!R.empty() && "lookup results empty despite recovery");
14782
14783 // If recovery created an ambiguity, just bail out.
14784 if (R.isAmbiguous()) {
14785 R.suppressDiagnostics();
14786 return ExprError();
14787 }
14788
14789 // Build an implicit member call if appropriate. Just drop the
14790 // casts and such from the call, we don't really care.
14791 ExprResult NewFn = ExprError();
14792 if ((*R.begin())->isCXXClassMember())
14793 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14794 ExplicitTemplateArgs, S);
14795 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14796 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14797 ExplicitTemplateArgs);
14798 else
14799 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14800
14801 if (NewFn.isInvalid())
14802 return ExprError();
14803
14804 // This shouldn't cause an infinite loop because we're giving it
14805 // an expression with viable lookup results, which should never
14806 // end up here.
14807 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14808 MultiExprArg(Args.data(), Args.size()),
14809 RParenLoc);
14810}
14811
14814 MultiExprArg Args,
14815 SourceLocation RParenLoc,
14816 OverloadCandidateSet *CandidateSet,
14817 ExprResult *Result) {
14818#ifndef NDEBUG
14819 if (ULE->requiresADL()) {
14820 // To do ADL, we must have found an unqualified name.
14821 assert(!ULE->getQualifier() && "qualified name with ADL");
14822
14823 // We don't perform ADL for implicit declarations of builtins.
14824 // Verify that this was correctly set up.
14825 FunctionDecl *F;
14826 if (ULE->decls_begin() != ULE->decls_end() &&
14827 ULE->decls_begin() + 1 == ULE->decls_end() &&
14828 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14829 F->getBuiltinID() && F->isImplicit())
14830 llvm_unreachable("performing ADL for builtin");
14831
14832 // We don't perform ADL in C.
14833 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14834 }
14835#endif
14836
14837 UnbridgedCastsSet UnbridgedCasts;
14838 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14839 *Result = ExprError();
14840 return true;
14841 }
14842
14843 // Add the functions denoted by the callee to the set of candidate
14844 // functions, including those from argument-dependent lookup.
14845 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14846
14847 if (getLangOpts().MSVCCompat &&
14848 CurContext->isDependentContext() && !isSFINAEContext() &&
14850
14852 if (CandidateSet->empty() ||
14853 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14855 // In Microsoft mode, if we are inside a template class member function
14856 // then create a type dependent CallExpr. The goal is to postpone name
14857 // lookup to instantiation time to be able to search into type dependent
14858 // base classes.
14859 CallExpr *CE =
14860 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14861 RParenLoc, CurFPFeatureOverrides());
14863 *Result = CE;
14864 return true;
14865 }
14866 }
14867
14868 if (CandidateSet->empty())
14869 return false;
14870
14871 UnbridgedCasts.restore();
14872 return false;
14873}
14874
14875// Guess at what the return type for an unresolvable overload should be.
14878 std::optional<QualType> Result;
14879 // Adjust Type after seeing a candidate.
14880 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14881 if (!Candidate.Function)
14882 return;
14883 if (Candidate.Function->isInvalidDecl())
14884 return;
14885 QualType T = Candidate.Function->getReturnType();
14886 if (T.isNull())
14887 return;
14888 if (!Result)
14889 Result = T;
14890 else if (Result != T)
14891 Result = QualType();
14892 };
14893
14894 // Look for an unambiguous type from a progressively larger subset.
14895 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14896 //
14897 // First, consider only the best candidate.
14898 if (Best && *Best != CS.end())
14899 ConsiderCandidate(**Best);
14900 // Next, consider only viable candidates.
14901 if (!Result)
14902 for (const auto &C : CS)
14903 if (C.Viable)
14904 ConsiderCandidate(C);
14905 // Finally, consider all candidates.
14906 if (!Result)
14907 for (const auto &C : CS)
14908 ConsiderCandidate(C);
14909
14910 if (!Result)
14911 return QualType();
14912 auto Value = *Result;
14913 if (Value.isNull() || Value->isUndeducedType())
14914 return QualType();
14915 return Value;
14916}
14917
14918/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14919/// the completed call expression. If overload resolution fails, emits
14920/// diagnostics and returns ExprError()
14923 SourceLocation LParenLoc,
14924 MultiExprArg Args,
14925 SourceLocation RParenLoc,
14926 Expr *ExecConfig,
14927 OverloadCandidateSet *CandidateSet,
14929 OverloadingResult OverloadResult,
14930 bool AllowTypoCorrection) {
14931 switch (OverloadResult) {
14932 case OR_Success: {
14933 FunctionDecl *FDecl = (*Best)->Function;
14934 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14935 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14936 return ExprError();
14937 ExprResult Res =
14938 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14939 if (Res.isInvalid())
14940 return ExprError();
14941 return SemaRef.BuildResolvedCallExpr(
14942 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14943 /*IsExecConfig=*/false,
14944 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14945 }
14946
14947 case OR_No_Viable_Function: {
14948 if (*Best != CandidateSet->end() &&
14949 CandidateSet->getKind() ==
14951 if (CXXMethodDecl *M =
14952 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14954 CandidateSet->NoteCandidates(
14956 Fn->getBeginLoc(),
14957 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14958 SemaRef, OCD_AmbiguousCandidates, Args);
14959 return ExprError();
14960 }
14961 }
14962
14963 // Try to recover by looking for viable functions which the user might
14964 // have meant to call.
14965 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14966 Args, RParenLoc,
14967 CandidateSet->empty(),
14968 AllowTypoCorrection);
14969 if (Recovery.isInvalid() || Recovery.isUsable())
14970 return Recovery;
14971
14972 // If the user passes in a function that we can't take the address of, we
14973 // generally end up emitting really bad error messages. Here, we attempt to
14974 // emit better ones.
14975 for (const Expr *Arg : Args) {
14976 if (!Arg->getType()->isFunctionType())
14977 continue;
14978 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14979 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14980 if (FD &&
14981 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14982 Arg->getExprLoc()))
14983 return ExprError();
14984 }
14985 }
14986
14987 CandidateSet->NoteCandidates(
14989 Fn->getBeginLoc(),
14990 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14991 << ULE->getName() << Fn->getSourceRange()),
14992 SemaRef, OCD_AllCandidates, Args);
14993 break;
14994 }
14995
14996 case OR_Ambiguous:
14997 CandidateSet->NoteCandidates(
14998 PartialDiagnosticAt(Fn->getBeginLoc(),
14999 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15000 << ULE->getName() << Fn->getSourceRange()),
15001 SemaRef, OCD_AmbiguousCandidates, Args);
15002 break;
15003
15004 case OR_Deleted: {
15005 FunctionDecl *FDecl = (*Best)->Function;
15006 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15007 Fn->getSourceRange(), ULE->getName(),
15008 *CandidateSet, FDecl, Args);
15009
15010 // We emitted an error for the unavailable/deleted function call but keep
15011 // the call in the AST.
15012 ExprResult Res =
15013 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15014 if (Res.isInvalid())
15015 return ExprError();
15016 return SemaRef.BuildResolvedCallExpr(
15017 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15018 /*IsExecConfig=*/false,
15019 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15020 }
15021 }
15022
15023 // Overload resolution failed, try to recover.
15024 SmallVector<Expr *, 8> SubExprs = {Fn};
15025 SubExprs.append(Args.begin(), Args.end());
15026 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15027 chooseRecoveryType(*CandidateSet, Best));
15028}
15029
15032 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15033 if (I->Viable &&
15034 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15035 I->Viable = false;
15036 I->FailureKind = ovl_fail_addr_not_available;
15037 }
15038 }
15039}
15040
15043 SourceLocation LParenLoc,
15044 MultiExprArg Args,
15045 SourceLocation RParenLoc,
15046 Expr *ExecConfig,
15047 bool AllowTypoCorrection,
15048 bool CalleesAddressIsTaken) {
15049
15053
15054 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15055 ExprResult result;
15056
15057 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15058 &result))
15059 return result;
15060
15061 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15062 // functions that aren't addressible are considered unviable.
15063 if (CalleesAddressIsTaken)
15064 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15065
15067 OverloadingResult OverloadResult =
15068 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15069
15070 // [C++23][over.call.func]
15071 // if overload resolution selects a non-static member function,
15072 // the call is ill-formed;
15074 Best != CandidateSet.end()) {
15075 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15076 M && M->isImplicitObjectMemberFunction()) {
15077 OverloadResult = OR_No_Viable_Function;
15078 }
15079 }
15080
15081 // Model the case with a call to a templated function whose definition
15082 // encloses the call and whose return type contains a placeholder type as if
15083 // the UnresolvedLookupExpr was type-dependent.
15084 if (OverloadResult == OR_Success) {
15085 const FunctionDecl *FDecl = Best->Function;
15086 if (LangOpts.CUDA)
15087 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15088 if (FDecl && FDecl->isTemplateInstantiation() &&
15089 FDecl->getReturnType()->isUndeducedType()) {
15090
15091 // Creating dependent CallExpr is not okay if the enclosing context itself
15092 // is not dependent. This situation notably arises if a non-dependent
15093 // member function calls the later-defined overloaded static function.
15094 //
15095 // For example, in
15096 // class A {
15097 // void c() { callee(1); }
15098 // static auto callee(auto x) { }
15099 // };
15100 //
15101 // Here callee(1) is unresolved at the call site, but is not inside a
15102 // dependent context. There will be no further attempt to resolve this
15103 // call if it is made dependent.
15104
15105 if (const auto *TP =
15106 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15107 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15108 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15109 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15110 }
15111 }
15112 }
15113
15114 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15115 ExecConfig, &CandidateSet, &Best,
15116 OverloadResult, AllowTypoCorrection);
15117}
15118
15122 const UnresolvedSetImpl &Fns,
15123 bool PerformADL) {
15125 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15126 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15127}
15128
15131 bool HadMultipleCandidates) {
15132 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15133 // the FoundDecl as it impedes TransformMemberExpr.
15134 // We go a bit further here: if there's no difference in UnderlyingDecl,
15135 // then using FoundDecl vs Method shouldn't make a difference either.
15136 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15137 FoundDecl = Method;
15138 // Convert the expression to match the conversion function's implicit object
15139 // parameter.
15140 ExprResult Exp;
15141 if (Method->isExplicitObjectMemberFunction())
15143 else
15145 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15146 if (Exp.isInvalid())
15147 return true;
15148
15149 if (Method->getParent()->isLambda() &&
15150 Method->getConversionType()->isBlockPointerType()) {
15151 // This is a lambda conversion to block pointer; check if the argument
15152 // was a LambdaExpr.
15153 Expr *SubE = E;
15154 auto *CE = dyn_cast<CastExpr>(SubE);
15155 if (CE && CE->getCastKind() == CK_NoOp)
15156 SubE = CE->getSubExpr();
15157 SubE = SubE->IgnoreParens();
15158 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15159 SubE = BE->getSubExpr();
15160 if (isa<LambdaExpr>(SubE)) {
15161 // For the conversion to block pointer on a lambda expression, we
15162 // construct a special BlockLiteral instead; this doesn't really make
15163 // a difference in ARC, but outside of ARC the resulting block literal
15164 // follows the normal lifetime rules for block literals instead of being
15165 // autoreleased.
15169 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15171
15172 // FIXME: This note should be produced by a CodeSynthesisContext.
15173 if (BlockExp.isInvalid())
15174 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15175 return BlockExp;
15176 }
15177 }
15178 CallExpr *CE;
15179 QualType ResultType = Method->getReturnType();
15181 ResultType = ResultType.getNonLValueExprType(Context);
15182 if (Method->isExplicitObjectMemberFunction()) {
15183 ExprResult FnExpr =
15184 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15185 HadMultipleCandidates, E->getBeginLoc());
15186 if (FnExpr.isInvalid())
15187 return ExprError();
15188 Expr *ObjectParam = Exp.get();
15189 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15190 ResultType, VK, Exp.get()->getEndLoc(),
15192 CE->setUsesMemberSyntax(true);
15193 } else {
15194 MemberExpr *ME =
15195 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15197 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15198 HadMultipleCandidates, DeclarationNameInfo(),
15199 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15200
15201 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15202 Exp.get()->getEndLoc(),
15204 }
15205
15206 if (CheckFunctionCall(Method, CE,
15207 Method->getType()->castAs<FunctionProtoType>()))
15208 return ExprError();
15209
15211}
15212
15215 const UnresolvedSetImpl &Fns,
15216 Expr *Input, bool PerformADL) {
15218 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15219 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15220 // TODO: provide better source location info.
15221 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15222
15223 if (checkPlaceholderForOverload(*this, Input))
15224 return ExprError();
15225
15226 Expr *Args[2] = { Input, nullptr };
15227 unsigned NumArgs = 1;
15228
15229 // For post-increment and post-decrement, add the implicit '0' as
15230 // the second argument, so that we know this is a post-increment or
15231 // post-decrement.
15232 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15233 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15234 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15235 SourceLocation());
15236 NumArgs = 2;
15237 }
15238
15239 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15240
15241 if (Input->isTypeDependent()) {
15243 // [C++26][expr.unary.op][expr.pre.incr]
15244 // The * operator yields an lvalue of type
15245 // The pre/post increment operators yied an lvalue.
15246 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15247 VK = VK_LValue;
15248
15249 if (Fns.empty())
15250 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15251 OK_Ordinary, OpLoc, false,
15253
15254 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15256 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15257 if (Fn.isInvalid())
15258 return ExprError();
15259 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15260 Context.DependentTy, VK_PRValue, OpLoc,
15262 }
15263
15264 // Build an empty overload set.
15266
15267 // Add the candidates from the given function set.
15268 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15269
15270 // Add operator candidates that are member functions.
15271 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15272
15273 // Add candidates from ADL.
15274 if (PerformADL) {
15275 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15276 /*ExplicitTemplateArgs*/nullptr,
15277 CandidateSet);
15278 }
15279
15280 // Add builtin operator candidates.
15281 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15282
15283 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15284
15285 // Perform overload resolution.
15287 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15288 case OR_Success: {
15289 // We found a built-in operator or an overloaded operator.
15290 FunctionDecl *FnDecl = Best->Function;
15291
15292 if (FnDecl) {
15293 Expr *Base = nullptr;
15294 // We matched an overloaded operator. Build a call to that
15295 // operator.
15296
15297 // Convert the arguments.
15298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15299 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15300
15301 ExprResult InputInit;
15302 if (Method->isExplicitObjectMemberFunction())
15303 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15304 else
15306 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15307 if (InputInit.isInvalid())
15308 return ExprError();
15309 Base = Input = InputInit.get();
15310 } else {
15311 // Convert the arguments.
15312 ExprResult InputInit
15314 Context,
15315 FnDecl->getParamDecl(0)),
15317 Input);
15318 if (InputInit.isInvalid())
15319 return ExprError();
15320 Input = InputInit.get();
15321 }
15322
15323 // Build the actual expression node.
15324 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15325 Base, HadMultipleCandidates,
15326 OpLoc);
15327 if (FnExpr.isInvalid())
15328 return ExprError();
15329
15330 // Determine the result type.
15331 QualType ResultTy = FnDecl->getReturnType();
15333 ResultTy = ResultTy.getNonLValueExprType(Context);
15334
15335 Args[0] = Input;
15337 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15339 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15340
15341 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15342 return ExprError();
15343
15344 if (CheckFunctionCall(FnDecl, TheCall,
15345 FnDecl->getType()->castAs<FunctionProtoType>()))
15346 return ExprError();
15347 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15348 } else {
15349 // We matched a built-in operator. Convert the arguments, then
15350 // break out so that we will build the appropriate built-in
15351 // operator node.
15353 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15356 if (InputRes.isInvalid())
15357 return ExprError();
15358 Input = InputRes.get();
15359 break;
15360 }
15361 }
15362
15364 // This is an erroneous use of an operator which can be overloaded by
15365 // a non-member function. Check for non-member operators which were
15366 // defined too late to be candidates.
15367 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15368 // FIXME: Recover by calling the found function.
15369 return ExprError();
15370
15371 // No viable function; fall through to handling this as a
15372 // built-in operator, which will produce an error message for us.
15373 break;
15374
15375 case OR_Ambiguous:
15376 CandidateSet.NoteCandidates(
15377 PartialDiagnosticAt(OpLoc,
15378 PDiag(diag::err_ovl_ambiguous_oper_unary)
15380 << Input->getType() << Input->getSourceRange()),
15381 *this, OCD_AmbiguousCandidates, ArgsArray,
15382 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15383 return ExprError();
15384
15385 case OR_Deleted: {
15386 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15387 // object whose method was called. Later in NoteCandidates size of ArgsArray
15388 // is passed further and it eventually ends up compared to number of
15389 // function candidate parameters which never includes the object parameter,
15390 // so slice ArgsArray to make sure apples are compared to apples.
15391 StringLiteral *Msg = Best->Function->getDeletedMessage();
15392 CandidateSet.NoteCandidates(
15393 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15395 << (Msg != nullptr)
15396 << (Msg ? Msg->getString() : StringRef())
15397 << Input->getSourceRange()),
15398 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15399 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15400 return ExprError();
15401 }
15402 }
15403
15404 // Either we found no viable overloaded operator or we matched a
15405 // built-in operator. In either case, fall through to trying to
15406 // build a built-in operation.
15407 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15408}
15409
15412 const UnresolvedSetImpl &Fns,
15413 ArrayRef<Expr *> Args, bool PerformADL) {
15414 SourceLocation OpLoc = CandidateSet.getLocation();
15415
15416 OverloadedOperatorKind ExtraOp =
15419 : OO_None;
15420
15421 // Add the candidates from the given function set. This also adds the
15422 // rewritten candidates using these functions if necessary.
15423 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15424
15425 // As template candidates are not deduced immediately,
15426 // persist the array in the overload set.
15427 ArrayRef<Expr *> ReversedArgs;
15428 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15429 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15430 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15431
15432 // Add operator candidates that are member functions.
15433 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15434 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15435 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15437
15438 // In C++20, also add any rewritten member candidates.
15439 if (ExtraOp) {
15440 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15441 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15442 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15444 }
15445
15446 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15447 // performed for an assignment operator (nor for operator[] nor operator->,
15448 // which don't get here).
15449 if (Op != OO_Equal && PerformADL) {
15450 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15451 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15452 /*ExplicitTemplateArgs*/ nullptr,
15453 CandidateSet);
15454 if (ExtraOp) {
15455 DeclarationName ExtraOpName =
15456 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15457 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15458 /*ExplicitTemplateArgs*/ nullptr,
15459 CandidateSet);
15460 }
15461 }
15462
15463 // Add builtin operator candidates.
15464 //
15465 // FIXME: We don't add any rewritten candidates here. This is strictly
15466 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15467 // resulting in our selecting a rewritten builtin candidate. For example:
15468 //
15469 // enum class E { e };
15470 // bool operator!=(E, E) requires false;
15471 // bool k = E::e != E::e;
15472 //
15473 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15474 // it seems unreasonable to consider rewritten builtin candidates. A core
15475 // issue has been filed proposing to removed this requirement.
15476 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15477}
15478
15481 const UnresolvedSetImpl &Fns, Expr *LHS,
15482 Expr *RHS, bool PerformADL,
15483 bool AllowRewrittenCandidates,
15484 FunctionDecl *DefaultedFn) {
15485 Expr *Args[2] = { LHS, RHS };
15486 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15487
15488 if (!getLangOpts().CPlusPlus20)
15489 AllowRewrittenCandidates = false;
15490
15492
15493 // If either side is type-dependent, create an appropriate dependent
15494 // expression.
15495 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15496 if (Fns.empty()) {
15497 // If there are no functions to store, just build a dependent
15498 // BinaryOperator or CompoundAssignment.
15501 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15502 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15503 Context.DependentTy);
15505 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15507 }
15508
15509 // FIXME: save results of ADL from here?
15510 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15511 // TODO: provide better source location info in DNLoc component.
15512 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15513 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15515 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15516 if (Fn.isInvalid())
15517 return ExprError();
15518 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15519 Context.DependentTy, VK_PRValue, OpLoc,
15521 }
15522
15523 // If this is the .* operator, which is not overloadable, just
15524 // create a built-in binary operator.
15525 if (Opc == BO_PtrMemD) {
15526 auto CheckPlaceholder = [&](Expr *&Arg) {
15528 if (Res.isUsable())
15529 Arg = Res.get();
15530 return !Res.isUsable();
15531 };
15532
15533 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15534 // expression that contains placeholders (in either the LHS or RHS).
15535 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15536 return ExprError();
15537 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15538 }
15539
15540 // Always do placeholder-like conversions on the RHS.
15541 if (checkPlaceholderForOverload(*this, Args[1]))
15542 return ExprError();
15543
15544 // Do placeholder-like conversion on the LHS; note that we should
15545 // not get here with a PseudoObject LHS.
15546 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15547 if (checkPlaceholderForOverload(*this, Args[0]))
15548 return ExprError();
15549
15550 // If this is the assignment operator, we only perform overload resolution
15551 // if the left-hand side is a class or enumeration type. This is actually
15552 // a hack. The standard requires that we do overload resolution between the
15553 // various built-in candidates, but as DR507 points out, this can lead to
15554 // problems. So we do it this way, which pretty much follows what GCC does.
15555 // Note that we go the traditional code path for compound assignment forms.
15556 // In HLSL, user-defined structs/classes do not have constructors or
15557 // overloadable assignment operators, so we can take this shortcut too.
15558 const Type *LHSTy = Args[0]->getType().getTypePtr();
15559 if (Opc == BO_Assign &&
15560 (!LHSTy->isOverloadableType() ||
15561 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15563 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15564
15565 // Build the overload set.
15568 Op, OpLoc, AllowRewrittenCandidates));
15569 if (DefaultedFn)
15570 CandidateSet.exclude(DefaultedFn);
15571 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15572
15573 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15574
15575 // Perform overload resolution.
15577 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15578 case OR_Success: {
15579 // We found a built-in operator or an overloaded operator.
15580 FunctionDecl *FnDecl = Best->Function;
15581
15582 bool IsReversed = Best->isReversed();
15583 if (IsReversed)
15584 std::swap(Args[0], Args[1]);
15585
15586 if (FnDecl) {
15587
15588 if (FnDecl->isInvalidDecl())
15589 return ExprError();
15590
15591 Expr *Base = nullptr;
15592 // We matched an overloaded operator. Build a call to that
15593 // operator.
15594
15595 OverloadedOperatorKind ChosenOp =
15597
15598 // C++2a [over.match.oper]p9:
15599 // If a rewritten operator== candidate is selected by overload
15600 // resolution for an operator@, its return type shall be cv bool
15601 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15602 !FnDecl->getReturnType()->isBooleanType()) {
15603 bool IsExtension =
15605 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15606 : diag::err_ovl_rewrite_equalequal_not_bool)
15607 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15608 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15609 Diag(FnDecl->getLocation(), diag::note_declared_at);
15610 if (!IsExtension)
15611 return ExprError();
15612 }
15613
15614 if (AllowRewrittenCandidates && !IsReversed &&
15615 CandidateSet.getRewriteInfo().isReversible()) {
15616 // We could have reversed this operator, but didn't. Check if some
15617 // reversed form was a viable candidate, and if so, if it had a
15618 // better conversion for either parameter. If so, this call is
15619 // formally ambiguous, and allowing it is an extension.
15621 for (OverloadCandidate &Cand : CandidateSet) {
15622 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15623 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15624 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15626 *this, OpLoc, Cand.Conversions[ArgIdx],
15627 Best->Conversions[ArgIdx]) ==
15629 AmbiguousWith.push_back(Cand.Function);
15630 break;
15631 }
15632 }
15633 }
15634 }
15635
15636 if (!AmbiguousWith.empty()) {
15637 bool AmbiguousWithSelf =
15638 AmbiguousWith.size() == 1 &&
15639 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15640 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15642 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15643 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15644 if (AmbiguousWithSelf) {
15645 Diag(FnDecl->getLocation(),
15646 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15647 // Mark member== const or provide matching != to disallow reversed
15648 // args. Eg.
15649 // struct S { bool operator==(const S&); };
15650 // S()==S();
15651 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15652 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15653 !MD->isConst() &&
15654 !MD->hasCXXExplicitFunctionObjectParameter() &&
15655 Context.hasSameUnqualifiedType(
15656 MD->getFunctionObjectParameterType(),
15657 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15658 Context.hasSameUnqualifiedType(
15659 MD->getFunctionObjectParameterType(),
15660 Args[0]->getType()) &&
15661 Context.hasSameUnqualifiedType(
15662 MD->getFunctionObjectParameterType(),
15663 Args[1]->getType()))
15664 Diag(FnDecl->getLocation(),
15665 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15666 } else {
15667 Diag(FnDecl->getLocation(),
15668 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15669 for (auto *F : AmbiguousWith)
15670 Diag(F->getLocation(),
15671 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15672 }
15673 }
15674 }
15675
15676 // Check for nonnull = nullable.
15677 // This won't be caught in the arg's initialization: the parameter to
15678 // the assignment operator is not marked nonnull.
15679 if (Op == OO_Equal)
15681 Args[1]->getType(), OpLoc);
15682
15683 // Convert the arguments.
15684 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15685 // Best->Access is only meaningful for class members.
15686 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15687
15688 ExprResult Arg0, Arg1;
15689 unsigned ParamIdx = 0;
15690 if (Method->isExplicitObjectMemberFunction()) {
15691 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15692 ParamIdx = 1;
15693 } else {
15695 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15696 }
15699 Context, FnDecl->getParamDecl(ParamIdx)),
15700 SourceLocation(), Args[1]);
15701 if (Arg0.isInvalid() || Arg1.isInvalid())
15702 return ExprError();
15703
15704 Base = Args[0] = Arg0.getAs<Expr>();
15705 Args[1] = RHS = Arg1.getAs<Expr>();
15706 } else {
15707 // Convert the arguments.
15710 FnDecl->getParamDecl(0)),
15711 SourceLocation(), Args[0]);
15712 if (Arg0.isInvalid())
15713 return ExprError();
15714
15715 ExprResult Arg1 =
15718 FnDecl->getParamDecl(1)),
15719 SourceLocation(), Args[1]);
15720 if (Arg1.isInvalid())
15721 return ExprError();
15722 Args[0] = LHS = Arg0.getAs<Expr>();
15723 Args[1] = RHS = Arg1.getAs<Expr>();
15724 }
15725
15726 // Build the actual expression node.
15727 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15728 Best->FoundDecl, Base,
15729 HadMultipleCandidates, OpLoc);
15730 if (FnExpr.isInvalid())
15731 return ExprError();
15732
15733 // Determine the result type.
15734 QualType ResultTy = FnDecl->getReturnType();
15736 ResultTy = ResultTy.getNonLValueExprType(Context);
15737
15738 CallExpr *TheCall;
15739 ArrayRef<const Expr *> ArgsArray(Args, 2);
15740 const Expr *ImplicitThis = nullptr;
15741
15742 // We always create a CXXOperatorCallExpr, even for explicit object
15743 // members; CodeGen should take care not to emit the this pointer.
15745 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15747 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15748 IsReversed);
15749
15750 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15751 Method && Method->isImplicitObjectMemberFunction()) {
15752 // Cut off the implicit 'this'.
15753 ImplicitThis = ArgsArray[0];
15754 ArgsArray = ArgsArray.slice(1);
15755 }
15756
15757 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15758 FnDecl))
15759 return ExprError();
15760
15761 if (Op == OO_Equal) {
15762 // Check for a self move.
15763 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15764 // lifetime check.
15766 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15767 Args[1]);
15768 }
15769 if (ImplicitThis) {
15770 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15771 QualType ThisTypeFromDecl = Context.getPointerType(
15772 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15773
15774 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15775 ThisTypeFromDecl);
15776 }
15777
15778 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15779 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15781
15782 ExprResult R = MaybeBindToTemporary(TheCall);
15783 if (R.isInvalid())
15784 return ExprError();
15785
15786 R = CheckForImmediateInvocation(R, FnDecl);
15787 if (R.isInvalid())
15788 return ExprError();
15789
15790 // For a rewritten candidate, we've already reversed the arguments
15791 // if needed. Perform the rest of the rewrite now.
15792 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15793 (Op == OO_Spaceship && IsReversed)) {
15794 if (Op == OO_ExclaimEqual) {
15795 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15796 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15797 } else {
15798 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15799 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15800 Expr *ZeroLiteral =
15802
15805 Ctx.Entity = FnDecl;
15807
15809 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15810 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15811 /*AllowRewrittenCandidates=*/false);
15812
15814 }
15815 if (R.isInvalid())
15816 return ExprError();
15817 } else {
15818 assert(ChosenOp == Op && "unexpected operator name");
15819 }
15820
15821 // Make a note in the AST if we did any rewriting.
15822 if (Best->RewriteKind != CRK_None)
15823 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15824
15825 return R;
15826 } else {
15827 // We matched a built-in operator. Convert the arguments, then
15828 // break out so that we will build the appropriate built-in
15829 // operator node.
15831 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15834 if (ArgsRes0.isInvalid())
15835 return ExprError();
15836 Args[0] = ArgsRes0.get();
15837
15839 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15842 if (ArgsRes1.isInvalid())
15843 return ExprError();
15844 Args[1] = ArgsRes1.get();
15845 break;
15846 }
15847 }
15848
15849 case OR_No_Viable_Function: {
15850 // C++ [over.match.oper]p9:
15851 // If the operator is the operator , [...] and there are no
15852 // viable functions, then the operator is assumed to be the
15853 // built-in operator and interpreted according to clause 5.
15854 if (Opc == BO_Comma)
15855 break;
15856
15857 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15858 // compare result using '==' and '<'.
15859 if (DefaultedFn && Opc == BO_Cmp) {
15860 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15861 Args[1], DefaultedFn);
15862 if (E.isInvalid() || E.isUsable())
15863 return E;
15864 }
15865
15866 // For class as left operand for assignment or compound assignment
15867 // operator do not fall through to handling in built-in, but report that
15868 // no overloaded assignment operator found
15870 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15871 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15872 Args, OpLoc);
15873 DeferDiagsRAII DDR(*this,
15874 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15875 if (Args[0]->getType()->isRecordType() &&
15876 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15877 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15879 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15880 if (Args[0]->getType()->isIncompleteType()) {
15881 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15882 << Args[0]->getType()
15883 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15884 }
15885 } else {
15886 // This is an erroneous use of an operator which can be overloaded by
15887 // a non-member function. Check for non-member operators which were
15888 // defined too late to be candidates.
15889 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15890 // FIXME: Recover by calling the found function.
15891 return ExprError();
15892
15893 // No viable function; try to create a built-in operation, which will
15894 // produce an error. Then, show the non-viable candidates.
15895 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15896 }
15897 assert(Result.isInvalid() &&
15898 "C++ binary operator overloading is missing candidates!");
15899 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15900 return Result;
15901 }
15902
15903 case OR_Ambiguous:
15904 CandidateSet.NoteCandidates(
15905 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15907 << Args[0]->getType()
15908 << Args[1]->getType()
15909 << Args[0]->getSourceRange()
15910 << Args[1]->getSourceRange()),
15912 OpLoc);
15913 return ExprError();
15914
15915 case OR_Deleted: {
15916 if (isImplicitlyDeleted(Best->Function)) {
15917 FunctionDecl *DeletedFD = Best->Function;
15919 if (DFK.isSpecialMember()) {
15920 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15921 << Args[0]->getType() << DFK.asSpecialMember();
15922 } else {
15923 assert(DFK.isComparison());
15924 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15925 << Args[0]->getType() << DeletedFD;
15926 }
15927
15928 // The user probably meant to call this special member. Just
15929 // explain why it's deleted.
15930 NoteDeletedFunction(DeletedFD);
15931 return ExprError();
15932 }
15933
15934 StringLiteral *Msg = Best->Function->getDeletedMessage();
15935 CandidateSet.NoteCandidates(
15937 OpLoc,
15938 PDiag(diag::err_ovl_deleted_oper)
15939 << getOperatorSpelling(Best->Function->getDeclName()
15940 .getCXXOverloadedOperator())
15941 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15942 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15944 OpLoc);
15945 return ExprError();
15946 }
15947 }
15948
15949 // We matched a built-in operator; build it.
15950 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15951}
15952
15954 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15955 FunctionDecl *DefaultedFn) {
15956 const ComparisonCategoryInfo *Info =
15957 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15958 // If we're not producing a known comparison category type, we can't
15959 // synthesize a three-way comparison. Let the caller diagnose this.
15960 if (!Info)
15961 return ExprResult((Expr*)nullptr);
15962
15963 // If we ever want to perform this synthesis more generally, we will need to
15964 // apply the temporary materialization conversion to the operands.
15965 assert(LHS->isGLValue() && RHS->isGLValue() &&
15966 "cannot use prvalue expressions more than once");
15967 Expr *OrigLHS = LHS;
15968 Expr *OrigRHS = RHS;
15969
15970 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15971 // each of them multiple times below.
15972 LHS = new (Context)
15973 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15974 LHS->getObjectKind(), LHS);
15975 RHS = new (Context)
15976 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15977 RHS->getObjectKind(), RHS);
15978
15979 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15980 DefaultedFn);
15981 if (Eq.isInvalid())
15982 return ExprError();
15983
15984 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15985 true, DefaultedFn);
15986 if (Less.isInvalid())
15987 return ExprError();
15988
15990 if (Info->isPartial()) {
15991 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15992 DefaultedFn);
15993 if (Greater.isInvalid())
15994 return ExprError();
15995 }
15996
15997 // Form the list of comparisons we're going to perform.
15998 struct Comparison {
16001 } Comparisons[4] =
16007 };
16008
16009 int I = Info->isPartial() ? 3 : 2;
16010
16011 // Combine the comparisons with suitable conditional expressions.
16013 for (; I >= 0; --I) {
16014 // Build a reference to the comparison category constant.
16015 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16016 // FIXME: Missing a constant for a comparison category. Diagnose this?
16017 if (!VI)
16018 return ExprResult((Expr*)nullptr);
16019 ExprResult ThisResult =
16021 if (ThisResult.isInvalid())
16022 return ExprError();
16023
16024 // Build a conditional unless this is the final case.
16025 if (Result.get()) {
16026 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16027 ThisResult.get(), Result.get());
16028 if (Result.isInvalid())
16029 return ExprError();
16030 } else {
16031 Result = ThisResult;
16032 }
16033 }
16034
16035 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16036 // bind the OpaqueValueExprs before they're (repeatedly) used.
16037 Expr *SyntacticForm = BinaryOperator::Create(
16038 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16039 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16041 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16042 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16043}
16044
16046 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16047 MultiExprArg Args, SourceLocation LParenLoc) {
16048
16049 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16050 unsigned NumParams = Proto->getNumParams();
16051 unsigned NumArgsSlots =
16052 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16053 // Build the full argument list for the method call (the implicit object
16054 // parameter is placed at the beginning of the list).
16055 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16056 bool IsError = false;
16057 // Initialize the implicit object parameter.
16058 // Check the argument types.
16059 for (unsigned i = 0; i != NumParams; i++) {
16060 Expr *Arg;
16061 if (i < Args.size()) {
16062 Arg = Args[i];
16063 ExprResult InputInit =
16065 S.Context, Method->getParamDecl(i)),
16066 SourceLocation(), Arg);
16067 IsError |= InputInit.isInvalid();
16068 Arg = InputInit.getAs<Expr>();
16069 } else {
16070 ExprResult DefArg =
16071 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16072 if (DefArg.isInvalid()) {
16073 IsError = true;
16074 break;
16075 }
16076 Arg = DefArg.getAs<Expr>();
16077 }
16078
16079 MethodArgs.push_back(Arg);
16080 }
16081 return IsError;
16082}
16083
16085 SourceLocation RLoc,
16086 Expr *Base,
16087 MultiExprArg ArgExpr) {
16089 Args.push_back(Base);
16090 for (auto *e : ArgExpr) {
16091 Args.push_back(e);
16092 }
16093 DeclarationName OpName =
16094 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16095
16096 SourceRange Range = ArgExpr.empty()
16097 ? SourceRange{}
16098 : SourceRange(ArgExpr.front()->getBeginLoc(),
16099 ArgExpr.back()->getEndLoc());
16100
16101 // If either side is type-dependent, create an appropriate dependent
16102 // expression.
16104
16105 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16106 // CHECKME: no 'operator' keyword?
16107 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16108 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16110 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16111 if (Fn.isInvalid())
16112 return ExprError();
16113 // Can't add any actual overloads yet
16114
16115 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16116 Context.DependentTy, VK_PRValue, RLoc,
16118 }
16119
16120 // Handle placeholders
16121 UnbridgedCastsSet UnbridgedCasts;
16122 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16123 return ExprError();
16124 }
16125 // Build an empty overload set.
16127
16128 // Subscript can only be overloaded as a member function.
16129
16130 // Add operator candidates that are member functions.
16131 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16132
16133 // Add builtin operator candidates.
16134 if (Args.size() == 2)
16135 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16136
16137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16138
16139 // Perform overload resolution.
16141 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16142 case OR_Success: {
16143 // We found a built-in operator or an overloaded operator.
16144 FunctionDecl *FnDecl = Best->Function;
16145
16146 if (FnDecl) {
16147 // We matched an overloaded operator. Build a call to that
16148 // operator.
16149
16150 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16151
16152 // Convert the arguments.
16154 SmallVector<Expr *, 2> MethodArgs;
16155
16156 // Initialize the object parameter.
16157 if (Method->isExplicitObjectMemberFunction()) {
16158 ExprResult Res =
16160 if (Res.isInvalid())
16161 return ExprError();
16162 Args[0] = Res.get();
16163 ArgExpr = Args;
16164 } else {
16166 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16167 if (Arg0.isInvalid())
16168 return ExprError();
16169
16170 MethodArgs.push_back(Arg0.get());
16171 }
16172
16174 *this, MethodArgs, Method, ArgExpr, LLoc);
16175 if (IsError)
16176 return ExprError();
16177
16178 // Build the actual expression node.
16179 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16180 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16182 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16183 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16184 if (FnExpr.isInvalid())
16185 return ExprError();
16186
16187 // Determine the result type
16188 QualType ResultTy = FnDecl->getReturnType();
16190 ResultTy = ResultTy.getNonLValueExprType(Context);
16191
16193 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16195
16196 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16197 return ExprError();
16198
16199 if (CheckFunctionCall(Method, TheCall,
16200 Method->getType()->castAs<FunctionProtoType>()))
16201 return ExprError();
16202
16204 FnDecl);
16205 } else {
16206 // We matched a built-in operator. Convert the arguments, then
16207 // break out so that we will build the appropriate built-in
16208 // operator node.
16210 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16213 if (ArgsRes0.isInvalid())
16214 return ExprError();
16215 Args[0] = ArgsRes0.get();
16216
16218 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16221 if (ArgsRes1.isInvalid())
16222 return ExprError();
16223 Args[1] = ArgsRes1.get();
16224
16225 break;
16226 }
16227 }
16228
16229 case OR_No_Viable_Function: {
16231 CandidateSet.empty()
16232 ? (PDiag(diag::err_ovl_no_oper)
16233 << Args[0]->getType() << /*subscript*/ 0
16234 << Args[0]->getSourceRange() << Range)
16235 : (PDiag(diag::err_ovl_no_viable_subscript)
16236 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16237 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16238 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16239 return ExprError();
16240 }
16241
16242 case OR_Ambiguous:
16243 if (Args.size() == 2) {
16244 CandidateSet.NoteCandidates(
16246 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16247 << "[]" << Args[0]->getType() << Args[1]->getType()
16248 << Args[0]->getSourceRange() << Range),
16249 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16250 } else {
16251 CandidateSet.NoteCandidates(
16253 PDiag(diag::err_ovl_ambiguous_subscript_call)
16254 << Args[0]->getType()
16255 << Args[0]->getSourceRange() << Range),
16256 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16257 }
16258 return ExprError();
16259
16260 case OR_Deleted: {
16261 StringLiteral *Msg = Best->Function->getDeletedMessage();
16262 CandidateSet.NoteCandidates(
16264 PDiag(diag::err_ovl_deleted_oper)
16265 << "[]" << (Msg != nullptr)
16266 << (Msg ? Msg->getString() : StringRef())
16267 << Args[0]->getSourceRange() << Range),
16268 *this, OCD_AllCandidates, Args, "[]", LLoc);
16269 return ExprError();
16270 }
16271 }
16272
16273 // We matched a built-in operator; build it.
16274 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16275}
16276
16278 SourceLocation LParenLoc,
16279 MultiExprArg Args,
16280 SourceLocation RParenLoc,
16281 Expr *ExecConfig, bool IsExecConfig,
16282 bool AllowRecovery) {
16283 assert(MemExprE->getType() == Context.BoundMemberTy ||
16284 MemExprE->getType() == Context.OverloadTy);
16285
16286 // Dig out the member expression. This holds both the object
16287 // argument and the member function we're referring to.
16288 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16289
16290 // Determine whether this is a call to a pointer-to-member function.
16291 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16292 assert(op->getType() == Context.BoundMemberTy);
16293 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16294
16295 QualType fnType =
16296 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16297
16298 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16299 QualType resultType = proto->getCallResultType(Context);
16301
16302 // Check that the object type isn't more qualified than the
16303 // member function we're calling.
16304 Qualifiers funcQuals = proto->getMethodQuals();
16305
16306 QualType objectType = op->getLHS()->getType();
16307 if (op->getOpcode() == BO_PtrMemI)
16308 objectType = objectType->castAs<PointerType>()->getPointeeType();
16309 Qualifiers objectQuals = objectType.getQualifiers();
16310
16311 Qualifiers difference = objectQuals - funcQuals;
16312 difference.removeObjCGCAttr();
16313 difference.removeAddressSpace();
16314 if (difference) {
16315 std::string qualsString = difference.getAsString();
16316 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16317 << fnType.getUnqualifiedType()
16318 << qualsString
16319 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16320 }
16321
16323 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16325
16326 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16327 call, nullptr))
16328 return ExprError();
16329
16330 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16331 return ExprError();
16332
16333 if (CheckOtherCall(call, proto))
16334 return ExprError();
16335
16336 return MaybeBindToTemporary(call);
16337 }
16338
16339 // We only try to build a recovery expr at this level if we can preserve
16340 // the return type, otherwise we return ExprError() and let the caller
16341 // recover.
16342 auto BuildRecoveryExpr = [&](QualType Type) {
16343 if (!AllowRecovery)
16344 return ExprError();
16345 std::vector<Expr *> SubExprs = {MemExprE};
16346 llvm::append_range(SubExprs, Args);
16347 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16348 Type);
16349 };
16350 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16351 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16352 RParenLoc, CurFPFeatureOverrides());
16353
16354 UnbridgedCastsSet UnbridgedCasts;
16355 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16356 return ExprError();
16357
16358 MemberExpr *MemExpr;
16359 CXXMethodDecl *Method = nullptr;
16360 bool HadMultipleCandidates = false;
16361 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16362 NestedNameSpecifier Qualifier = std::nullopt;
16363 if (isa<MemberExpr>(NakedMemExpr)) {
16364 MemExpr = cast<MemberExpr>(NakedMemExpr);
16366 FoundDecl = MemExpr->getFoundDecl();
16367 Qualifier = MemExpr->getQualifier();
16368 UnbridgedCasts.restore();
16369 } else {
16370 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16371 Qualifier = UnresExpr->getQualifier();
16372
16373 QualType ObjectType = UnresExpr->getBaseType();
16374 Expr::Classification ObjectClassification
16376 : UnresExpr->getBase()->Classify(Context);
16377
16378 // Add overload candidates
16379 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16381
16382 // FIXME: avoid copy.
16383 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16384 if (UnresExpr->hasExplicitTemplateArgs()) {
16385 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16386 TemplateArgs = &TemplateArgsBuffer;
16387 }
16388
16390 E = UnresExpr->decls_end(); I != E; ++I) {
16391
16392 QualType ExplicitObjectType = ObjectType;
16393
16394 NamedDecl *Func = *I;
16395 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16397 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16398
16399 bool HasExplicitParameter = false;
16400 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16401 M && M->hasCXXExplicitFunctionObjectParameter())
16402 HasExplicitParameter = true;
16403 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16404 M &&
16405 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16406 HasExplicitParameter = true;
16407
16408 if (HasExplicitParameter)
16409 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16410
16411 // Microsoft supports direct constructor calls.
16412 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16414 CandidateSet,
16415 /*SuppressUserConversions*/ false);
16416 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16417 // If explicit template arguments were provided, we can't call a
16418 // non-template member function.
16419 if (TemplateArgs)
16420 continue;
16421
16422 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16423 ObjectClassification, Args, CandidateSet,
16424 /*SuppressUserConversions=*/false);
16425 } else {
16427 I.getPair(), ActingDC, TemplateArgs,
16428 ExplicitObjectType, ObjectClassification,
16429 Args, CandidateSet,
16430 /*SuppressUserConversions=*/false);
16431 }
16432 }
16433
16434 HadMultipleCandidates = (CandidateSet.size() > 1);
16435
16436 DeclarationName DeclName = UnresExpr->getMemberName();
16437
16438 UnbridgedCasts.restore();
16439
16441 bool Succeeded = false;
16442 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16443 Best)) {
16444 case OR_Success:
16445 Method = cast<CXXMethodDecl>(Best->Function);
16446 FoundDecl = Best->FoundDecl;
16447 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16448 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16449 break;
16450 // If FoundDecl is different from Method (such as if one is a template
16451 // and the other a specialization), make sure DiagnoseUseOfDecl is
16452 // called on both.
16453 // FIXME: This would be more comprehensively addressed by modifying
16454 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16455 // being used.
16456 if (Method != FoundDecl.getDecl() &&
16458 break;
16459 Succeeded = true;
16460 break;
16461
16463 CandidateSet.NoteCandidates(
16465 UnresExpr->getMemberLoc(),
16466 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16467 << DeclName << MemExprE->getSourceRange()),
16468 *this, OCD_AllCandidates, Args);
16469 break;
16470 case OR_Ambiguous:
16471 CandidateSet.NoteCandidates(
16472 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16473 PDiag(diag::err_ovl_ambiguous_member_call)
16474 << DeclName << MemExprE->getSourceRange()),
16475 *this, OCD_AmbiguousCandidates, Args);
16476 break;
16477 case OR_Deleted:
16479 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16480 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16481 break;
16482 }
16483 // Overload resolution fails, try to recover.
16484 if (!Succeeded)
16485 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16486
16487 ExprResult Res =
16488 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16489 if (Res.isInvalid())
16490 return ExprError();
16491 MemExprE = Res.get();
16492
16493 // If overload resolution picked a static member
16494 // build a non-member call based on that function.
16495 if (Method->isStatic()) {
16496 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16497 ExecConfig, IsExecConfig);
16498 }
16499
16500 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16501 }
16502
16503 QualType ResultType = Method->getReturnType();
16505 ResultType = ResultType.getNonLValueExprType(Context);
16506
16507 assert(Method && "Member call to something that isn't a method?");
16508 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16509
16510 CallExpr *TheCall = nullptr;
16512 if (Method->isExplicitObjectMemberFunction()) {
16513 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16514 NewArgs))
16515 return ExprError();
16516
16517 // Build the actual expression node.
16518 ExprResult FnExpr =
16519 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16520 HadMultipleCandidates, MemExpr->getExprLoc());
16521 if (FnExpr.isInvalid())
16522 return ExprError();
16523
16524 TheCall =
16525 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16526 CurFPFeatureOverrides(), Proto->getNumParams());
16527 TheCall->setUsesMemberSyntax(true);
16528 } else {
16529 // Convert the object argument (for a non-static member function call).
16531 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16532 if (ObjectArg.isInvalid())
16533 return ExprError();
16534 MemExpr->setBase(ObjectArg.get());
16535 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16536 RParenLoc, CurFPFeatureOverrides(),
16537 Proto->getNumParams());
16538 }
16539
16540 // Check for a valid return type.
16541 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16542 TheCall, Method))
16543 return BuildRecoveryExpr(ResultType);
16544
16545 // Convert the rest of the arguments
16546 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16547 RParenLoc))
16548 return BuildRecoveryExpr(ResultType);
16549
16550 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16551
16552 if (CheckFunctionCall(Method, TheCall, Proto))
16553 return ExprError();
16554
16555 // In the case the method to call was not selected by the overloading
16556 // resolution process, we still need to handle the enable_if attribute. Do
16557 // that here, so it will not hide previous -- and more relevant -- errors.
16558 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16559 if (const EnableIfAttr *Attr =
16560 CheckEnableIf(Method, LParenLoc, Args, true)) {
16561 Diag(MemE->getMemberLoc(),
16562 diag::err_ovl_no_viable_member_function_in_call)
16563 << Method << Method->getSourceRange();
16564 Diag(Method->getLocation(),
16565 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16566 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16567 return ExprError();
16568 }
16569 }
16570
16572 TheCall->getDirectCallee()->isPureVirtual()) {
16573 const FunctionDecl *MD = TheCall->getDirectCallee();
16574
16575 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16577 Diag(MemExpr->getBeginLoc(),
16578 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16580 << MD->getParent();
16581
16582 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16583 if (getLangOpts().AppleKext)
16584 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16585 << MD->getParent() << MD->getDeclName();
16586 }
16587 }
16588
16589 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16590 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16591 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16592 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16593 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16594 MemExpr->getMemberLoc());
16595 }
16596
16598 TheCall->getDirectCallee());
16599}
16600
16603 SourceLocation LParenLoc,
16604 MultiExprArg Args,
16605 SourceLocation RParenLoc) {
16606 if (checkPlaceholderForOverload(*this, Obj))
16607 return ExprError();
16608 ExprResult Object = Obj;
16609
16610 UnbridgedCastsSet UnbridgedCasts;
16611 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16612 return ExprError();
16613
16614 assert(Object.get()->getType()->isRecordType() &&
16615 "Requires object type argument");
16616
16617 // C++ [over.call.object]p1:
16618 // If the primary-expression E in the function call syntax
16619 // evaluates to a class object of type "cv T", then the set of
16620 // candidate functions includes at least the function call
16621 // operators of T. The function call operators of T are obtained by
16622 // ordinary lookup of the name operator() in the context of
16623 // (E).operator().
16624 OverloadCandidateSet CandidateSet(LParenLoc,
16626 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16627
16628 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16629 diag::err_incomplete_object_call, Object.get()))
16630 return true;
16631
16632 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16633 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16635 R.suppressAccessDiagnostics();
16636
16637 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16638 Oper != OperEnd; ++Oper) {
16639 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16640 Object.get()->Classify(Context), Args, CandidateSet,
16641 /*SuppressUserConversion=*/false);
16642 }
16643
16644 // When calling a lambda, both the call operator, and
16645 // the conversion operator to function pointer
16646 // are considered. But when constraint checking
16647 // on the call operator fails, it will also fail on the
16648 // conversion operator as the constraints are always the same.
16649 // As the user probably does not intend to perform a surrogate call,
16650 // we filter them out to produce better error diagnostics, ie to avoid
16651 // showing 2 failed overloads instead of one.
16652 bool IgnoreSurrogateFunctions = false;
16653 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16654 const OverloadCandidate &Candidate = *CandidateSet.begin();
16655 if (!Candidate.Viable &&
16657 IgnoreSurrogateFunctions = true;
16658 }
16659
16660 // C++ [over.call.object]p2:
16661 // In addition, for each (non-explicit in C++0x) conversion function
16662 // declared in T of the form
16663 //
16664 // operator conversion-type-id () cv-qualifier;
16665 //
16666 // where cv-qualifier is the same cv-qualification as, or a
16667 // greater cv-qualification than, cv, and where conversion-type-id
16668 // denotes the type "pointer to function of (P1,...,Pn) returning
16669 // R", or the type "reference to pointer to function of
16670 // (P1,...,Pn) returning R", or the type "reference to function
16671 // of (P1,...,Pn) returning R", a surrogate call function [...]
16672 // is also considered as a candidate function. Similarly,
16673 // surrogate call functions are added to the set of candidate
16674 // functions for each conversion function declared in an
16675 // accessible base class provided the function is not hidden
16676 // within T by another intervening declaration.
16677 const auto &Conversions = Record->getVisibleConversionFunctions();
16678 for (auto I = Conversions.begin(), E = Conversions.end();
16679 !IgnoreSurrogateFunctions && I != E; ++I) {
16680 NamedDecl *D = *I;
16681 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16682 if (isa<UsingShadowDecl>(D))
16683 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16684
16685 // Skip over templated conversion functions; they aren't
16686 // surrogates.
16688 continue;
16689
16691 if (!Conv->isExplicit()) {
16692 // Strip the reference type (if any) and then the pointer type (if
16693 // any) to get down to what might be a function type.
16694 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16695 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16696 ConvType = ConvPtrType->getPointeeType();
16697
16698 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16699 {
16700 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16701 Object.get(), Args, CandidateSet);
16702 }
16703 }
16704 }
16705
16706 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16707
16708 // Perform overload resolution.
16710 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16711 Best)) {
16712 case OR_Success:
16713 // Overload resolution succeeded; we'll build the appropriate call
16714 // below.
16715 break;
16716
16717 case OR_No_Viable_Function: {
16719 CandidateSet.empty()
16720 ? (PDiag(diag::err_ovl_no_oper)
16721 << Object.get()->getType() << /*call*/ 1
16722 << Object.get()->getSourceRange())
16723 : (PDiag(diag::err_ovl_no_viable_object_call)
16724 << Object.get()->getType() << Object.get()->getSourceRange());
16725 CandidateSet.NoteCandidates(
16726 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16727 OCD_AllCandidates, Args);
16728 break;
16729 }
16730 case OR_Ambiguous:
16731 if (!R.isAmbiguous())
16732 CandidateSet.NoteCandidates(
16733 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16734 PDiag(diag::err_ovl_ambiguous_object_call)
16735 << Object.get()->getType()
16736 << Object.get()->getSourceRange()),
16737 *this, OCD_AmbiguousCandidates, Args);
16738 break;
16739
16740 case OR_Deleted: {
16741 // FIXME: Is this diagnostic here really necessary? It seems that
16742 // 1. we don't have any tests for this diagnostic, and
16743 // 2. we already issue err_deleted_function_use for this later on anyway.
16744 StringLiteral *Msg = Best->Function->getDeletedMessage();
16745 CandidateSet.NoteCandidates(
16746 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16747 PDiag(diag::err_ovl_deleted_object_call)
16748 << Object.get()->getType() << (Msg != nullptr)
16749 << (Msg ? Msg->getString() : StringRef())
16750 << Object.get()->getSourceRange()),
16751 *this, OCD_AllCandidates, Args);
16752 break;
16753 }
16754 }
16755
16756 if (Best == CandidateSet.end())
16757 return true;
16758
16759 UnbridgedCasts.restore();
16760
16761 if (Best->Function == nullptr) {
16762 // Since there is no function declaration, this is one of the
16763 // surrogate candidates. Dig out the conversion function.
16764 CXXConversionDecl *Conv
16766 Best->Conversions[0].UserDefined.ConversionFunction);
16767
16768 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16769 Best->FoundDecl);
16770 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16771 return ExprError();
16772 assert(Conv == Best->FoundDecl.getDecl() &&
16773 "Found Decl & conversion-to-functionptr should be same, right?!");
16774 // We selected one of the surrogate functions that converts the
16775 // object parameter to a function pointer. Perform the conversion
16776 // on the object argument, then let BuildCallExpr finish the job.
16777
16778 // Create an implicit member expr to refer to the conversion operator.
16779 // and then call it.
16780 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16781 Conv, HadMultipleCandidates);
16782 if (Call.isInvalid())
16783 return ExprError();
16784 // Record usage of conversion in an implicit cast.
16786 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16787 nullptr, VK_PRValue, CurFPFeatureOverrides());
16788
16789 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16790 }
16791
16792 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16793
16794 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16795 // that calls this method, using Object for the implicit object
16796 // parameter and passing along the remaining arguments.
16797 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16798
16799 // An error diagnostic has already been printed when parsing the declaration.
16800 if (Method->isInvalidDecl())
16801 return ExprError();
16802
16803 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16804 unsigned NumParams = Proto->getNumParams();
16805
16806 DeclarationNameInfo OpLocInfo(
16807 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16808 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16809 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16810 Obj, HadMultipleCandidates,
16811 OpLocInfo.getLoc(),
16812 OpLocInfo.getInfo());
16813 if (NewFn.isInvalid())
16814 return true;
16815
16816 SmallVector<Expr *, 8> MethodArgs;
16817 MethodArgs.reserve(NumParams + 1);
16818
16819 bool IsError = false;
16820
16821 // Initialize the object parameter.
16823 if (Method->isExplicitObjectMemberFunction()) {
16824 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16825 } else {
16827 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16828 if (ObjRes.isInvalid())
16829 IsError = true;
16830 else
16831 Object = ObjRes;
16832 MethodArgs.push_back(Object.get());
16833 }
16834
16836 *this, MethodArgs, Method, Args, LParenLoc);
16837
16838 // If this is a variadic call, handle args passed through "...".
16839 if (Proto->isVariadic()) {
16840 // Promote the arguments (C99 6.5.2.2p7).
16841 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16843 Args[i], VariadicCallType::Method, nullptr);
16844 IsError |= Arg.isInvalid();
16845 MethodArgs.push_back(Arg.get());
16846 }
16847 }
16848
16849 if (IsError)
16850 return true;
16851
16852 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16853
16854 // Once we've built TheCall, all of the expressions are properly owned.
16855 QualType ResultTy = Method->getReturnType();
16857 ResultTy = ResultTy.getNonLValueExprType(Context);
16858
16860 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16862
16863 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16864 return true;
16865
16866 if (CheckFunctionCall(Method, TheCall, Proto))
16867 return true;
16868
16870}
16871
16873 SourceLocation OpLoc,
16874 bool *NoArrowOperatorFound) {
16875 assert(Base->getType()->isRecordType() &&
16876 "left-hand side must have class type");
16877
16879 return ExprError();
16880
16881 SourceLocation Loc = Base->getExprLoc();
16882
16883 // C++ [over.ref]p1:
16884 //
16885 // [...] An expression x->m is interpreted as (x.operator->())->m
16886 // for a class object x of type T if T::operator->() exists and if
16887 // the operator is selected as the best match function by the
16888 // overload resolution mechanism (13.3).
16889 DeclarationName OpName =
16890 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16892
16893 if (RequireCompleteType(Loc, Base->getType(),
16894 diag::err_typecheck_incomplete_tag, Base))
16895 return ExprError();
16896
16897 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16898 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16899 R.suppressAccessDiagnostics();
16900
16901 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16902 Oper != OperEnd; ++Oper) {
16903 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16904 {}, CandidateSet,
16905 /*SuppressUserConversion=*/false);
16906 }
16907
16908 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16909
16910 // Perform overload resolution.
16912 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16913 case OR_Success:
16914 // Overload resolution succeeded; we'll build the call below.
16915 break;
16916
16917 case OR_No_Viable_Function: {
16918 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16919 if (CandidateSet.empty()) {
16920 QualType BaseType = Base->getType();
16921 if (NoArrowOperatorFound) {
16922 // Report this specific error to the caller instead of emitting a
16923 // diagnostic, as requested.
16924 *NoArrowOperatorFound = true;
16925 return ExprError();
16926 }
16927 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16928 << BaseType << Base->getSourceRange();
16929 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16930 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16931 << FixItHint::CreateReplacement(OpLoc, ".");
16932 }
16933 } else
16934 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16935 << "operator->" << Base->getSourceRange();
16936 CandidateSet.NoteCandidates(*this, Base, Cands);
16937 return ExprError();
16938 }
16939 case OR_Ambiguous:
16940 if (!R.isAmbiguous())
16941 CandidateSet.NoteCandidates(
16942 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16943 << "->" << Base->getType()
16944 << Base->getSourceRange()),
16946 return ExprError();
16947
16948 case OR_Deleted: {
16949 StringLiteral *Msg = Best->Function->getDeletedMessage();
16950 CandidateSet.NoteCandidates(
16951 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16952 << "->" << (Msg != nullptr)
16953 << (Msg ? Msg->getString() : StringRef())
16954 << Base->getSourceRange()),
16955 *this, OCD_AllCandidates, Base);
16956 return ExprError();
16957 }
16958 }
16959
16960 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16961
16962 // Convert the object parameter.
16963 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16964
16965 if (Method->isExplicitObjectMemberFunction()) {
16967 if (R.isInvalid())
16968 return ExprError();
16969 Base = R.get();
16970 } else {
16972 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16973 if (BaseResult.isInvalid())
16974 return ExprError();
16975 Base = BaseResult.get();
16976 }
16977
16978 // Build the operator call.
16979 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16980 Base, HadMultipleCandidates, OpLoc);
16981 if (FnExpr.isInvalid())
16982 return ExprError();
16983
16984 QualType ResultTy = Method->getReturnType();
16986 ResultTy = ResultTy.getNonLValueExprType(Context);
16987
16988 CallExpr *TheCall =
16989 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16990 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16991
16992 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16993 return ExprError();
16994
16995 if (CheckFunctionCall(Method, TheCall,
16996 Method->getType()->castAs<FunctionProtoType>()))
16997 return ExprError();
16998
17000}
17001
17003 DeclarationNameInfo &SuffixInfo,
17004 ArrayRef<Expr*> Args,
17005 SourceLocation LitEndLoc,
17006 TemplateArgumentListInfo *TemplateArgs) {
17007 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17008
17009 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17011 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17012 TemplateArgs);
17013
17014 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17015
17016 // Perform overload resolution. This will usually be trivial, but might need
17017 // to perform substitutions for a literal operator template.
17019 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17020 case OR_Success:
17021 case OR_Deleted:
17022 break;
17023
17025 CandidateSet.NoteCandidates(
17026 PartialDiagnosticAt(UDSuffixLoc,
17027 PDiag(diag::err_ovl_no_viable_function_in_call)
17028 << R.getLookupName()),
17029 *this, OCD_AllCandidates, Args);
17030 return ExprError();
17031
17032 case OR_Ambiguous:
17033 CandidateSet.NoteCandidates(
17034 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17035 << R.getLookupName()),
17036 *this, OCD_AmbiguousCandidates, Args);
17037 return ExprError();
17038 }
17039
17040 FunctionDecl *FD = Best->Function;
17041 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17042 nullptr, HadMultipleCandidates,
17043 SuffixInfo.getLoc(),
17044 SuffixInfo.getInfo());
17045 if (Fn.isInvalid())
17046 return true;
17047
17048 // Check the argument types. This should almost always be a no-op, except
17049 // that array-to-pointer decay is applied to string literals.
17050 Expr *ConvArgs[2];
17051 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17054 SourceLocation(), Args[ArgIdx]);
17055 if (InputInit.isInvalid())
17056 return true;
17057 ConvArgs[ArgIdx] = InputInit.get();
17058 }
17059
17060 QualType ResultTy = FD->getReturnType();
17062 ResultTy = ResultTy.getNonLValueExprType(Context);
17063
17065 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17066 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17067
17068 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17069 return ExprError();
17070
17071 if (CheckFunctionCall(FD, UDL, nullptr))
17072 return ExprError();
17073
17075}
17076
17079 SourceLocation RangeLoc,
17080 const DeclarationNameInfo &NameInfo,
17081 LookupResult &MemberLookup,
17082 OverloadCandidateSet *CandidateSet,
17083 Expr *Range, ExprResult *CallExpr) {
17084 Scope *S = nullptr;
17085
17087 if (!MemberLookup.empty()) {
17088 ExprResult MemberRef =
17089 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17090 /*IsPtr=*/false, CXXScopeSpec(),
17091 /*TemplateKWLoc=*/SourceLocation(),
17092 /*FirstQualifierInScope=*/nullptr,
17093 MemberLookup,
17094 /*TemplateArgs=*/nullptr, S);
17095 if (MemberRef.isInvalid()) {
17096 *CallExpr = ExprError();
17097 return FRS_DiagnosticIssued;
17098 }
17099 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17100 if (CallExpr->isInvalid()) {
17101 *CallExpr = ExprError();
17102 return FRS_DiagnosticIssued;
17103 }
17104 } else {
17105 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17107 NameInfo, UnresolvedSet<0>());
17108 if (FnR.isInvalid())
17109 return FRS_DiagnosticIssued;
17111
17112 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17113 CandidateSet, CallExpr);
17114 if (CandidateSet->empty() || CandidateSetError) {
17115 *CallExpr = ExprError();
17116 return FRS_NoViableFunction;
17117 }
17119 OverloadingResult OverloadResult =
17120 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17121
17122 if (OverloadResult == OR_No_Viable_Function) {
17123 *CallExpr = ExprError();
17124 return FRS_NoViableFunction;
17125 }
17126 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17127 Loc, nullptr, CandidateSet, &Best,
17128 OverloadResult,
17129 /*AllowTypoCorrection=*/false);
17130 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17131 *CallExpr = ExprError();
17132 return FRS_DiagnosticIssued;
17133 }
17134 }
17135 return FRS_Success;
17136}
17137
17139 FunctionDecl *Fn) {
17140 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17141 ExprResult SubExpr =
17142 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17143 if (SubExpr.isInvalid())
17144 return ExprError();
17145 if (SubExpr.get() == PE->getSubExpr())
17146 return PE;
17147
17148 return new (Context)
17149 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17150 }
17151
17152 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17153 ExprResult SubExpr =
17154 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17155 if (SubExpr.isInvalid())
17156 return ExprError();
17157 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17158 SubExpr.get()->getType()) &&
17159 "Implicit cast type cannot be determined from overload");
17160 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17161 if (SubExpr.get() == ICE->getSubExpr())
17162 return ICE;
17163
17164 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17165 SubExpr.get(), nullptr, ICE->getValueKind(),
17167 }
17168
17169 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17170 if (!GSE->isResultDependent()) {
17171 ExprResult SubExpr =
17172 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17173 if (SubExpr.isInvalid())
17174 return ExprError();
17175 if (SubExpr.get() == GSE->getResultExpr())
17176 return GSE;
17177
17178 // Replace the resulting type information before rebuilding the generic
17179 // selection expression.
17180 ArrayRef<Expr *> A = GSE->getAssocExprs();
17181 SmallVector<Expr *, 4> AssocExprs(A);
17182 unsigned ResultIdx = GSE->getResultIndex();
17183 AssocExprs[ResultIdx] = SubExpr.get();
17184
17185 if (GSE->isExprPredicate())
17187 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17188 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17189 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17190 ResultIdx);
17192 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17193 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17194 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17195 ResultIdx);
17196 }
17197 // Rather than fall through to the unreachable, return the original generic
17198 // selection expression.
17199 return GSE;
17200 }
17201
17202 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17203 assert(UnOp->getOpcode() == UO_AddrOf &&
17204 "Can only take the address of an overloaded function");
17205 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17206 if (!Method->isImplicitObjectMemberFunction()) {
17207 // Do nothing: the address of static and
17208 // explicit object member functions is a (non-member) function pointer.
17209 } else {
17210 // Fix the subexpression, which really has to be an
17211 // UnresolvedLookupExpr holding an overloaded member function
17212 // or template.
17213 ExprResult SubExpr =
17214 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17215 if (SubExpr.isInvalid())
17216 return ExprError();
17217 if (SubExpr.get() == UnOp->getSubExpr())
17218 return UnOp;
17219
17220 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17221 SubExpr.get(), Method))
17222 return ExprError();
17223
17224 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17225 "fixed to something other than a decl ref");
17226 NestedNameSpecifier Qualifier =
17227 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17228 assert(Qualifier &&
17229 "fixed to a member ref with no nested name qualifier");
17230
17231 // We have taken the address of a pointer to member
17232 // function. Perform the computation here so that we get the
17233 // appropriate pointer to member type.
17234 QualType MemPtrType = Context.getMemberPointerType(
17235 Fn->getType(), Qualifier,
17236 cast<CXXRecordDecl>(Method->getDeclContext()));
17237 // Under the MS ABI, lock down the inheritance model now.
17238 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17239 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17240
17241 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17242 MemPtrType, VK_PRValue, OK_Ordinary,
17243 UnOp->getOperatorLoc(), false,
17245 }
17246 }
17247 ExprResult SubExpr =
17248 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17249 if (SubExpr.isInvalid())
17250 return ExprError();
17251 if (SubExpr.get() == UnOp->getSubExpr())
17252 return UnOp;
17253
17254 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17255 SubExpr.get());
17256 }
17257
17258 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17259 if (Found.getAccess() == AS_none) {
17261 }
17262 // FIXME: avoid copy.
17263 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17264 if (ULE->hasExplicitTemplateArgs()) {
17265 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17266 TemplateArgs = &TemplateArgsBuffer;
17267 }
17268
17269 QualType Type = Fn->getType();
17270 ExprValueKind ValueKind =
17271 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17272 ? VK_LValue
17273 : VK_PRValue;
17274
17275 // FIXME: Duplicated from BuildDeclarationNameExpr.
17276 if (unsigned BID = Fn->getBuiltinID()) {
17277 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17278 Type = Context.BuiltinFnTy;
17279 ValueKind = VK_PRValue;
17280 }
17281 }
17282
17284 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17285 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17286 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17287 return DRE;
17288 }
17289
17290 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17291 // FIXME: avoid copy.
17292 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17293 if (MemExpr->hasExplicitTemplateArgs()) {
17294 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17295 TemplateArgs = &TemplateArgsBuffer;
17296 }
17297
17298 Expr *Base;
17299
17300 // If we're filling in a static method where we used to have an
17301 // implicit member access, rewrite to a simple decl ref.
17302 if (MemExpr->isImplicitAccess()) {
17303 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17305 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17306 MemExpr->getQualifierLoc(), Found.getDecl(),
17307 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17308 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17309 return DRE;
17310 } else {
17311 SourceLocation Loc = MemExpr->getMemberLoc();
17312 if (MemExpr->getQualifier())
17313 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17314 Base =
17315 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17316 }
17317 } else
17318 Base = MemExpr->getBase();
17319
17320 ExprValueKind valueKind;
17321 QualType type;
17322 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17323 valueKind = VK_LValue;
17324 type = Fn->getType();
17325 } else {
17326 valueKind = VK_PRValue;
17327 type = Context.BoundMemberTy;
17328 }
17329
17330 return BuildMemberExpr(
17331 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17332 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17333 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17334 type, valueKind, OK_Ordinary, TemplateArgs);
17335 }
17336
17337 llvm_unreachable("Invalid reference to overloaded function");
17338}
17339
17345
17346bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17348 if (!PartialOverloading || !Function)
17349 return true;
17350 if (Function->isVariadic())
17351 return false;
17352 if (const auto *Proto =
17353 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17354 if (Proto->isTemplateVariadic())
17355 return false;
17356 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17357 if (const auto *Proto =
17358 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17359 if (Proto->isTemplateVariadic())
17360 return false;
17361 return true;
17362}
17363
17365 DeclarationName Name,
17366 OverloadCandidateSet &CandidateSet,
17367 FunctionDecl *Fn, MultiExprArg Args,
17368 bool IsMember) {
17369 StringLiteral *Msg = Fn->getDeletedMessage();
17370 CandidateSet.NoteCandidates(
17371 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17372 << IsMember << Name << (Msg != nullptr)
17373 << (Msg ? Msg->getString() : StringRef())
17374 << Range),
17375 *this, OCD_AllCandidates, Args);
17376}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:481
bool isFloat() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:974
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:806
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:959
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:922
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType Char8Ty
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3956
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:316
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8246
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2187
StringRef getOpcodeStr() const
Definition Expr.h:4110
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2140
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5104
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Pointer to a block type.
Definition TypeBase.h:3606
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3067
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3104
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2965
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2997
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3001
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:699
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2717
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2724
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2868
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:629
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1564
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3113
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3331
Represents a canonical, potentially-qualified type.
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isVolatileQualified() const
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5126
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1469
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:786
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:771
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:762
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:598
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4033
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4251
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4149
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1968
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1952
const Expr * getExpr() const
Definition DeclCXX.h:1953
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2368
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3348
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4238
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3182
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
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:104
Represents a function declaration or definition.
Definition Decl.h:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4169
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3738
param_iterator param_end()
Definition Decl.h:2805
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3642
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3841
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
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:4240
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4289
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3723
param_iterator param_begin()
Definition Decl.h:2804
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3109
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4305
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4233
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3845
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4106
bool isConsteval() const
Definition Decl.h:2500
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3686
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:2880
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:3691
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3802
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2703
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
unsigned getNumParams() const
Definition TypeBase.h:5649
Qualifiers getMethodQuals() const
Definition TypeBase.h:5797
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4606
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4935
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4725
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3859
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:770
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:827
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:681
bool hasInitializerListContainerType() const
Definition Overload.h:809
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:734
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:816
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:685
QualType getInitializerListContainerType() const
Definition Overload.h:819
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5305
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5421
unsigned getNumInits() const
Definition Expr.h:5338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2505
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2523
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
bool isCompatibleWithMSVC() const
Represents the results of name lookup.
Definition Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition Lookup.h:488
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition Lookup.h:643
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3559
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3481
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3467
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3588
Expr * getBase() const
Definition Expr.h:3447
void setBase(Expr *E)
Definition Expr.h:3446
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1800
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3457
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3749
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5642
QualType getPointeeType() const
Definition TypeBase.h:3735
Describes a module or submodule.
Definition Module.h:340
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp: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:1681
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8154
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8123
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8077
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8117
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8129
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition Overload.h:1360
bool shouldDeferTemplateArgumentDeduction(const Sema &S) const
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1458
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1392
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1350
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1185
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1190
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition Overload.h:1368
SourceLocation getLocation() const
Definition Overload.h:1348
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1349
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1383
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3132
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3284
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3248
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3245
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3223
decls_iterator decls_begin() const
Definition ExprCXX.h:3225
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3236
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3258
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3254
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3228
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3242
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1808
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3034
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5198
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8525
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3682
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1240
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8601
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8612
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8479
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8387
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8394
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4792
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4347
field_range fields() const
Definition Decl.h:4550
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4535
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition SemaARM.cpp:1516
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1561
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:459
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:396
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:406
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:308
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10409
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:6438
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6467
RAII class to control scope of DeferDiags.
Definition Sema.h:10132
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1386
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1421
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:12552
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12586
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
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:10150
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:9420
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9447
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9432
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
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:416
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
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:1473
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:10492
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10495
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10501
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10499
@ AR_dependent
Definition Sema.h:1688
@ AR_accessible
Definition Sema.h:1686
@ AR_inaccessible
Definition Sema.h:1687
@ AR_delayed
Definition Sema.h:1689
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:2077
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1308
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:686
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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:1518
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:760
ASTContext & getASTContext() const
Definition Sema.h:939
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
@ FRS_Success
Definition Sema.h:10880
@ FRS_DiagnosticIssued
Definition Sema.h:10882
@ FRS_NoViableFunction
Definition Sema.h:10881
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9413
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:10201
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:1212
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:3638
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:12250
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:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1306
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:1483
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9412
MemberPointerConversionDirection
Definition Sema.h:10333
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:10520
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
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:15616
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:7060
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:1446
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
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:14054
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:7557
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:13787
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:15571
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:125
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:6823
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6792
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:10325
SourceManager & SourceMgr
Definition Sema.h:1311
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1310
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
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:6500
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:1453
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:8748
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:362
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:339
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition Overload.h:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:367
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:329
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition Overload.h:384
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
StringRef getString() const
Definition Expr.h:1873
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:679
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3560
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isObjCBuiltinType() const
Definition TypeBase.h:8914
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2000
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isFloat16Type() const
Definition TypeBase.h:9059
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
bool isRValueReferenceType() const
Definition TypeBase.h:8716
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8787
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9217
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2193
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9122
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2422
bool isPointerType() const
Definition TypeBase.h:8684
bool isArrayParameterType() const
Definition TypeBase.h:8799
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2667
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8884
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2229
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8871
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2854
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isBitIntType() const
Definition TypeBase.h:8959
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2503
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isHalfType() const
Definition TypeBase.h:9054
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9032
bool isQueueT() const
Definition TypeBase.h:8940
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9200
bool isObjCIdType() const
Definition TypeBase.h:8896
bool isMatrixType() const
Definition TypeBase.h:8847
bool isOverflowBehaviorType() const
Definition TypeBase.h:8855
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8932
bool isBFloat16Type() const
Definition TypeBase.h:9071
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isVectorType() const
Definition TypeBase.h:8823
bool isObjCClassType() const
Definition TypeBase.h:8902
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9007
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2332
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1436
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5161
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1412
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:973
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:260
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:63
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:859
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:887
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:896
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:879
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:883
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition Overload.h:924
@ ovl_fail_too_few_arguments
Definition Overload.h:861
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:903
@ ovl_fail_too_many_arguments
Definition Overload.h:860
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:911
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:892
@ ovl_fail_bad_deduction
Definition Overload.h:863
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:907
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:916
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:900
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:868
@ Comparison
A comparison.
Definition Sema.h:667
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1800
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1048
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:310
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:522
ConversionSet::const_iterator const_iterator
Definition Overload.h:558
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:523
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:549
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:607
QualType getFromType() const
Definition Overload.h:606
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:640
Extra information about a function prototype.
Definition TypeBase.h:5456
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5461
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1195
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1217
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1244
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1206
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1208
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1234
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:998
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:989
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1063
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1037
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1002
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:979
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:947
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:943
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:938
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1010
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:959
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:973
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1028
unsigned getNumParams() const
Definition Overload.h:1076
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1006
unsigned TookAddressOfOverload
Definition Overload.h:992
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
DeductionFailureInfo DeductionFailure
Definition Overload.h:1022
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:951
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1033
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10612
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10619
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13284
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13330
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:477
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.