clang 24.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"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
57
59 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
66 Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
67 FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
68 bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo,
69 const TemplateArgumentListInfo *TemplateArgs) {
70 SourceLocation Loc = NameInfo.getLoc();
71
72 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
73 return ExprError();
74 // If FoundDecl is different from Fn (such as if one is a template
75 // and the other a specialization), make sure DiagnoseUseOfDecl is
76 // called on both.
77 // FIXME: This would be more comprehensively addressed by modifying
78 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
79 // being used.
80 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
81 return ExprError();
82 auto *DRE = DeclRefExpr::Create(S.Context, QualifierLoc, TemplateKWLoc, Fn,
83 /*RefersToEnclosingVariableOrCapture=*/false,
84 NameInfo, Fn->getType(), VK_LValue, FoundDecl,
85 TemplateArgs);
86 if (HadMultipleCandidates)
87 DRE->setHadMultipleCandidates(true);
88
90 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
91 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
92 S.ResolveExceptionSpec(Loc, FPT);
93 DRE->setType(Fn->getType());
94 }
95 }
96 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
97 CK_FunctionToPointerDecay);
98}
99
101 NamedDecl *FoundDecl, const Expr *Base,
102 bool HadMultipleCandidates,
103 const DeclarationNameInfo &NameInfo) {
104 return CreateFunctionRefExpr(S, /*QualifierLoc=*/{}, /*TemplateKWLoc=*/{}, Fn,
105 FoundDecl, Base, HadMultipleCandidates, NameInfo,
106 /*TemplateArgs=*/nullptr);
107}
108
110 NamedDecl *FoundDecl, const Expr *Base,
111 bool HadMultipleCandidates,
112 SourceLocation Loc) {
113 return CreateFunctionRefExpr(S, Fn, FoundDecl, Base, HadMultipleCandidates,
114 DeclarationNameInfo(Fn->getDeclName(), Loc));
115}
116
117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
118 bool InOverloadResolution,
120 bool CStyle,
121 bool AllowObjCWritebackConversion);
122
124 QualType &ToType,
125 bool InOverloadResolution,
127 bool CStyle);
129IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
131 OverloadCandidateSet& Conversions,
132 AllowedExplicit AllowExplicit,
133 bool AllowObjCConversionOnExplicit);
134
137 const StandardConversionSequence& SCS1,
138 const StandardConversionSequence& SCS2);
139
142 const StandardConversionSequence& SCS1,
143 const StandardConversionSequence& SCS2);
144
147 const StandardConversionSequence &SCS1,
148 const StandardConversionSequence &SCS2);
149
152 const StandardConversionSequence& SCS1,
153 const StandardConversionSequence& SCS2);
154
155/// GetConversionRank - Retrieve the implicit conversion rank
156/// corresponding to the given implicit conversion kind.
158 static const ImplicitConversionRank Rank[] = {
185 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
186 // it was omitted by the patch that added
187 // ICK_Zero_Event_Conversion
188 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
189 // it was omitted by the patch that added
190 // ICK_Zero_Queue_Conversion
200 };
201 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
202 return Rank[(int)Kind];
203}
204
223
224/// GetImplicitConversionName - Return the name of this kind of
225/// implicit conversion.
227 static const char *const Name[] = {
228 "No conversion",
229 "Lvalue-to-rvalue",
230 "Array-to-pointer",
231 "Function-to-pointer",
232 "Function pointer conversion",
233 "Qualification",
234 "Integral promotion",
235 "Floating point promotion",
236 "Complex promotion",
237 "Integral conversion",
238 "Floating conversion",
239 "Complex conversion",
240 "Floating-integral conversion",
241 "Pointer conversion",
242 "Pointer-to-member conversion",
243 "Boolean conversion",
244 "Compatible-types conversion",
245 "Derived-to-base conversion",
246 "Vector conversion",
247 "SVE Vector conversion",
248 "RVV Vector conversion",
249 "Vector splat",
250 "Complex-real conversion",
251 "Block Pointer conversion",
252 "Transparent Union Conversion",
253 "Writeback conversion",
254 "OpenCL Zero Event Conversion",
255 "OpenCL Zero Queue Conversion",
256 "C specific type conversion",
257 "Incompatible pointer conversion",
258 "Fixed point conversion",
259 "HLSL vector truncation",
260 "HLSL matrix truncation",
261 "Non-decaying array conversion",
262 "HLSL vector splat",
263 "HLSL matrix splat",
264 "HLSL packed type conversion",
265 };
266 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
267 return Name[Kind];
268}
269
270/// StandardConversionSequence - Set the standard conversion
271/// sequence to the identity conversion.
289
290/// getRank - Retrieve the rank of this standard conversion sequence
291/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
292/// implicit conversions.
305
306/// isPointerConversionToBool - Determines whether this conversion is
307/// a conversion of a pointer or pointer-to-member to bool. This is
308/// used as part of the ranking of standard conversion sequences
309/// (C++ 13.3.3.2p4).
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer or function-to-pointer implicit conversions, so
313 // check for their presence as well as checking whether FromType is
314 // a pointer.
315 if (getToType(1)->isBooleanType() &&
316 (getFromType()->isPointerType() ||
317 getFromType()->isMemberPointerType() ||
318 getFromType()->isObjCObjectPointerType() ||
319 getFromType()->isBlockPointerType() ||
321 return true;
322
323 return false;
324}
325
326/// isPointerConversionToVoidPointer - Determines whether this
327/// conversion is a conversion of a pointer to a void pointer. This is
328/// used as part of the ranking of standard conversion sequences (C++
329/// 13.3.3.2p4).
330bool
333 QualType FromType = getFromType();
334 QualType ToType = getToType(1);
335
336 // Note that FromType has not necessarily been transformed by the
337 // array-to-pointer implicit conversion, so check for its presence
338 // and redo the conversion to get a pointer.
340 FromType = Context.getArrayDecayedType(FromType);
341
342 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
343 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
344 return ToPtrType->getPointeeType()->isVoidType();
345
346 return false;
347}
348
349/// Skip any implicit casts which could be either part of a narrowing conversion
350/// or after one in an implicit conversion.
352 const Expr *Converted) {
353 // We can have cleanups wrapping the converted expression; these need to be
354 // preserved so that destructors run if necessary.
355 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
356 Expr *Inner =
357 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
358 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
359 EWC->getObjects());
360 }
361
362 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
363 switch (ICE->getCastKind()) {
364 case CK_NoOp:
365 case CK_IntegralCast:
366 case CK_IntegralToBoolean:
367 case CK_IntegralToFloating:
368 case CK_BooleanToSignedIntegral:
369 case CK_FloatingToIntegral:
370 case CK_FloatingToBoolean:
371 case CK_FloatingCast:
372 Converted = ICE->getSubExpr();
373 continue;
374
375 default:
376 return Converted;
377 }
378 }
379
380 return Converted;
381}
382
383/// Check if this standard conversion sequence represents a narrowing
384/// conversion, according to C++11 [dcl.init.list]p7.
385///
386/// \param Ctx The AST context.
387/// \param Converted The result of applying this standard conversion sequence.
388/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
389/// value of the expression prior to the narrowing conversion.
390/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
391/// type of the expression prior to the narrowing conversion.
392/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
393/// from floating point types to integral types should be ignored.
394/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
395/// to conform MSVC compiler behavior.
397 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
398 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
399 bool AllowRelaxedEval) const {
400 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
401 "narrowing check outside C++");
402
403 // C++11 [dcl.init.list]p7:
404 // A narrowing conversion is an implicit conversion ...
405 QualType FromType = getToType(0);
406 QualType ToType = getToType(1);
407
408 // A conversion to an enumeration type is narrowing if the conversion to
409 // the underlying type is narrowing. This only arises for expressions of
410 // the form 'Enum{init}'.
411 if (const auto *ED = ToType->getAsEnumDecl())
412 ToType = ED->getIntegerType();
413
414 switch (Second) {
415 // 'bool' is an integral type; dispatch to the right place to handle it.
417 if (FromType->isRealFloatingType())
418 goto FloatingIntegralConversion;
420 goto IntegralConversion;
421 // -- from a pointer type or pointer-to-member type to bool, or
422 return NK_Type_Narrowing;
423
424 // -- from a floating-point type to an integer type, or
425 //
426 // -- from an integer type or unscoped enumeration type to a floating-point
427 // type, except where the source is a constant expression and the actual
428 // value after conversion will fit into the target type and will produce
429 // the original value when converted back to the original type, or
431 FloatingIntegralConversion:
432 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
433 return NK_Type_Narrowing;
434 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
435 ToType->isRealFloatingType()) {
436 if (IgnoreFloatToIntegralConversion)
437 return NK_Not_Narrowing;
438 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439 assert(Initializer && "Unknown conversion expression");
440
441 // If it's value-dependent, we can't tell whether it's narrowing.
442 if (Initializer->isValueDependent())
444
445 if (std::optional<llvm::APSInt> IntConstantValue =
446 Initializer->getIntegerConstantExpr(Ctx)) {
447 // Convert the integer to the floating type.
448 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
449 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
450 llvm::APFloat::rmNearestTiesToEven);
451 // And back.
452 llvm::APSInt ConvertedValue = *IntConstantValue;
453 bool ignored;
454 llvm::APFloat::opStatus Status = Result.convertToInteger(
455 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
456 // If the converted-back integer has unspecified value, or if the
457 // resulting value is different, this was a narrowing conversion.
458 if (Status == llvm::APFloat::opInvalidOp ||
459 *IntConstantValue != ConvertedValue) {
460 ConstantValue = APValue(*IntConstantValue);
461 ConstantType = Initializer->getType();
463 }
464 } else {
465 // Variables are always narrowings.
467 }
468 }
469 return NK_Not_Narrowing;
470
471 // -- from long double to double or float, or from double to float, except
472 // where the source is a constant expression and the actual value after
473 // conversion is within the range of values that can be represented (even
474 // if it cannot be represented exactly), or
476 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
477 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
478 // FromType is larger than ToType.
479 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
480
481 // If it's value-dependent, we can't tell whether it's narrowing.
482 if (Initializer->isValueDependent())
484
486 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
487 ((Ctx.getLangOpts().CPlusPlus &&
488 Initializer->isCXX11ConstantExpr(Ctx, ConstantValue,
489 AllowRelaxedEval)))) {
490 // Constant!
491 if (Ctx.getLangOpts().C23)
492 ConstantValue = R.Val;
493 assert(ConstantValue.isFloat());
494 llvm::APFloat FloatVal = ConstantValue.getFloat();
495 // Convert the source value into the target type.
496 bool ignored;
497 llvm::APFloat Converted = FloatVal;
498 llvm::APFloat::opStatus ConvertStatus =
499 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
500 llvm::APFloat::rmNearestTiesToEven, &ignored);
501 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
502 llvm::APFloat::rmNearestTiesToEven, &ignored);
503 if (Ctx.getLangOpts().C23) {
504 if (FloatVal.isNaN() && Converted.isNaN() &&
505 !FloatVal.isSignaling() && !Converted.isSignaling()) {
506 // Quiet NaNs are considered the same value, regardless of
507 // payloads.
508 return NK_Not_Narrowing;
509 }
510 // For normal values, check exact equality.
511 if (!Converted.bitwiseIsEqual(FloatVal)) {
512 ConstantType = Initializer->getType();
514 }
515 } else {
516 // If there was no overflow, the source value is within the range of
517 // values that can be represented.
518 if (ConvertStatus & llvm::APFloat::opOverflow) {
519 ConstantType = Initializer->getType();
521 }
522 }
523 } else {
525 }
526 }
527 return NK_Not_Narrowing;
528
529 // -- from an integer type or unscoped enumeration type to an integer type
530 // that cannot represent all the values of the original type, except where
531 // (CWG2627) -- the source is a bit-field whose width w is less than that
532 // of its type (or, for an enumeration type, its underlying type) and the
533 // target type can represent all the values of a hypothetical extended
534 // integer type with width w and with the same signedness as the original
535 // type or
536 // -- the source is a constant expression and the actual value after
537 // conversion will fit into the target type and will produce the original
538 // value when converted back to the original type.
540 IntegralConversion: {
541 assert(FromType->isIntegralOrUnscopedEnumerationType());
542 assert(ToType->isIntegralOrUnscopedEnumerationType());
543 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
544 unsigned FromWidth = Ctx.getIntWidth(FromType);
545 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
546 const unsigned ToWidth = Ctx.getIntWidth(ToType);
547
548 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
549 bool ToSigned, unsigned ToWidth) {
550 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
551 !(FromSigned && !ToSigned);
552 };
553
554 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
555 return NK_Not_Narrowing;
556
557 // Not all values of FromType can be represented in ToType.
558 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
559
560 bool DependentBitField = false;
561 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
562 if (BitField->getBitWidth()->isValueDependent())
563 DependentBitField = true;
564 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
565 BitFieldWidth < FromWidth) {
566 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
567 return NK_Not_Narrowing;
568
569 // The initializer will be truncated to the bit-field width
570 FromWidth = BitFieldWidth;
571 }
572 }
573
574 // If it's value-dependent, we can't tell whether it's narrowing.
575 if (Initializer->isValueDependent())
577
578 std::optional<llvm::APSInt> OptInitializerValue =
579 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
580 if (!OptInitializerValue) {
581 // If the bit-field width was dependent, it might end up being small
582 // enough to fit in the target type (unless the target type is unsigned
583 // and the source type is signed, in which case it will never fit)
584 if (DependentBitField && !(FromSigned && !ToSigned))
586
587 // Otherwise, such a conversion is always narrowing
589 }
590 llvm::APSInt &InitializerValue = *OptInitializerValue;
591 bool Narrowing = false;
592 if (FromWidth < ToWidth) {
593 // Negative -> unsigned is narrowing. Otherwise, more bits is never
594 // narrowing.
595 if (InitializerValue.isSigned() && InitializerValue.isNegative())
596 Narrowing = true;
597 } else {
598 // Add a bit to the InitializerValue so we don't have to worry about
599 // signed vs. unsigned comparisons.
600 InitializerValue =
601 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
602 // Convert the initializer to and from the target width and signed-ness.
603 llvm::APSInt ConvertedValue = InitializerValue;
604 ConvertedValue = ConvertedValue.trunc(ToWidth);
605 ConvertedValue.setIsSigned(ToSigned);
606 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
607 ConvertedValue.setIsSigned(InitializerValue.isSigned());
608 // If the result is different, this was a narrowing conversion.
609 if (ConvertedValue != InitializerValue)
610 Narrowing = true;
611 }
612 if (Narrowing) {
613 ConstantType = Initializer->getType();
614 ConstantValue = APValue(InitializerValue);
616 }
617
618 return NK_Not_Narrowing;
619 }
620 case ICK_Complex_Real:
621 if (FromType->isComplexType() && !ToType->isComplexType())
622 return NK_Type_Narrowing;
623 return NK_Not_Narrowing;
624
626 if (Ctx.getLangOpts().C23) {
627 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
629 if (Initializer->EvaluateAsRValue(R, Ctx)) {
630 ConstantValue = R.Val;
631 assert(ConstantValue.isFloat());
632 llvm::APFloat FloatVal = ConstantValue.getFloat();
633 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
634 // value, the unqualified versions of the type of the initializer and
635 // the corresponding real type of the object declared shall be
636 // compatible.
637 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
638 ConstantType = Initializer->getType();
640 }
641 }
642 }
643 return NK_Not_Narrowing;
644 default:
645 // Other kinds of conversions are not narrowings.
646 return NK_Not_Narrowing;
647 }
648}
649
650/// dump - Print this standard conversion sequence to standard
651/// error. Useful for debugging overloading issues.
652LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
653 raw_ostream &OS = llvm::errs();
654 bool PrintedSomething = false;
655 if (First != ICK_Identity) {
657 PrintedSomething = true;
658 }
659
660 if (Second != ICK_Identity) {
661 if (PrintedSomething) {
662 OS << " -> ";
663 }
665
666 if (CopyConstructor) {
667 OS << " (by copy constructor)";
668 } else if (DirectBinding) {
669 OS << " (direct reference binding)";
670 } else if (ReferenceBinding) {
671 OS << " (reference binding)";
672 }
673 PrintedSomething = true;
674 }
675
676 if (Third != ICK_Identity) {
677 if (PrintedSomething) {
678 OS << " -> ";
679 }
681 PrintedSomething = true;
682 }
683
684 if (!PrintedSomething) {
685 OS << "No conversions required";
686 }
687}
688
689/// dump - Print this user-defined conversion sequence to standard
690/// error. Useful for debugging overloading issues.
692 raw_ostream &OS = llvm::errs();
693 if (Before.First || Before.Second || Before.Third) {
694 Before.dump();
695 OS << " -> ";
696 }
698 OS << '\'' << *ConversionFunction << '\'';
699 else
700 OS << "aggregate initialization";
701 if (After.First || After.Second || After.Third) {
702 OS << " -> ";
703 After.dump();
704 }
705}
706
707/// dump - Print this implicit conversion sequence to standard
708/// error. Useful for debugging overloading issues.
710 raw_ostream &OS = llvm::errs();
712 OS << "Worst list element conversion: ";
713 switch (ConversionKind) {
715 OS << "Standard conversion: ";
716 Standard.dump();
717 break;
719 OS << "User-defined conversion: ";
720 UserDefined.dump();
721 break;
723 OS << "Ellipsis conversion";
724 break;
726 OS << "Ambiguous conversion";
727 break;
728 case BadConversion:
729 OS << "Bad conversion";
730 break;
731 }
732
733 OS << "\n";
734}
735
739
741 conversions().~ConversionSet();
742}
743
744void
750
751namespace {
752 // Structure used by DeductionFailureInfo to store
753 // template argument information.
754 struct DFIArguments {
755 TemplateArgument FirstArg;
756 TemplateArgument SecondArg;
757 };
758 // Structure used by DeductionFailureInfo to store
759 // template parameter and template argument information.
760 struct DFIParamWithArguments : DFIArguments {
761 TemplateParameter Param;
762 };
763 // Structure used by DeductionFailureInfo to store template argument
764 // information and the index of the problematic call argument.
765 struct DFIDeducedMismatchArgs : DFIArguments {
766 TemplateArgumentList *TemplateArgs;
767 unsigned CallArgIndex;
768 };
769 // Structure used by DeductionFailureInfo to store information about
770 // unsatisfied constraints.
771 struct CNSInfo {
772 TemplateArgumentList *TemplateArgs;
773 ConstraintSatisfaction Satisfaction;
774 };
775}
776
777/// Convert from Sema's representation of template deduction information
778/// to the form used in overload-candidate information.
782 TemplateDeductionInfo &Info) {
784 Result.Result = static_cast<unsigned>(TDK);
785 Result.HasDiagnostic = false;
786 switch (TDK) {
793 Result.Data = nullptr;
794 break;
795
797 Result.Data = Info.Param.getOpaqueValue();
798 break;
800 Result.Data = Info.Param.getOpaqueValue();
801 if (Info.hasSFINAEDiagnostic()) {
805 Result.HasDiagnostic = true;
806 }
807 break;
808
811 // FIXME: Should allocate from normal heap so that we can free this later.
812 auto *Saved = new (Context) DFIDeducedMismatchArgs;
813 Saved->FirstArg = Info.FirstArg;
814 Saved->SecondArg = Info.SecondArg;
815 Saved->TemplateArgs = Info.takeSugared();
816 Saved->CallArgIndex = Info.CallArgIndex;
817 Result.Data = Saved;
818 break;
819 }
820
822 // FIXME: Should allocate from normal heap so that we can free this later.
823 DFIArguments *Saved = new (Context) DFIArguments;
824 Saved->FirstArg = Info.FirstArg;
825 Saved->SecondArg = Info.SecondArg;
826 Result.Data = Saved;
827 break;
828 }
829
831 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
834 // FIXME: Should allocate from normal heap so that we can free this later.
835 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
836 Saved->Param = Info.Param;
837 Saved->FirstArg = Info.FirstArg;
838 Saved->SecondArg = Info.SecondArg;
839 Result.Data = Saved;
840 break;
841 }
842
844 Result.Data = Info.takeSugared();
845 if (Info.hasSFINAEDiagnostic()) {
849 Result.HasDiagnostic = true;
850 }
851 break;
852
854 CNSInfo *Saved = new (Context) CNSInfo;
855 Saved->TemplateArgs = Info.takeSugared();
856 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
857 Result.Data = Saved;
858 break;
859 }
860
864 llvm_unreachable("not a deduction failure");
865 }
866
867 return Result;
868}
869
871 switch (static_cast<TemplateDeductionResult>(Result)) {
880 break;
881
888 // FIXME: Destroy the data?
889 Data = nullptr;
890 break;
891
894 // FIXME: Destroy the template argument list?
895 Data = nullptr;
897 Diag->~PartialDiagnosticAt();
898 HasDiagnostic = false;
899 }
900 break;
901
903 // FIXME: Destroy the template argument list?
904 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
905 Data = nullptr;
907 Diag->~PartialDiagnosticAt();
908 HasDiagnostic = false;
909 }
910 break;
911
912 // Unhandled
915 break;
916 }
917}
918
920 if (HasDiagnostic)
921 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
922 return nullptr;
923}
924
958
994
1026
1058
1060 switch (static_cast<TemplateDeductionResult>(Result)) {
1063 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1064
1065 default:
1066 return std::nullopt;
1067 }
1068}
1069
1071 const FunctionDecl *Y) {
1072 if (!X || !Y)
1073 return false;
1074 if (X->getNumParams() != Y->getNumParams())
1075 return false;
1076 // FIXME: when do rewritten comparison operators
1077 // with explicit object parameters correspond?
1078 // https://cplusplus.github.io/CWG/issues/2797.html
1079 for (unsigned I = 0; I < X->getNumParams(); ++I)
1080 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1081 Y->getParamDecl(I)->getType()))
1082 return false;
1083 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1084 auto *FTY = Y->getDescribedFunctionTemplate();
1085 if (!FTY)
1086 return false;
1087 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1088 FTY->getTemplateParameters()))
1089 return false;
1090 }
1091 return true;
1092}
1093
1095 Expr *FirstOperand, FunctionDecl *EqFD) {
1096 assert(EqFD->getOverloadedOperator() ==
1097 OverloadedOperatorKind::OO_EqualEqual);
1098 // C++2a [over.match.oper]p4:
1099 // A non-template function or function template F named operator== is a
1100 // rewrite target with first operand o unless a search for the name operator!=
1101 // in the scope S from the instantiation context of the operator expression
1102 // finds a function or function template that would correspond
1103 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1104 // scope of the class type of o if F is a class member, and the namespace
1105 // scope of which F is a member otherwise. A function template specialization
1106 // named operator== is a rewrite target if its function template is a rewrite
1107 // target.
1109 OverloadedOperatorKind::OO_ExclaimEqual);
1110 if (isa<CXXMethodDecl>(EqFD)) {
1111 // If F is a class member, search scope is class type of first operand.
1112 QualType RHS = FirstOperand->getType();
1113 auto *RHSRec = RHS->getAsCXXRecordDecl();
1114 if (!RHSRec)
1115 return true;
1116 LookupResult Members(S, NotEqOp, OpLoc,
1118 S.LookupQualifiedName(Members, RHSRec);
1119 Members.suppressAccessDiagnostics();
1120 for (NamedDecl *Op : Members)
1121 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1122 return false;
1123 return true;
1124 }
1125 // Otherwise the search scope is the namespace scope of which F is a member.
1126 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1127 auto *NotEqFD = Op->getAsFunction();
1128 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1129 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1130 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1132 cast<Decl>(Op->getLexicalDeclContext())))
1133 return false;
1134 }
1135 return true;
1136}
1137
1139 OverloadedOperatorKind Op) const {
1141 return false;
1142 return Op == OO_EqualEqual || Op == OO_Spaceship;
1143}
1144
1146 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1147 auto Op = FD->getOverloadedOperator();
1148 if (!allowsReversed(Op))
1149 return false;
1150 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1151 assert(OriginalArgs.size() == 2);
1153 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1154 return false;
1155 }
1156 // Don't bother adding a reversed candidate that can never be a better
1157 // match than the non-reversed version.
1158 return FD->getNumNonObjectParams() != 2 ||
1160 FD->getParamDecl(1)->getType()) ||
1161 FD->hasAttr<EnableIfAttr>();
1162}
1163
1164void OverloadCandidateSet::destroyCandidates() {
1165 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1166 for (auto &C : i->Conversions)
1167 C.~ImplicitConversionSequence();
1168 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1169 i->DeductionFailure.Destroy();
1170 }
1171}
1172
1174 destroyCandidates();
1175 SlabAllocator.Reset();
1176 NumInlineBytesUsed = 0;
1177 Candidates.clear();
1178 Functions.clear();
1179 Kind = CSK;
1180 FirstDeferredCandidate = nullptr;
1181 DeferredCandidatesCount = 0;
1182 HasDeferredTemplateConstructors = false;
1183 ResolutionByPerfectCandidateIsDisabled = false;
1184}
1185
1186namespace {
1187 class UnbridgedCastsSet {
1188 struct Entry {
1189 Expr **Addr;
1190 Expr *Saved;
1191 };
1192 SmallVector<Entry, 2> Entries;
1193
1194 public:
1195 void save(Sema &S, Expr *&E) {
1196 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1197 Entry entry = { &E, E };
1198 Entries.push_back(entry);
1199 E = S.ObjC().stripARCUnbridgedCast(E);
1200 }
1201
1202 void restore() {
1203 for (SmallVectorImpl<Entry>::iterator
1204 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1205 *i->Addr = i->Saved;
1206 }
1207 };
1208}
1209
1210/// checkPlaceholderForOverload - Do any interesting placeholder-like
1211/// preprocessing on the given expression.
1212///
1213/// \param unbridgedCasts a collection to which to add unbridged casts;
1214/// without this, they will be immediately diagnosed as errors
1215///
1216/// Return true on unrecoverable error.
1217static bool
1219 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1220 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1221 // We can't handle overloaded expressions here because overload
1222 // resolution might reasonably tweak them.
1223 if (placeholder->getKind() == BuiltinType::Overload) return false;
1224
1225 // If the context potentially accepts unbridged ARC casts, strip
1226 // the unbridged cast and add it to the collection for later restoration.
1227 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1228 unbridgedCasts) {
1229 unbridgedCasts->save(S, E);
1230 return false;
1231 }
1232
1233 // Go ahead and check everything else.
1234 ExprResult result = S.CheckPlaceholderExpr(E);
1235 if (result.isInvalid())
1236 return true;
1237
1238 E = result.get();
1239 return false;
1240 }
1241
1242 // Nothing to do.
1243 return false;
1244}
1245
1246/// checkArgPlaceholdersForOverload - Check a set of call operands for
1247/// placeholders.
1249 UnbridgedCastsSet &unbridged) {
1250 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1251 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1252 return true;
1253
1254 return false;
1255}
1256
1258 const LookupResult &Old, NamedDecl *&Match,
1259 bool NewIsUsingDecl) {
1260 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1261 I != E; ++I) {
1262 NamedDecl *OldD = *I;
1263
1264 bool OldIsUsingDecl = false;
1265 if (isa<UsingShadowDecl>(OldD)) {
1266 OldIsUsingDecl = true;
1267
1268 // We can always introduce two using declarations into the same
1269 // context, even if they have identical signatures.
1270 if (NewIsUsingDecl) continue;
1271
1272 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1273 }
1274
1275 // A using-declaration does not conflict with another declaration
1276 // if one of them is hidden.
1277 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1278 continue;
1279
1280 // If either declaration was introduced by a using declaration,
1281 // we'll need to use slightly different rules for matching.
1282 // Essentially, these rules are the normal rules, except that
1283 // function templates hide function templates with different
1284 // return types or template parameter lists.
1285 bool UseMemberUsingDeclRules =
1286 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1287 !New->getFriendObjectKind();
1288
1289 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1290 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1291 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1293 continue;
1294 }
1295
1296 if (!isa<FunctionTemplateDecl>(OldD) &&
1297 !shouldLinkPossiblyHiddenDecl(*I, New))
1298 continue;
1299
1300 Match = *I;
1301 return OverloadKind::Match;
1302 }
1303
1304 // Builtins that have custom typechecking or have a reference should
1305 // not be overloadable or redeclarable.
1306 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1307 Match = *I;
1309 }
1310 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1311 // We can overload with these, which can show up when doing
1312 // redeclaration checks for UsingDecls.
1313 assert(Old.getLookupKind() == LookupUsingDeclName);
1314 } else if (isa<TagDecl>(OldD)) {
1315 // We can always overload with tags by hiding them.
1316 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1317 // Optimistically assume that an unresolved using decl will
1318 // overload; if it doesn't, we'll have to diagnose during
1319 // template instantiation.
1320 //
1321 // Exception: if the scope is dependent and this is not a class
1322 // member, the using declaration can only introduce an enumerator.
1323 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1324 Match = *I;
1326 }
1327 } else {
1328 // (C++ 13p1):
1329 // Only function declarations can be overloaded; object and type
1330 // declarations cannot be overloaded.
1331 Match = *I;
1333 }
1334 }
1335
1336 // C++ [temp.friend]p1:
1337 // For a friend function declaration that is not a template declaration:
1338 // -- if the name of the friend is a qualified or unqualified template-id,
1339 // [...], otherwise
1340 // -- if the name of the friend is a qualified-id and a matching
1341 // non-template function is found in the specified class or namespace,
1342 // the friend declaration refers to that function, otherwise,
1343 // -- if the name of the friend is a qualified-id and a matching function
1344 // template is found in the specified class or namespace, the friend
1345 // declaration refers to the deduced specialization of that function
1346 // template, otherwise
1347 // -- the name shall be an unqualified-id [...]
1348 // If we get here for a qualified friend declaration, we've just reached the
1349 // third bullet. If the type of the friend is dependent, skip this lookup
1350 // until instantiation.
1351 if (New->getFriendObjectKind() && New->getQualifier() &&
1352 !New->getDescribedFunctionTemplate() &&
1353 !New->getDependentSpecializationInfo() &&
1354 !New->getType()->isDependentType()) {
1355 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1356 TemplateSpecResult.addAllDecls(Old);
1357 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1358 /*QualifiedFriend*/true)) {
1359 New->setInvalidDecl();
1361 }
1362
1363 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1364 return OverloadKind::Match;
1365 }
1366
1368}
1369
1370template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1371 assert(D && "function decl should not be null");
1372 if (auto *A = D->getAttr<AttrT>())
1373 return !A->isImplicit();
1374 return false;
1375}
1376
1378 FunctionDecl *Old,
1379 bool UseMemberUsingDeclRules,
1380 bool ConsiderCudaAttrs,
1381 bool UseOverrideRules = false) {
1382 // C++ [basic.start.main]p2: This function shall not be overloaded.
1383 if (New->isMain())
1384 return false;
1385
1386 // MSVCRT user defined entry points cannot be overloaded.
1387 if (New->isMSVCRTEntryPoint())
1388 return false;
1389
1390 NamedDecl *OldDecl = Old;
1391 NamedDecl *NewDecl = New;
1393 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1394
1395 // C++ [temp.fct]p2:
1396 // A function template can be overloaded with other function templates
1397 // and with normal (non-template) functions.
1398 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1399 return true;
1400
1401 // Is the function New an overload of the function Old?
1402 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1403 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1404
1405 // Compare the signatures (C++ 1.3.10) of the two functions to
1406 // determine whether they are overloads. If we find any mismatch
1407 // in the signature, they are overloads.
1408
1409 // If either of these functions is a K&R-style function (no
1410 // prototype), then we consider them to have matching signatures.
1411 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1413 return false;
1414
1415 const auto *OldType = cast<FunctionProtoType>(OldQType);
1416 const auto *NewType = cast<FunctionProtoType>(NewQType);
1417
1418 // The signature of a function includes the types of its
1419 // parameters (C++ 1.3.10), which includes the presence or absence
1420 // of the ellipsis; see C++ DR 357).
1421 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1422 return true;
1423
1424 // For member-like friends, the enclosing class is part of the signature.
1425 if ((New->isMemberLikeConstrainedFriend() ||
1427 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1428 return true;
1429
1430 // Compare the parameter lists.
1431 // This can only be done once we have establish that friend functions
1432 // inhabit the same context, otherwise we might tried to instantiate
1433 // references to non-instantiated entities during constraint substitution.
1434 // GH78101.
1435 if (NewTemplate) {
1436 OldDecl = OldTemplate;
1437 NewDecl = NewTemplate;
1438 // C++ [temp.over.link]p4:
1439 // The signature of a function template consists of its function
1440 // signature, its return type and its template parameter list. The names
1441 // of the template parameters are significant only for establishing the
1442 // relationship between the template parameters and the rest of the
1443 // signature.
1444 //
1445 // We check the return type and template parameter lists for function
1446 // templates first; the remaining checks follow.
1447 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1448 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1449 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1450 bool SameReturnType = SemaRef.Context.hasSameType(
1451 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1452 // FIXME(GH58571): Match template parameter list even for non-constrained
1453 // template heads. This currently ensures that the code prior to C++20 is
1454 // not newly broken.
1455 bool ConstraintsInTemplateHead =
1458 // C++ [namespace.udecl]p11:
1459 // The set of declarations named by a using-declarator that inhabits a
1460 // class C does not include member functions and member function
1461 // templates of a base class that "correspond" to (and thus would
1462 // conflict with) a declaration of a function or function template in
1463 // C.
1464 // Comparing return types is not required for the "correspond" check to
1465 // decide whether a member introduced by a shadow declaration is hidden.
1466 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1467 !SameTemplateParameterList)
1468 return true;
1469 if (!UseMemberUsingDeclRules &&
1470 (!SameTemplateParameterList || !SameReturnType))
1471 return true;
1472 }
1473
1474 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1475 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1476
1477 int OldParamsOffset = 0;
1478 int NewParamsOffset = 0;
1479
1480 // When determining if a method is an overload from a base class, act as if
1481 // the implicit object parameter are of the same type.
1482
1483 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1485 auto ThisType = M->getFunctionObjectParameterReferenceType();
1486 if (ThisType.isConstQualified())
1487 Q.removeConst();
1488 return Q;
1489 }
1490
1491 // We do not allow overloading based off of '__restrict'.
1492 Q.removeRestrict();
1493
1494 // We may not have applied the implicit const for a constexpr member
1495 // function yet (because we haven't yet resolved whether this is a static
1496 // or non-static member function). Add it now, on the assumption that this
1497 // is a redeclaration of OldMethod.
1498 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1499 (M->isConstexpr() || M->isConsteval()) &&
1500 !isa<CXXConstructorDecl>(NewMethod))
1501 Q.addConst();
1502 return Q;
1503 };
1504
1505 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1506 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1507 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1508
1509 if (OldMethod->isExplicitObjectMemberFunction()) {
1510 BS.Quals.removeVolatile();
1511 DS.Quals.removeVolatile();
1512 }
1513
1514 return BS.Quals == DS.Quals;
1515 };
1516
1517 auto CompareType = [&](QualType Base, QualType D) {
1518 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1519 auto DS = D.getNonReferenceType().getCanonicalType().split();
1520
1521 if (!AreQualifiersEqual(BS, DS))
1522 return false;
1523
1524 if (OldMethod->isImplicitObjectMemberFunction() &&
1525 OldMethod->getParent() != NewMethod->getParent()) {
1526 CanQualType ParentType =
1527 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1528 if (ParentType.getTypePtr() != BS.Ty)
1529 return false;
1530 BS.Ty = DS.Ty;
1531 }
1532
1533 // FIXME: should we ignore some type attributes here?
1534 if (BS.Ty != DS.Ty)
1535 return false;
1536
1537 if (Base->isLValueReferenceType())
1538 return D->isLValueReferenceType();
1539 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1540 };
1541
1542 // If the function is a class member, its signature includes the
1543 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1544 auto DiagnoseInconsistentRefQualifiers = [&]() {
1545 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1546 return false;
1547 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1548 return false;
1549 if (OldMethod->isExplicitObjectMemberFunction() ||
1550 NewMethod->isExplicitObjectMemberFunction())
1551 return false;
1552 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1553 NewMethod->getRefQualifier() == RQ_None)) {
1554 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1555 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1556 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1557 return true;
1558 }
1559 return false;
1560 };
1561
1562 // We look at the parameters first, as it is the common case.
1563 // However we should not emit diagnostic before checking
1564 // the overloads do not differ by constraints or other discriminant.
1565 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1566 bool HaveInconsistentQualifiers = false;
1567
1568 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1569 OldParamsOffset++;
1570 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1571 NewParamsOffset++;
1572
1573 if (OldType->getNumParams() - OldParamsOffset !=
1574 NewType->getNumParams() - NewParamsOffset ||
1576 {OldType->param_type_begin() + OldParamsOffset,
1577 OldType->param_type_end()},
1578 {NewType->param_type_begin() + NewParamsOffset,
1579 NewType->param_type_end()},
1580 nullptr)) {
1581 return true;
1582 }
1583
1584 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1585 !NewMethod->isStatic()) {
1586 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1587 const CXXMethodDecl *New) {
1588 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1589 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1590
1591 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1592 return F->getRefQualifier() == RQ_None &&
1593 !F->isExplicitObjectMemberFunction();
1594 };
1595
1596 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1597 CompareType(OldObjectType.getNonReferenceType(),
1598 NewObjectType.getNonReferenceType()))
1599 return true;
1600 return CompareType(OldObjectType, NewObjectType);
1601 }(OldMethod, NewMethod);
1602
1603 if (!HaveCorrespondingObjectParameters) {
1604 ShouldDiagnoseInconsistentRefQualifiers = true;
1605 // CWG2554
1606 // and, if at least one is an explicit object member function, ignoring
1607 // object parameters
1608 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1609 !OldMethod->isExplicitObjectMemberFunction()))
1610 HaveInconsistentQualifiers = true;
1611 }
1612 }
1613
1614 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1615 NewMethod->isImplicitObjectMemberFunction())
1616 ShouldDiagnoseInconsistentRefQualifiers = true;
1617
1618 if (!UseOverrideRules &&
1619 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1620 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1621 OldRC = Old->getTrailingRequiresClause();
1622 if (!NewRC != !OldRC)
1623 return true;
1624 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1625 return true;
1626 if (NewRC &&
1627 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1628 NewDecl, NewRC.ConstraintExpr))
1629 return true;
1630 }
1631
1632 // Though pass_object_size is placed on parameters and takes an argument, we
1633 // consider it to be a function-level modifier for the sake of function
1634 // identity. Either the function has one or more parameters with
1635 // pass_object_size or it doesn't.
1638 return true;
1639
1640 // enable_if attributes are an order-sensitive part of the signature.
1642 NewI = New->specific_attr_begin<EnableIfAttr>(),
1643 NewE = New->specific_attr_end<EnableIfAttr>(),
1644 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1645 OldE = Old->specific_attr_end<EnableIfAttr>();
1646 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1647 if (NewI == NewE || OldI == OldE)
1648 return true;
1649 llvm::FoldingSetNodeID NewID, OldID;
1650 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1651 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1652 if (NewID != OldID)
1653 return true;
1654 }
1655
1656 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1657 DiagnoseInconsistentRefQualifiers()) ||
1658 HaveInconsistentQualifiers)
1659 return true;
1660
1661 // At this point, it is known that the two functions have the same signature.
1662 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1663 // Don't allow overloading of destructors. (In theory we could, but it
1664 // would be a giant change to clang.)
1666 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1667 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1668 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1669 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1670 "Unexpected invalid target.");
1671
1672 // Allow overloading of functions with same signature and different CUDA
1673 // target attributes.
1674 if (NewTarget != OldTarget) {
1675 // Special case: non-constexpr function is allowed to override
1676 // constexpr virtual function
1677 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1678 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1683 return false;
1684 }
1685 return true;
1686 }
1687 }
1688 }
1689 }
1690
1691 // The signatures match; this is not an overload.
1692 return false;
1693}
1694
1696 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1697 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1698 ConsiderCudaAttrs);
1699}
1700
1702 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1703 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1704 /*UseMemberUsingDeclRules=*/false,
1705 /*ConsiderCudaAttrs=*/true,
1706 /*UseOverrideRules=*/true);
1707}
1708
1709/// Tries a user-defined conversion from From to ToType.
1710///
1711/// Produces an implicit conversion sequence for when a standard conversion
1712/// is not an option. See TryImplicitConversion for more information.
1715 bool SuppressUserConversions,
1716 AllowedExplicit AllowExplicit,
1717 bool InOverloadResolution,
1718 bool CStyle,
1719 bool AllowObjCWritebackConversion,
1720 bool AllowObjCConversionOnExplicit) {
1722
1723 if (SuppressUserConversions) {
1724 // We're not in the case above, so there is no conversion that
1725 // we can perform.
1727 return ICS;
1728 }
1729
1730 // Attempt user-defined conversion.
1731 OverloadCandidateSet Conversions(From->getExprLoc(),
1733 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1734 Conversions, AllowExplicit,
1735 AllowObjCConversionOnExplicit)) {
1736 case OR_Success:
1737 case OR_Deleted:
1738 ICS.setUserDefined();
1739 // C++ [over.ics.user]p4:
1740 // A conversion of an expression of class type to the same class
1741 // type is given Exact Match rank, and a conversion of an
1742 // expression of class type to a base class of that type is
1743 // given Conversion rank, in spite of the fact that a copy
1744 // constructor (i.e., a user-defined conversion function) is
1745 // called for those cases.
1747 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1748 QualType FromType;
1749 SourceLocation FromLoc;
1750 // C++11 [over.ics.list]p6, per DR2137:
1751 // C++17 [over.ics.list]p6:
1752 // If C is not an initializer-list constructor and the initializer list
1753 // has a single element of type cv U, where U is X or a class derived
1754 // from X, the implicit conversion sequence has Exact Match rank if U is
1755 // X, or Conversion rank if U is derived from X.
1756 bool FromListInit = false;
1757 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1758 InitList && InitList->getNumInits() == 1 &&
1760 const Expr *SingleInit = InitList->getInit(0);
1761 FromType = SingleInit->getType();
1762 FromLoc = SingleInit->getBeginLoc();
1763 FromListInit = true;
1764 } else {
1765 FromType = From->getType();
1766 FromLoc = From->getBeginLoc();
1767 }
1768 QualType FromCanon =
1770 QualType ToCanon
1772 if ((FromCanon == ToCanon ||
1773 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1774 // Turn this into a "standard" conversion sequence, so that it
1775 // gets ranked with standard conversion sequences.
1777 ICS.setStandard();
1779 ICS.Standard.setFromType(FromType);
1780 ICS.Standard.setAllToTypes(ToType);
1781 ICS.Standard.FromBracedInitList = FromListInit;
1784 if (ToCanon != FromCanon)
1786 }
1787 }
1788 break;
1789
1790 case OR_Ambiguous:
1791 ICS.setAmbiguous();
1792 ICS.Ambiguous.setFromType(From->getType());
1793 ICS.Ambiguous.setToType(ToType);
1794 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1795 Cand != Conversions.end(); ++Cand)
1796 if (Cand->Best)
1797 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1798 break;
1799
1800 // Fall through.
1803 break;
1804 }
1805
1806 return ICS;
1807}
1808
1809/// TryImplicitConversion - Attempt to perform an implicit conversion
1810/// from the given expression (Expr) to the given type (ToType). This
1811/// function returns an implicit conversion sequence that can be used
1812/// to perform the initialization. Given
1813///
1814/// void f(float f);
1815/// void g(int i) { f(i); }
1816///
1817/// this routine would produce an implicit conversion sequence to
1818/// describe the initialization of f from i, which will be a standard
1819/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1820/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1821//
1822/// Note that this routine only determines how the conversion can be
1823/// performed; it does not actually perform the conversion. As such,
1824/// it will not produce any diagnostics if no conversion is available,
1825/// but will instead return an implicit conversion sequence of kind
1826/// "BadConversion".
1827///
1828/// If @p SuppressUserConversions, then user-defined conversions are
1829/// not permitted.
1830/// If @p AllowExplicit, then explicit user-defined conversions are
1831/// permitted.
1832///
1833/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1834/// writeback conversion, which allows __autoreleasing id* parameters to
1835/// be initialized with __strong id* or __weak id* arguments.
1836static ImplicitConversionSequence
1838 bool SuppressUserConversions,
1839 AllowedExplicit AllowExplicit,
1840 bool InOverloadResolution,
1841 bool CStyle,
1842 bool AllowObjCWritebackConversion,
1843 bool AllowObjCConversionOnExplicit) {
1845 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1846 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1847 ICS.setStandard();
1848 return ICS;
1849 }
1850
1851 if (!S.getLangOpts().CPlusPlus) {
1853 return ICS;
1854 }
1855
1856 // C++ [over.ics.user]p4:
1857 // A conversion of an expression of class type to the same class
1858 // type is given Exact Match rank, and a conversion of an
1859 // expression of class type to a base class of that type is
1860 // given Conversion rank, in spite of the fact that a copy/move
1861 // constructor (i.e., a user-defined conversion function) is
1862 // called for those cases.
1863 QualType FromType = From->getType();
1864 if (ToType->isRecordType() &&
1865 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1866 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1867 ICS.setStandard();
1869 ICS.Standard.setFromType(FromType);
1870 ICS.Standard.setAllToTypes(ToType);
1871
1872 // We don't actually check at this point whether there is a valid
1873 // copy/move constructor, since overloading just assumes that it
1874 // exists. When we actually perform initialization, we'll find the
1875 // appropriate constructor to copy the returned object, if needed.
1876 ICS.Standard.CopyConstructor = nullptr;
1877
1878 // In HLSL, a conversion of an expression of class type to the same class
1879 // type needs implicit LvaluetoRvalue conversion.
1880 if (S.getLangOpts().HLSL)
1882
1883 // Determine whether this is considered a derived-to-base conversion.
1884 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1886
1887 return ICS;
1888 }
1889
1890 if (S.getLangOpts().HLSL) {
1891 // Handle conversion of the HLSL resource types.
1892 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1893 if (FromTy->isHLSLAttributedResourceType()) {
1894 // Attributed resource types can convert to other attributed
1895 // resource types with the same attributes and contained types,
1896 // or to __hlsl_resource_t without any attributes.
1897 bool CanConvert = false;
1898 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1899 if (ToTy->isHLSLAttributedResourceType()) {
1900 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1901 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1902 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1903 FromResType->getWrappedType()) &&
1904 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1905 FromResType->getContainedType()) &&
1906 ToResType->getAttrs() == FromResType->getAttrs())
1907 CanConvert = true;
1908 } else if (ToTy->isHLSLResourceType()) {
1909 CanConvert = true;
1910 }
1911 if (CanConvert) {
1912 ICS.setStandard();
1914 ICS.Standard.setFromType(FromType);
1915 ICS.Standard.setAllToTypes(ToType);
1916 return ICS;
1917 }
1918 }
1919 }
1920
1921 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1922 AllowExplicit, InOverloadResolution, CStyle,
1923 AllowObjCWritebackConversion,
1924 AllowObjCConversionOnExplicit);
1925}
1926
1927ImplicitConversionSequence
1929 bool SuppressUserConversions,
1930 AllowedExplicit AllowExplicit,
1931 bool InOverloadResolution,
1932 bool CStyle,
1933 bool AllowObjCWritebackConversion) {
1934 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1935 AllowExplicit, InOverloadResolution, CStyle,
1936 AllowObjCWritebackConversion,
1937 /*AllowObjCConversionOnExplicit=*/false);
1938}
1939
1941 AssignmentAction Action,
1942 bool AllowExplicit) {
1943 if (checkPlaceholderForOverload(*this, From))
1944 return ExprError();
1945
1946 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1947 bool AllowObjCWritebackConversion =
1948 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1949 Action == AssignmentAction::Sending);
1950 if (getLangOpts().ObjC)
1951 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1952 From->getType(), From);
1954 *this, From, ToType,
1955 /*SuppressUserConversions=*/false,
1956 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1957 /*InOverloadResolution=*/false,
1958 /*CStyle=*/false, AllowObjCWritebackConversion,
1959 /*AllowObjCConversionOnExplicit=*/false);
1960 return PerformImplicitConversion(From, ToType, ICS, Action);
1961}
1962
1964 QualType &ResultTy) const {
1965 bool Changed = IsFunctionConversion(FromType, ToType);
1966 if (Changed)
1967 ResultTy = ToType;
1968 return Changed;
1969}
1970
1971bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1972 if (Context.hasSameUnqualifiedType(FromType, ToType))
1973 return false;
1974
1975 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1976 // or F(t noexcept) -> F(t)
1977 // where F adds one of the following at most once:
1978 // - a pointer
1979 // - a member pointer
1980 // - a block pointer
1981 // Changes here need matching changes in FindCompositePointerType.
1982 CanQualType CanTo = Context.getCanonicalType(ToType);
1983 CanQualType CanFrom = Context.getCanonicalType(FromType);
1984 Type::TypeClass TyClass = CanTo->getTypeClass();
1985 if (TyClass != CanFrom->getTypeClass()) return false;
1986 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1987 if (TyClass == Type::Pointer) {
1988 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1989 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1990 } else if (TyClass == Type::BlockPointer) {
1991 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1992 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1993 } else if (TyClass == Type::MemberPointer) {
1994 auto ToMPT = CanTo.castAs<MemberPointerType>();
1995 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1996 // A function pointer conversion cannot change the class of the function.
1997 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1998 FromMPT->getMostRecentCXXRecordDecl()))
1999 return false;
2000 CanTo = ToMPT->getPointeeType();
2001 CanFrom = FromMPT->getPointeeType();
2002 } else {
2003 return false;
2004 }
2005
2006 TyClass = CanTo->getTypeClass();
2007 if (TyClass != CanFrom->getTypeClass()) return false;
2008 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
2009 return false;
2010 }
2011
2012 const auto *FromFn = cast<FunctionType>(CanFrom);
2013 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
2014
2015 const auto *ToFn = cast<FunctionType>(CanTo);
2016 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
2017
2018 bool Changed = false;
2019
2020 // Drop 'noreturn' if not present in target type.
2021 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
2022 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
2023 Changed = true;
2024 }
2025
2026 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
2027 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
2028
2029 if (FromFPT && ToFPT) {
2030 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2031 QualType NewTy = Context.getFunctionType(
2032 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2033 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2034 ToFPT->hasCFIUncheckedCallee()));
2035 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2036 FromFn = FromFPT;
2037 Changed = true;
2038 }
2039 }
2040
2041 // Drop 'noexcept' if not present in target type.
2042 if (FromFPT && ToFPT) {
2043 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2044 FromFn = cast<FunctionType>(
2045 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2046 EST_None)
2047 .getTypePtr());
2048 Changed = true;
2049 }
2050
2051 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2052 // only if the ExtParameterInfo lists of the two function prototypes can be
2053 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2055 bool CanUseToFPT, CanUseFromFPT;
2056 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2057 CanUseFromFPT, NewParamInfos) &&
2058 CanUseToFPT && !CanUseFromFPT) {
2059 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2060 ExtInfo.ExtParameterInfos =
2061 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2062 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2063 FromFPT->getParamTypes(), ExtInfo);
2064 FromFn = QT->getAs<FunctionType>();
2065 Changed = true;
2066 }
2067
2068 if (Context.hasAnyFunctionEffects()) {
2069 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2070
2071 // Transparently add/drop effects; here we are concerned with
2072 // language rules/canonicalization. Adding/dropping effects is a warning.
2073 const auto FromFX = FromFPT->getFunctionEffects();
2074 const auto ToFX = ToFPT->getFunctionEffects();
2075 if (FromFX != ToFX) {
2076 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2077 ExtInfo.FunctionEffects = ToFX;
2078 QualType QT = Context.getFunctionType(
2079 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2080 FromFn = QT->getAs<FunctionType>();
2081 Changed = true;
2082 }
2083 }
2084 }
2085
2086 if (!Changed)
2087 return false;
2088
2089 assert(QualType(FromFn, 0).isCanonical());
2090 if (QualType(FromFn, 0) != CanTo) return false;
2091
2092 return true;
2093}
2094
2095/// Determine whether the conversion from FromType to ToType is a valid
2096/// floating point conversion.
2097///
2098static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2099 QualType ToType) {
2100 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2101 return false;
2102 // FIXME: disable conversions between long double, __ibm128 and __float128
2103 // if their representation is different until there is back end support
2104 // We of course allow this conversion if long double is really double.
2105
2106 // Conversions between bfloat16 and float16 are currently not supported.
2107 if ((FromType->isBFloat16Type() &&
2108 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2109 (ToType->isBFloat16Type() &&
2110 (FromType->isFloat16Type() || FromType->isHalfType())))
2111 return false;
2112
2113 // Conversions between IEEE-quad and IBM-extended semantics are not
2114 // permitted.
2115 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2116 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2117 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2118 &ToSem == &llvm::APFloat::IEEEquad()) ||
2119 (&FromSem == &llvm::APFloat::IEEEquad() &&
2120 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2121 return false;
2122 return true;
2123}
2124
2126 QualType ToType,
2128 Expr *From) {
2129 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2130 return true;
2131
2132 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2134 return true;
2135 }
2136
2137 if (IsFloatingPointConversion(S, FromType, ToType)) {
2139 return true;
2140 }
2141
2142 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2144 return true;
2145 }
2146
2147 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2149 ToType->isRealFloatingType())) {
2151 return true;
2152 }
2153
2154 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2156 return true;
2157 }
2158
2159 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2160 ToType->isIntegralType(S.Context)) {
2162 return true;
2163 }
2164
2165 return false;
2166}
2167
2168/// Determine whether the conversion from FromType to ToType is a valid
2169/// matrix conversion.
2170///
2171/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2172/// conversion.
2173static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2175 ImplicitConversionKind &ElConv, Expr *From,
2176 bool InOverloadResolution, bool CStyle) {
2177 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2178 if (!S.getLangOpts().HLSL)
2179 return false;
2180
2181 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2182 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2183
2184 // If both arguments are matrix, handle possible matrix truncation and
2185 // element conversion.
2186 if (ToMatrixType && FromMatrixType) {
2187 unsigned FromCols = FromMatrixType->getNumColumns();
2188 unsigned ToCols = ToMatrixType->getNumColumns();
2189 if (FromCols < ToCols)
2190 return false;
2191
2192 unsigned FromRows = FromMatrixType->getNumRows();
2193 unsigned ToRows = ToMatrixType->getNumRows();
2194 if (FromRows < ToRows)
2195 return false;
2196
2197 if (FromRows == ToRows && FromCols == ToCols)
2198 ElConv = ICK_Identity;
2199 else
2201
2202 QualType FromElTy = FromMatrixType->getElementType();
2203 QualType ToElTy = ToMatrixType->getElementType();
2204 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2205 return true;
2206 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2207 }
2208
2209 // Matrix splat from any arithmetic type to a matrix.
2210 if (ToMatrixType && FromType->isArithmeticType()) {
2211 ElConv = ICK_HLSL_Matrix_Splat;
2212 QualType ToElTy = ToMatrixType->getElementType();
2213 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2214 }
2215 if (FromMatrixType && !ToMatrixType) {
2217 QualType FromElTy = FromMatrixType->getElementType();
2218 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2219 return true;
2220 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2221 }
2222
2223 return false;
2224}
2225
2226/// Determine whether the conversion from FromType to ToType is a valid
2227/// vector conversion.
2228///
2229/// \param ICK Will be set to the vector conversion kind, if this is a vector
2230/// conversion.
2231static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2233 ImplicitConversionKind &ElConv, Expr *From,
2234 bool InOverloadResolution, bool CStyle) {
2235 // We need at least one of these types to be a vector type to have a vector
2236 // conversion.
2237 if (!ToType->isVectorType() && !FromType->isVectorType())
2238 return false;
2239
2240 // Identical types require no conversions.
2241 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2242 return false;
2243
2244 // HLSL allows implicit truncation of vector types.
2245 if (S.getLangOpts().HLSL) {
2246 auto *ToExtType = ToType->getAs<ExtVectorType>();
2247 auto *FromExtType = FromType->getAs<ExtVectorType>();
2248
2249 // If both arguments are vectors, handle possible vector truncation and
2250 // element conversion.
2251 if (ToExtType && FromExtType) {
2252 unsigned FromElts = FromExtType->getNumElements();
2253 unsigned ToElts = ToExtType->getNumElements();
2254 if (FromElts < ToElts)
2255 return false;
2256 if (FromElts == ToElts)
2257 ElConv = ICK_Identity;
2258 else
2260
2261 QualType FromElTy = FromExtType->getElementType();
2262 QualType ToElTy = ToExtType->getElementType();
2263 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2264 return true;
2265 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2266 }
2267 if (FromExtType && !ToExtType) {
2269 QualType FromElTy = FromExtType->getElementType();
2270 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2271 return true;
2272 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2273 }
2274 // Fallthrough for the case where ToType is a vector and FromType is not.
2275 }
2276
2277 // There are no conversions between extended vector types, only identity.
2278 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2279 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2280 // Implicit conversions require the same number of elements.
2281 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2282 return false;
2283
2284 // Permit implicit conversions from integral values to boolean vectors.
2285 if (ToType->isExtVectorBoolType() &&
2286 FromExtType->getElementType()->isIntegerType()) {
2288 return true;
2289 }
2290 // There are no other conversions between extended vector types.
2291 return false;
2292 }
2293
2294 // Vector splat from any arithmetic type to a vector.
2295 if (FromType->isArithmeticType()) {
2296 if (S.getLangOpts().HLSL) {
2297 ElConv = ICK_HLSL_Vector_Splat;
2298 QualType ToElTy = ToExtType->getElementType();
2299 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2300 From);
2301 }
2302 ICK = ICK_Vector_Splat;
2303 return true;
2304 }
2305 }
2306
2307 if (ToType->isSVESizelessBuiltinType() ||
2308 FromType->isSVESizelessBuiltinType())
2309 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2310 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2312 return true;
2313 }
2314
2315 if (ToType->isRVVSizelessBuiltinType() ||
2316 FromType->isRVVSizelessBuiltinType())
2317 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2318 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2320 return true;
2321 }
2322
2323 // We can perform the conversion between vector types in the following cases:
2324 // 1)vector types are equivalent AltiVec and GCC vector types
2325 // 2)lax vector conversions are permitted and the vector types are of the
2326 // same size
2327 // 3)the destination type does not have the ARM MVE strict-polymorphism
2328 // attribute, which inhibits lax vector conversion for overload resolution
2329 // only
2330 if (ToType->isVectorType() && FromType->isVectorType()) {
2331 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2332 (S.isLaxVectorConversion(FromType, ToType) &&
2333 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2334 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2335 S.isLaxVectorConversion(FromType, ToType) &&
2336 S.anyAltivecTypes(FromType, ToType) &&
2337 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2338 !InOverloadResolution && !CStyle) {
2339 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2340 << FromType << ToType;
2341 }
2343 return true;
2344 }
2345 }
2346
2347 return false;
2348}
2349
2351 QualType ToType,
2353 ImplicitConversionKind &DimensionICK,
2354 Expr *From) {
2355 if (!S.getLangOpts().HLSL)
2356 return false;
2357 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2358 return false;
2359
2360 const bool FromPacked = FromType->isHLSLBuiltinPackedType();
2361 const bool ToPacked = ToType->isHLSLBuiltinPackedType();
2362
2363 if (FromPacked && ToPacked) {
2365 DimensionICK = ICK_Identity;
2366 return true;
2367 }
2368
2369 // Only convert packed types to and from uint
2370 QualType UIntTy = S.Context.UnsignedIntTy;
2371 const bool ToIsUint = S.Context.hasSameUnqualifiedType(ToType, UIntTy);
2372 if (FromPacked && !ToIsUint)
2373 return false;
2374
2375 const bool FromIsUint = S.Context.hasSameUnqualifiedType(FromType, UIntTy);
2376 if (ToPacked && !FromIsUint)
2377 return false;
2378
2379 // Converting to or from uint
2380 if (FromIsUint || ToIsUint) {
2382 DimensionICK = ICK_Identity;
2383 return true;
2384 }
2385
2386 return false;
2387}
2388
2389static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2390 bool InOverloadResolution,
2391 StandardConversionSequence &SCS,
2392 bool CStyle);
2393
2394static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2395 QualType ToType,
2396 bool InOverloadResolution,
2397 StandardConversionSequence &SCS,
2398 bool CStyle);
2399
2400/// IsStandardConversion - Determines whether there is a standard
2401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2402/// expression From to the type ToType. Standard conversion sequences
2403/// only consider non-class types; for conversions that involve class
2404/// types, use TryImplicitConversion. If a conversion exists, SCS will
2405/// contain the standard conversion sequence required to perform this
2406/// conversion and this routine will return true. Otherwise, this
2407/// routine will return false and the value of SCS is unspecified.
2408static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2409 bool InOverloadResolution,
2411 bool CStyle,
2412 bool AllowObjCWritebackConversion) {
2413 QualType FromType = From->getType();
2414
2415 // Standard conversions (C++ [conv])
2417 SCS.IncompatibleObjC = false;
2418 SCS.setFromType(FromType);
2419 SCS.CopyConstructor = nullptr;
2420
2421 // There are no standard conversions for class types in C++, so
2422 // abort early. When overloading in C, however, we do permit them.
2423 if (S.getLangOpts().CPlusPlus &&
2424 (FromType->isRecordType() || ToType->isRecordType()))
2425 return false;
2426
2427 // The first conversion can be an lvalue-to-rvalue conversion,
2428 // array-to-pointer conversion, or function-to-pointer conversion
2429 // (C++ 4p1).
2430
2431 if (FromType == S.Context.OverloadTy) {
2432 DeclAccessPair AccessPair;
2433 if (FunctionDecl *Fn
2434 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2435 AccessPair)) {
2436 // We were able to resolve the address of the overloaded function,
2437 // so we can convert to the type of that function.
2438 FromType = Fn->getType();
2439 SCS.setFromType(FromType);
2440
2441 // we can sometimes resolve &foo<int> regardless of ToType, so check
2442 // if the type matches (identity) or we are converting to bool
2444 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2445 // if the function type matches except for [[noreturn]], it's ok
2446 if (!S.IsFunctionConversion(FromType,
2448 // otherwise, only a boolean conversion is standard
2449 if (!ToType->isBooleanType())
2450 return false;
2451 }
2452
2453 // Check if the "from" expression is taking the address of an overloaded
2454 // function and recompute the FromType accordingly. Take advantage of the
2455 // fact that non-static member functions *must* have such an address-of
2456 // expression.
2457 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2458 if (Method && !Method->isStatic() &&
2459 !Method->isExplicitObjectMemberFunction()) {
2460 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2461 "Non-unary operator on non-static member address");
2462 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2463 == UO_AddrOf &&
2464 "Non-address-of operator on non-static member address");
2465 FromType = S.Context.getMemberPointerType(
2466 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2467 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2468 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2469 UO_AddrOf &&
2470 "Non-address-of operator for overloaded function expression");
2471 FromType = S.Context.getPointerType(FromType);
2472 }
2473 } else {
2474 return false;
2475 }
2476 }
2477
2478 bool argIsLValue = From->isGLValue();
2479 // To handle conversion from ArrayParameterType to ConstantArrayType
2480 // this block must be above the one below because Array parameters
2481 // do not decay and when handling HLSLOutArgExprs and
2482 // the From expression is an LValue.
2483 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2484 ToType->isConstantArrayType()) {
2485 // HLSL constant array parameters do not decay, so if the argument is a
2486 // constant array and the parameter is an ArrayParameterType we have special
2487 // handling here.
2488 if (ToType->isArrayParameterType()) {
2489 FromType = S.Context.getArrayParameterType(FromType);
2490 } else if (FromType->isArrayParameterType()) {
2491 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2492 FromType = APT->getConstantArrayType(S.Context);
2493 }
2494
2496
2497 // Don't consider qualifiers, which include things like address spaces
2498 if (FromType.getCanonicalType().getUnqualifiedType() !=
2500 return false;
2501
2502 SCS.setAllToTypes(ToType);
2503 return true;
2504 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2505 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2506 // Lvalue-to-rvalue conversion (C++11 4.1):
2507 // A glvalue (3.10) of a non-function, non-array type T can
2508 // be converted to a prvalue.
2509
2511
2512 // C11 6.3.2.1p2:
2513 // ... if the lvalue has atomic type, the value has the non-atomic version
2514 // of the type of the lvalue ...
2515 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2516 FromType = Atomic->getValueType();
2517
2518 // If T is a non-class type, the type of the rvalue is the
2519 // cv-unqualified version of T. Otherwise, the type of the rvalue
2520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2521 // just strip the qualifiers because they don't matter.
2522 FromType = FromType.getUnqualifiedType();
2523 } else if (FromType->isArrayType()) {
2524 // Array-to-pointer conversion (C++ 4.2)
2526
2527 // An lvalue or rvalue of type "array of N T" or "array of unknown
2528 // bound of T" can be converted to an rvalue of type "pointer to
2529 // T" (C++ 4.2p1).
2530 FromType = S.Context.getArrayDecayedType(FromType);
2531
2532 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2533 // This conversion is deprecated in C++03 (D.4)
2535
2536 // For the purpose of ranking in overload resolution
2537 // (13.3.3.1.1), this conversion is considered an
2538 // array-to-pointer conversion followed by a qualification
2539 // conversion (4.4). (C++ 4.2p2)
2540 SCS.Second = ICK_Identity;
2543 SCS.setAllToTypes(FromType);
2544 return true;
2545 }
2546 } else if (FromType->isFunctionType() && argIsLValue) {
2547 // Function-to-pointer conversion (C++ 4.3).
2549
2550 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2551 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2553 return false;
2554
2555 // An lvalue of function type T can be converted to an rvalue of
2556 // type "pointer to T." The result is a pointer to the
2557 // function. (C++ 4.3p1).
2558 FromType = S.Context.getPointerType(FromType);
2559 } else {
2560 // We don't require any conversions for the first step.
2561 SCS.First = ICK_Identity;
2562 }
2563 SCS.setToType(0, FromType);
2564
2565 // The second conversion can be an integral promotion, floating
2566 // point promotion, integral conversion, floating point conversion,
2567 // floating-integral conversion, pointer conversion,
2568 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2569 // For overloading in C, this can also be a "compatible-type"
2570 // conversion.
2571 bool IncompatibleObjC = false;
2573 ImplicitConversionKind DimensionICK = ICK_Identity;
2574 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2575 // The unqualified versions of the types are the same: there's no
2576 // conversion to do.
2577 SCS.Second = ICK_Identity;
2578 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2579 // Integral promotion (C++ 4.5).
2581 FromType = ToType.getUnqualifiedType();
2582 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2583 // Floating point promotion (C++ 4.6).
2585 FromType = ToType.getUnqualifiedType();
2586 } else if (S.IsComplexPromotion(FromType, ToType)) {
2587 // Complex promotion (Clang extension)
2589 FromType = ToType.getUnqualifiedType();
2590 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2591 // OverflowBehaviorType promotions
2593 FromType = ToType.getUnqualifiedType();
2594 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2595 // OverflowBehaviorType conversions
2597 FromType = ToType.getUnqualifiedType();
2598 } else if (ToType->isBooleanType() &&
2599 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2600 FromType->isBlockPointerType() ||
2601 FromType->isMemberPointerType())) {
2602 // Boolean conversions (C++ 4.12).
2604 FromType = S.Context.BoolTy;
2605 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2606 ToType->isIntegralType(S.Context)) {
2607 // Integral conversions (C++ 4.7).
2609 FromType = ToType.getUnqualifiedType();
2610 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2611 // Complex conversions (C99 6.3.1.6)
2613 FromType = ToType.getUnqualifiedType();
2614 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2615 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2616 // Complex-real conversions (C99 6.3.1.7)
2618 FromType = ToType.getUnqualifiedType();
2619 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2620 // Floating point conversions (C++ 4.8).
2622 FromType = ToType.getUnqualifiedType();
2623 } else if ((FromType->isRealFloatingType() &&
2624 ToType->isIntegralType(S.Context)) ||
2626 ToType->isRealFloatingType())) {
2627
2628 // Floating-integral conversions (C++ 4.9).
2630 FromType = ToType.getUnqualifiedType();
2631 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2633 } else if (AllowObjCWritebackConversion &&
2634 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2636 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2637 FromType, IncompatibleObjC)) {
2638 // Pointer conversions (C++ 4.10).
2640 SCS.IncompatibleObjC = IncompatibleObjC;
2641 FromType = FromType.getUnqualifiedType();
2642 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2643 InOverloadResolution, FromType)) {
2644 // Pointer to member conversions (4.11).
2646 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2647 From, InOverloadResolution, CStyle)) {
2648 SCS.Second = SecondICK;
2649 SCS.Dimension = DimensionICK;
2650 FromType = ToType.getUnqualifiedType();
2651 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2652 From, InOverloadResolution, CStyle)) {
2653 SCS.Second = SecondICK;
2654 SCS.Dimension = DimensionICK;
2655 FromType = ToType.getUnqualifiedType();
2656 } else if (IsHLSLPackedTypeConversion(S, FromType, ToType, SecondICK,
2657 DimensionICK, From)) {
2658 SCS.Second = SecondICK;
2659 SCS.Dimension = DimensionICK;
2660 FromType = ToType.getUnqualifiedType();
2661 } else if (!S.getLangOpts().CPlusPlus &&
2662 S.Context.typesAreCompatible(ToType, FromType)) {
2663 // Compatible conversions (Clang extension for C function overloading)
2665 FromType = ToType.getUnqualifiedType();
2667 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2669 FromType = ToType;
2670 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2671 CStyle)) {
2672 // tryAtomicConversion has updated the standard conversion sequence
2673 // appropriately.
2674 return true;
2676 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2677 return true;
2678 } else if (ToType->isEventT() &&
2680 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2682 FromType = ToType;
2683 } else if (ToType->isQueueT() &&
2685 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2687 FromType = ToType;
2688 } else if (ToType->isSamplerT() &&
2691 FromType = ToType;
2692 } else if ((ToType->isFixedPointType() &&
2693 FromType->isConvertibleToFixedPointType()) ||
2694 (FromType->isFixedPointType() &&
2695 ToType->isConvertibleToFixedPointType())) {
2697 FromType = ToType;
2698 } else {
2699 // No second conversion required.
2700 SCS.Second = ICK_Identity;
2701 }
2702 SCS.setToType(1, FromType);
2703
2704 // The third conversion can be a function pointer conversion or a
2705 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2706 bool ObjCLifetimeConversion;
2707 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2708 // Function pointer conversions (removing 'noexcept') including removal of
2709 // 'noreturn' (Clang extension).
2711 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2712 ObjCLifetimeConversion)) {
2714 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2715 FromType = ToType;
2716 } else {
2717 // No conversion required
2718 SCS.Third = ICK_Identity;
2719 }
2720
2721 // C++ [over.best.ics]p6:
2722 // [...] Any difference in top-level cv-qualification is
2723 // subsumed by the initialization itself and does not constitute
2724 // a conversion. [...]
2725 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2726 QualType CanonTo = S.Context.getCanonicalType(ToType);
2727 if (CanonFrom.getLocalUnqualifiedType()
2728 == CanonTo.getLocalUnqualifiedType() &&
2729 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2730 FromType = ToType;
2731 CanonFrom = CanonTo;
2732 }
2733
2734 SCS.setToType(2, FromType);
2735
2736 if (CanonFrom == CanonTo)
2737 return true;
2738
2739 // If we have not converted the argument type to the parameter type,
2740 // this is a bad conversion sequence, unless we're resolving an overload in C.
2741 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2742 return false;
2743
2744 ExprResult ER = ExprResult{From};
2745 AssignConvertType Conv =
2747 /*Diagnose=*/false,
2748 /*DiagnoseCFAudited=*/false,
2749 /*ConvertRHS=*/false);
2750 ImplicitConversionKind SecondConv;
2751 switch (Conv) {
2753 case AssignConvertType::
2754 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2755 SecondConv = ICK_C_Only_Conversion;
2756 break;
2757 // For our purposes, discarding qualifiers is just as bad as using an
2758 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2759 // qualifiers, as well.
2764 break;
2765 default:
2766 return false;
2767 }
2768
2769 // First can only be an lvalue conversion, so we pretend that this was the
2770 // second conversion. First should already be valid from earlier in the
2771 // function.
2772 SCS.Second = SecondConv;
2773 SCS.setToType(1, ToType);
2774
2775 // Third is Identity, because Second should rank us worse than any other
2776 // conversion. This could also be ICK_Qualification, but it's simpler to just
2777 // lump everything in with the second conversion, and we don't gain anything
2778 // from making this ICK_Qualification.
2779 SCS.Third = ICK_Identity;
2780 SCS.setToType(2, ToType);
2781 return true;
2782}
2783
2784static bool
2786 QualType &ToType,
2787 bool InOverloadResolution,
2789 bool CStyle) {
2790
2791 const RecordType *UT = ToType->getAsUnionType();
2792 if (!UT)
2793 return false;
2794 // The field to initialize within the transparent union.
2795 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2796 if (!UD->hasAttr<TransparentUnionAttr>())
2797 return false;
2798 // It's compatible if the expression matches any of the fields.
2799 for (const auto *it : UD->fields()) {
2800 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2801 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2802 ToType = it->getType();
2803 return true;
2804 }
2805 }
2806 return false;
2807}
2808
2809bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2810 const BuiltinType *To = ToType->getAs<BuiltinType>();
2811 // All integers are built-in.
2812 if (!To) {
2813 return false;
2814 }
2815
2816 // An rvalue of type char, signed char, unsigned char, short int, or
2817 // unsigned short int can be converted to an rvalue of type int if
2818 // int can represent all the values of the source type; otherwise,
2819 // the source rvalue can be converted to an rvalue of type unsigned
2820 // int (C++ 4.5p1).
2821 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2822 !FromType->isEnumeralType()) {
2823 if ( // We can promote any signed, promotable integer type to an int
2824 (FromType->isSignedIntegerType() ||
2825 // We can promote any unsigned integer type whose size is
2826 // less than int to an int.
2827 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2828 return To->getKind() == BuiltinType::Int;
2829 }
2830
2831 return To->getKind() == BuiltinType::UInt;
2832 }
2833
2834 // C++11 [conv.prom]p3:
2835 // A prvalue of an unscoped enumeration type whose underlying type is not
2836 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2837 // following types that can represent all the values of the enumeration
2838 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2839 // unsigned int, long int, unsigned long int, long long int, or unsigned
2840 // long long int. If none of the types in that list can represent all the
2841 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2842 // type can be converted to an rvalue a prvalue of the extended integer type
2843 // with lowest integer conversion rank (4.13) greater than the rank of long
2844 // long in which all the values of the enumeration can be represented. If
2845 // there are two such extended types, the signed one is chosen.
2846 // C++11 [conv.prom]p4:
2847 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2848 // can be converted to a prvalue of its underlying type. Moreover, if
2849 // integral promotion can be applied to its underlying type, a prvalue of an
2850 // unscoped enumeration type whose underlying type is fixed can also be
2851 // converted to a prvalue of the promoted underlying type.
2852 if (const auto *FromED = FromType->getAsEnumDecl()) {
2853 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2854 // provided for a scoped enumeration.
2855 if (FromED->isScoped())
2856 return false;
2857
2858 // We can perform an integral promotion to the underlying type of the enum,
2859 // even if that's not the promoted type. Note that the check for promoting
2860 // the underlying type is based on the type alone, and does not consider
2861 // the bitfield-ness of the actual source expression.
2862 if (FromED->isFixed()) {
2863 QualType Underlying = FromED->getIntegerType();
2864 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2865 IsIntegralPromotion(nullptr, Underlying, ToType);
2866 }
2867
2868 // We have already pre-calculated the promotion type, so this is trivial.
2869 if (ToType->isIntegerType() &&
2870 isCompleteType(From->getBeginLoc(), FromType))
2871 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2872
2873 // C++ [conv.prom]p5:
2874 // If the bit-field has an enumerated type, it is treated as any other
2875 // value of that type for promotion purposes.
2876 //
2877 // ... so do not fall through into the bit-field checks below in C++.
2878 if (getLangOpts().CPlusPlus)
2879 return false;
2880 }
2881
2882 // C++0x [conv.prom]p2:
2883 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2884 // to an rvalue a prvalue of the first of the following types that can
2885 // represent all the values of its underlying type: int, unsigned int,
2886 // long int, unsigned long int, long long int, or unsigned long long int.
2887 // If none of the types in that list can represent all the values of its
2888 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2889 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2890 // type.
2891 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2892 ToType->isIntegerType()) {
2893 // Determine whether the type we're converting from is signed or
2894 // unsigned.
2895 bool FromIsSigned = FromType->isSignedIntegerType();
2896 uint64_t FromSize = Context.getTypeSize(FromType);
2897
2898 // The types we'll try to promote to, in the appropriate
2899 // order. Try each of these types.
2900 QualType PromoteTypes[6] = {
2901 Context.IntTy, Context.UnsignedIntTy,
2902 Context.LongTy, Context.UnsignedLongTy ,
2903 Context.LongLongTy, Context.UnsignedLongLongTy
2904 };
2905 for (int Idx = 0; Idx < 6; ++Idx) {
2906 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2907 if (FromSize < ToSize ||
2908 (FromSize == ToSize &&
2909 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2910 // We found the type that we can promote to. If this is the
2911 // type we wanted, we have a promotion. Otherwise, no
2912 // promotion.
2913 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2914 }
2915 }
2916 }
2917
2918 // An rvalue for an integral bit-field (9.6) can be converted to an
2919 // rvalue of type int if int can represent all the values of the
2920 // bit-field; otherwise, it can be converted to unsigned int if
2921 // unsigned int can represent all the values of the bit-field. If
2922 // the bit-field is larger yet, no integral promotion applies to
2923 // it. If the bit-field has an enumerated type, it is treated as any
2924 // other value of that type for promotion purposes (C++ 4.5p3).
2925 // FIXME: We should delay checking of bit-fields until we actually perform the
2926 // conversion.
2927 //
2928 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2929 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2930 // bit-fields and those whose underlying type is larger than int) for GCC
2931 // compatibility.
2932 if (From) {
2933 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2934 std::optional<llvm::APSInt> BitWidth;
2935 if (FromType->isIntegralType(Context) &&
2936 (BitWidth =
2937 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2938 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2939 ToSize = Context.getTypeSize(ToType);
2940
2941 // Are we promoting to an int from a bitfield that fits in an int?
2942 if (*BitWidth < ToSize ||
2943 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2944 return To->getKind() == BuiltinType::Int;
2945 }
2946
2947 // Are we promoting to an unsigned int from an unsigned bitfield
2948 // that fits into an unsigned int?
2949 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2950 return To->getKind() == BuiltinType::UInt;
2951 }
2952
2953 return false;
2954 }
2955 }
2956 }
2957
2958 // An rvalue of type bool can be converted to an rvalue of type int,
2959 // with false becoming zero and true becoming one (C++ 4.5p4).
2960 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2961 return true;
2962 }
2963
2964 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2965 // integral type.
2966 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2967 ToType->isIntegerType())
2968 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2969
2970 return false;
2971}
2972
2974 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2975 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2976 /// An rvalue of type float can be converted to an rvalue of type
2977 /// double. (C++ 4.6p1).
2978 if (FromBuiltin->getKind() == BuiltinType::Float &&
2979 ToBuiltin->getKind() == BuiltinType::Double)
2980 return true;
2981
2982 // C99 6.3.1.5p1:
2983 // When a float is promoted to double or long double, or a
2984 // double is promoted to long double [...].
2985 if (!getLangOpts().CPlusPlus &&
2986 (FromBuiltin->getKind() == BuiltinType::Float ||
2987 FromBuiltin->getKind() == BuiltinType::Double) &&
2988 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2989 ToBuiltin->getKind() == BuiltinType::Float128 ||
2990 ToBuiltin->getKind() == BuiltinType::Ibm128))
2991 return true;
2992
2993 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2994 // or not native half types are enabled.
2995 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2996 (ToBuiltin->getKind() == BuiltinType::Float ||
2997 ToBuiltin->getKind() == BuiltinType::Double))
2998 return true;
2999
3000 // Half can be promoted to float.
3001 if (!getLangOpts().NativeHalfType &&
3002 FromBuiltin->getKind() == BuiltinType::Half &&
3003 ToBuiltin->getKind() == BuiltinType::Float)
3004 return true;
3005 }
3006
3007 return false;
3008}
3009
3011 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
3012 if (!FromComplex)
3013 return false;
3014
3015 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
3016 if (!ToComplex)
3017 return false;
3018
3019 return IsFloatingPointPromotion(FromComplex->getElementType(),
3020 ToComplex->getElementType()) ||
3021 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
3022 ToComplex->getElementType());
3023}
3024
3026 if (!getLangOpts().OverflowBehaviorTypes)
3027 return false;
3028
3029 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
3030 return false;
3031
3032 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
3033}
3034
3036 QualType ToType) {
3037 if (!getLangOpts().OverflowBehaviorTypes)
3038 return false;
3039
3040 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
3041 if (ToType->isBooleanType())
3042 return false;
3043 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
3044 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
3045 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
3046 if (ToED->isScoped())
3047 return false;
3048 }
3049 return true;
3050 }
3051
3052 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3053 return true;
3054
3055 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3056 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
3057
3058 return false;
3059}
3060
3061/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
3062/// the pointer type FromPtr to a pointer to type ToPointee, with the
3063/// same type qualifiers as FromPtr has on its pointee type. ToType,
3064/// if non-empty, will be a pointer to ToType that may or may not have
3065/// the right set of qualifiers on its pointee.
3066///
3067static QualType
3069 QualType ToPointee, QualType ToType,
3070 ASTContext &Context,
3071 bool StripObjCLifetime = false) {
3072 assert((FromPtr->getTypeClass() == Type::Pointer ||
3073 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3074 "Invalid similarly-qualified pointer type");
3075
3076 /// Conversions to 'id' subsume cv-qualifier conversions.
3077 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3078 return ToType.getUnqualifiedType();
3079
3080 QualType CanonFromPointee
3081 = Context.getCanonicalType(FromPtr->getPointeeType());
3082 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3083 Qualifiers Quals = CanonFromPointee.getQualifiers();
3084
3085 if (StripObjCLifetime)
3086 Quals.removeObjCLifetime();
3087
3088 // Exact qualifier match -> return the pointer type we're converting to.
3089 if (CanonToPointee.getLocalQualifiers() == Quals) {
3090 // ToType is exactly what we need. Return it.
3091 if (!ToType.isNull())
3092 return ToType.getUnqualifiedType();
3093
3094 // Build a pointer to ToPointee. It has the right qualifiers
3095 // already.
3096 if (isa<ObjCObjectPointerType>(ToType))
3097 return Context.getObjCObjectPointerType(ToPointee);
3098 return Context.getPointerType(ToPointee);
3099 }
3100
3101 // Just build a canonical type that has the right qualifiers.
3102 QualType QualifiedCanonToPointee
3103 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3104
3105 if (isa<ObjCObjectPointerType>(ToType))
3106 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3107 return Context.getPointerType(QualifiedCanonToPointee);
3108}
3109
3111 bool InOverloadResolution,
3112 ASTContext &Context) {
3113 // Handle value-dependent integral null pointer constants correctly.
3114 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3115 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3117 return !InOverloadResolution;
3118
3119 return Expr->isNullPointerConstant(Context,
3120 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3122}
3123
3125 bool InOverloadResolution,
3126 QualType& ConvertedType,
3127 bool &IncompatibleObjC) {
3128 IncompatibleObjC = false;
3129 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3130 IncompatibleObjC))
3131 return true;
3132
3133 // Conversion from a null pointer constant to any Objective-C pointer type.
3134 if (ToType->isObjCObjectPointerType() &&
3135 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3136 ConvertedType = ToType;
3137 return true;
3138 }
3139
3140 // Blocks: Block pointers can be converted to void*.
3141 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3142 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3143 ConvertedType = ToType;
3144 return true;
3145 }
3146 // Blocks: A null pointer constant can be converted to a block
3147 // pointer type.
3148 if (ToType->isBlockPointerType() &&
3149 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3150 ConvertedType = ToType;
3151 return true;
3152 }
3153
3154 // If the left-hand-side is nullptr_t, the right side can be a null
3155 // pointer constant.
3156 if (ToType->isNullPtrType() &&
3157 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3158 ConvertedType = ToType;
3159 return true;
3160 }
3161
3162 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3163 if (!ToTypePtr)
3164 return false;
3165
3166 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3167 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3168 ConvertedType = ToType;
3169 return true;
3170 }
3171
3172 // Beyond this point, both types need to be pointers
3173 // , including objective-c pointers.
3174 QualType ToPointeeType = ToTypePtr->getPointeeType();
3175 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3176 !getLangOpts().ObjCAutoRefCount) {
3177 ConvertedType = BuildSimilarlyQualifiedPointerType(
3178 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3179 Context);
3180 return true;
3181 }
3182 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3183 if (!FromTypePtr)
3184 return false;
3185
3186 QualType FromPointeeType = FromTypePtr->getPointeeType();
3187
3188 // If the unqualified pointee types are the same, this can't be a
3189 // pointer conversion, so don't do all of the work below.
3190 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3191 return false;
3192
3193 // An rvalue of type "pointer to cv T," where T is an object type,
3194 // can be converted to an rvalue of type "pointer to cv void" (C++
3195 // 4.10p2).
3196 if (FromPointeeType->isIncompleteOrObjectType() &&
3197 ToPointeeType->isVoidType()) {
3198 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3199 ToPointeeType,
3200 ToType, Context,
3201 /*StripObjCLifetime=*/true);
3202 return true;
3203 }
3204
3205 // MSVC allows implicit function to void* type conversion.
3206 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3207 ToPointeeType->isVoidType()) {
3208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3209 ToPointeeType,
3210 ToType, Context);
3211 return true;
3212 }
3213
3214 // When we're overloading in C, we allow a special kind of pointer
3215 // conversion for compatible-but-not-identical pointee types.
3216 if (!getLangOpts().CPlusPlus &&
3217 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3219 ToPointeeType,
3220 ToType, Context);
3221 return true;
3222 }
3223
3224 // C++ [conv.ptr]p3:
3225 //
3226 // An rvalue of type "pointer to cv D," where D is a class type,
3227 // can be converted to an rvalue of type "pointer to cv B," where
3228 // B is a base class (clause 10) of D. If B is an inaccessible
3229 // (clause 11) or ambiguous (10.2) base class of D, a program that
3230 // necessitates this conversion is ill-formed. The result of the
3231 // conversion is a pointer to the base class sub-object of the
3232 // derived class object. The null pointer value is converted to
3233 // the null pointer value of the destination type.
3234 //
3235 // Note that we do not check for ambiguity or inaccessibility
3236 // here. That is handled by CheckPointerConversion.
3237 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3238 ToPointeeType->isRecordType() &&
3239 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3240 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3241 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3242 ToPointeeType,
3243 ToType, Context);
3244 return true;
3245 }
3246
3247 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3248 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3249 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3250 ToPointeeType,
3251 ToType, Context);
3252 return true;
3253 }
3254
3255 return false;
3256}
3257
3258/// Adopt the given qualifiers for the given type.
3260 Qualifiers TQs = T.getQualifiers();
3261
3262 // Check whether qualifiers already match.
3263 if (TQs == Qs)
3264 return T;
3265
3266 if (Qs.compatiblyIncludes(TQs, Context))
3267 return Context.getQualifiedType(T, Qs);
3268
3269 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3270}
3271
3273 QualType& ConvertedType,
3274 bool &IncompatibleObjC) {
3275 if (!getLangOpts().ObjC)
3276 return false;
3277
3278 // The set of qualifiers on the type we're converting from.
3279 Qualifiers FromQualifiers = FromType.getQualifiers();
3280
3281 // First, we handle all conversions on ObjC object pointer types.
3282 const ObjCObjectPointerType* ToObjCPtr =
3283 ToType->getAs<ObjCObjectPointerType>();
3284 const ObjCObjectPointerType *FromObjCPtr =
3285 FromType->getAs<ObjCObjectPointerType>();
3286
3287 if (ToObjCPtr && FromObjCPtr) {
3288 // If the pointee types are the same (ignoring qualifications),
3289 // then this is not a pointer conversion.
3290 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3291 FromObjCPtr->getPointeeType()))
3292 return false;
3293
3294 // Conversion between Objective-C pointers.
3295 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3296 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3297 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3298 if (getLangOpts().CPlusPlus && LHS && RHS &&
3300 FromObjCPtr->getPointeeType(), getASTContext()))
3301 return false;
3302 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3303 ToObjCPtr->getPointeeType(),
3304 ToType, Context);
3305 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3306 return true;
3307 }
3308
3309 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3310 // Okay: this is some kind of implicit downcast of Objective-C
3311 // interfaces, which is permitted. However, we're going to
3312 // complain about it.
3313 IncompatibleObjC = true;
3314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3315 ToObjCPtr->getPointeeType(),
3316 ToType, Context);
3317 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3318 return true;
3319 }
3320 }
3321 // Beyond this point, both types need to be C pointers or block pointers.
3322 QualType ToPointeeType;
3323 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3324 ToPointeeType = ToCPtr->getPointeeType();
3325 else if (const BlockPointerType *ToBlockPtr =
3326 ToType->getAs<BlockPointerType>()) {
3327 // Objective C++: We're able to convert from a pointer to any object
3328 // to a block pointer type.
3329 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3330 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3331 return true;
3332 }
3333 ToPointeeType = ToBlockPtr->getPointeeType();
3334 }
3335 else if (FromType->getAs<BlockPointerType>() &&
3336 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3337 // Objective C++: We're able to convert from a block pointer type to a
3338 // pointer to any object.
3339 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3340 return true;
3341 }
3342 else
3343 return false;
3344
3345 QualType FromPointeeType;
3346 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3347 FromPointeeType = FromCPtr->getPointeeType();
3348 else if (const BlockPointerType *FromBlockPtr =
3349 FromType->getAs<BlockPointerType>())
3350 FromPointeeType = FromBlockPtr->getPointeeType();
3351 else
3352 return false;
3353
3354 // If we have pointers to pointers, recursively check whether this
3355 // is an Objective-C conversion.
3356 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3357 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3358 IncompatibleObjC)) {
3359 // We always complain about this conversion.
3360 IncompatibleObjC = true;
3361 ConvertedType = Context.getPointerType(ConvertedType);
3362 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3363 return true;
3364 }
3365 // Allow conversion of pointee being objective-c pointer to another one;
3366 // as in I* to id.
3367 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3368 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3369 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3370 IncompatibleObjC)) {
3371
3372 ConvertedType = Context.getPointerType(ConvertedType);
3373 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3374 return true;
3375 }
3376
3377 // If we have pointers to functions or blocks, check whether the only
3378 // differences in the argument and result types are in Objective-C
3379 // pointer conversions. If so, we permit the conversion (but
3380 // complain about it).
3381 const FunctionProtoType *FromFunctionType
3382 = FromPointeeType->getAs<FunctionProtoType>();
3383 const FunctionProtoType *ToFunctionType
3384 = ToPointeeType->getAs<FunctionProtoType>();
3385 if (FromFunctionType && ToFunctionType) {
3386 // If the function types are exactly the same, this isn't an
3387 // Objective-C pointer conversion.
3388 if (Context.getCanonicalType(FromPointeeType)
3389 == Context.getCanonicalType(ToPointeeType))
3390 return false;
3391
3392 // Perform the quick checks that will tell us whether these
3393 // function types are obviously different.
3394 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3395 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3396 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3397 return false;
3398
3399 bool HasObjCConversion = false;
3400 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3401 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3402 // Okay, the types match exactly. Nothing to do.
3403 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3404 ToFunctionType->getReturnType(),
3405 ConvertedType, IncompatibleObjC)) {
3406 // Okay, we have an Objective-C pointer conversion.
3407 HasObjCConversion = true;
3408 } else {
3409 // Function types are too different. Abort.
3410 return false;
3411 }
3412
3413 // Check argument types.
3414 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3415 ArgIdx != NumArgs; ++ArgIdx) {
3416 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3417 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3418 if (Context.getCanonicalType(FromArgType)
3419 == Context.getCanonicalType(ToArgType)) {
3420 // Okay, the types match exactly. Nothing to do.
3421 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3422 ConvertedType, IncompatibleObjC)) {
3423 // Okay, we have an Objective-C pointer conversion.
3424 HasObjCConversion = true;
3425 } else {
3426 // Argument types are too different. Abort.
3427 return false;
3428 }
3429 }
3430
3431 if (HasObjCConversion) {
3432 // We had an Objective-C conversion. Allow this pointer
3433 // conversion, but complain about it.
3434 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3435 IncompatibleObjC = true;
3436 return true;
3437 }
3438 }
3439
3440 return false;
3441}
3442
3444 QualType& ConvertedType) {
3445 QualType ToPointeeType;
3446 if (const BlockPointerType *ToBlockPtr =
3447 ToType->getAs<BlockPointerType>())
3448 ToPointeeType = ToBlockPtr->getPointeeType();
3449 else
3450 return false;
3451
3452 QualType FromPointeeType;
3453 if (const BlockPointerType *FromBlockPtr =
3454 FromType->getAs<BlockPointerType>())
3455 FromPointeeType = FromBlockPtr->getPointeeType();
3456 else
3457 return false;
3458 // We have pointer to blocks, check whether the only
3459 // differences in the argument and result types are in Objective-C
3460 // pointer conversions. If so, we permit the conversion.
3461
3462 const FunctionProtoType *FromFunctionType
3463 = FromPointeeType->getAs<FunctionProtoType>();
3464 const FunctionProtoType *ToFunctionType
3465 = ToPointeeType->getAs<FunctionProtoType>();
3466
3467 if (!FromFunctionType || !ToFunctionType)
3468 return false;
3469
3470 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3471 return true;
3472
3473 // Perform the quick checks that will tell us whether these
3474 // function types are obviously different.
3475 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3476 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3477 return false;
3478
3479 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3480 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3481 if (FromEInfo != ToEInfo)
3482 return false;
3483
3484 bool IncompatibleObjC = false;
3485 if (Context.hasSameType(FromFunctionType->getReturnType(),
3486 ToFunctionType->getReturnType())) {
3487 // Okay, the types match exactly. Nothing to do.
3488 } else {
3489 QualType RHS = FromFunctionType->getReturnType();
3490 QualType LHS = ToFunctionType->getReturnType();
3491 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3492 !RHS.hasQualifiers() && LHS.hasQualifiers())
3493 LHS = LHS.getUnqualifiedType();
3494
3495 if (Context.hasSameType(RHS,LHS)) {
3496 // OK exact match.
3497 } else if (isObjCPointerConversion(RHS, LHS,
3498 ConvertedType, IncompatibleObjC)) {
3499 if (IncompatibleObjC)
3500 return false;
3501 // Okay, we have an Objective-C pointer conversion.
3502 }
3503 else
3504 return false;
3505 }
3506
3507 // Check argument types.
3508 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3509 ArgIdx != NumArgs; ++ArgIdx) {
3510 IncompatibleObjC = false;
3511 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3512 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3513 if (Context.hasSameType(FromArgType, ToArgType)) {
3514 // Okay, the types match exactly. Nothing to do.
3515 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3516 ConvertedType, IncompatibleObjC)) {
3517 if (IncompatibleObjC)
3518 return false;
3519 // Okay, we have an Objective-C pointer conversion.
3520 } else
3521 // Argument types are too different. Abort.
3522 return false;
3523 }
3524
3526 bool CanUseToFPT, CanUseFromFPT;
3527 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3528 CanUseToFPT, CanUseFromFPT,
3529 NewParamInfos))
3530 return false;
3531
3532 ConvertedType = ToType;
3533 return true;
3534}
3535
3536enum {
3544};
3545
3546/// Attempts to get the FunctionProtoType from a Type. Handles
3547/// MemberFunctionPointers properly.
3549 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3550 return FPT;
3551
3552 if (auto *MPT = FromType->getAs<MemberPointerType>())
3553 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3554
3555 return nullptr;
3556}
3557
3559 QualType FromType, QualType ToType) {
3560 // If either type is not valid, include no extra info.
3561 if (FromType.isNull() || ToType.isNull()) {
3562 PDiag << ft_default;
3563 return;
3564 }
3565
3566 // Get the function type from the pointers.
3567 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3568 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3569 *ToMember = ToType->castAs<MemberPointerType>();
3570 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3571 ToMember->getMostRecentCXXRecordDecl())) {
3573 if (ToMember->isSugared())
3574 PDiag << Context.getCanonicalTagType(
3575 ToMember->getMostRecentCXXRecordDecl());
3576 else
3577 PDiag << ToMember->getQualifier();
3578 if (FromMember->isSugared())
3579 PDiag << Context.getCanonicalTagType(
3580 FromMember->getMostRecentCXXRecordDecl());
3581 else
3582 PDiag << FromMember->getQualifier();
3583 return;
3584 }
3585 FromType = FromMember->getPointeeType();
3586 ToType = ToMember->getPointeeType();
3587 }
3588
3589 if (FromType->isPointerType())
3590 FromType = FromType->getPointeeType();
3591 if (ToType->isPointerType())
3592 ToType = ToType->getPointeeType();
3593
3594 // Remove references.
3595 FromType = FromType.getNonReferenceType();
3596 ToType = ToType.getNonReferenceType();
3597
3598 // Don't print extra info for non-specialized template functions.
3599 if (FromType->isInstantiationDependentType() &&
3600 !FromType->getAs<TemplateSpecializationType>()) {
3601 PDiag << ft_default;
3602 return;
3603 }
3604
3605 // No extra info for same types.
3606 if (Context.hasSameType(FromType, ToType)) {
3607 PDiag << ft_default;
3608 return;
3609 }
3610
3611 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3612 *ToFunction = tryGetFunctionProtoType(ToType);
3613
3614 // Both types need to be function types.
3615 if (!FromFunction || !ToFunction) {
3616 PDiag << ft_default;
3617 return;
3618 }
3619
3620 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3621 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3622 << FromFunction->getNumParams();
3623 return;
3624 }
3625
3626 // Handle different parameter types.
3627 unsigned ArgPos;
3628 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3629 PDiag << ft_parameter_mismatch << ArgPos + 1
3630 << ToFunction->getParamType(ArgPos)
3631 << FromFunction->getParamType(ArgPos);
3632 return;
3633 }
3634
3635 // Handle different return type.
3636 if (!Context.hasSameType(FromFunction->getReturnType(),
3637 ToFunction->getReturnType())) {
3638 PDiag << ft_return_type << ToFunction->getReturnType()
3639 << FromFunction->getReturnType();
3640 return;
3641 }
3642
3643 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3644 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3645 << FromFunction->getMethodQuals();
3646 return;
3647 }
3648
3649 // Handle exception specification differences on canonical type (in C++17
3650 // onwards).
3652 ->isNothrow() !=
3653 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3654 ->isNothrow()) {
3655 PDiag << ft_noexcept;
3656 return;
3657 }
3658
3659 // Unable to find a difference, so add no extra info.
3660 PDiag << ft_default;
3661}
3662
3664 ArrayRef<QualType> New, unsigned *ArgPos,
3665 bool Reversed) {
3666 assert(llvm::size(Old) == llvm::size(New) &&
3667 "Can't compare parameters of functions with different number of "
3668 "parameters!");
3669
3670 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3671 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3672 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3673
3674 // Ignore address spaces in pointee type. This is to disallow overloading
3675 // on __ptr32/__ptr64 address spaces.
3676 QualType OldType =
3677 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3678 QualType NewType =
3679 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3680
3681 if (!Context.hasSameType(OldType, NewType)) {
3682 if (ArgPos)
3683 *ArgPos = Idx;
3684 return false;
3685 }
3686 }
3687 return true;
3688}
3689
3691 const FunctionProtoType *NewType,
3692 unsigned *ArgPos, bool Reversed) {
3693 return FunctionParamTypesAreEqual(OldType->param_types(),
3694 NewType->param_types(), ArgPos, Reversed);
3695}
3696
3698 const FunctionDecl *NewFunction,
3699 unsigned *ArgPos,
3700 bool Reversed) {
3701
3702 if (OldFunction->getNumNonObjectParams() !=
3703 NewFunction->getNumNonObjectParams())
3704 return false;
3705
3706 unsigned OldIgnore =
3708 unsigned NewIgnore =
3710
3711 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3712 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3713
3714 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3715 NewPT->param_types().slice(NewIgnore),
3716 ArgPos, Reversed);
3717}
3718
3720 CastKind &Kind,
3721 CXXCastPath& BasePath,
3722 bool IgnoreBaseAccess,
3723 bool Diagnose) {
3724 QualType FromType = From->getType();
3725 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3726
3727 Kind = CK_BitCast;
3728
3729 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3732 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3733 DiagRuntimeBehavior(From->getExprLoc(), From,
3734 PDiag(diag::warn_impcast_bool_to_null_pointer)
3735 << ToType << From->getSourceRange());
3736 else if (!isUnevaluatedContext())
3737 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3738 << ToType << From->getSourceRange();
3739 }
3740 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3741 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3742 QualType FromPointeeType = FromPtrType->getPointeeType(),
3743 ToPointeeType = ToPtrType->getPointeeType();
3744
3745 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3746 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3747 // We must have a derived-to-base conversion. Check an
3748 // ambiguous or inaccessible conversion.
3749 unsigned InaccessibleID = 0;
3750 unsigned AmbiguousID = 0;
3751 if (Diagnose) {
3752 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3753 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3754 }
3756 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3757 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3758 &BasePath, IgnoreBaseAccess))
3759 return true;
3760
3761 // The conversion was successful.
3762 Kind = CK_DerivedToBase;
3763 }
3764
3765 if (Diagnose && !IsCStyleOrFunctionalCast &&
3766 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3767 assert(getLangOpts().MSVCCompat &&
3768 "this should only be possible with MSVCCompat!");
3769 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3770 << From->getSourceRange();
3771 }
3772 }
3773 } else if (const ObjCObjectPointerType *ToPtrType =
3774 ToType->getAs<ObjCObjectPointerType>()) {
3775 if (const ObjCObjectPointerType *FromPtrType =
3776 FromType->getAs<ObjCObjectPointerType>()) {
3777 // Objective-C++ conversions are always okay.
3778 // FIXME: We should have a different class of conversions for the
3779 // Objective-C++ implicit conversions.
3780 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3781 return false;
3782 } else if (FromType->isBlockPointerType()) {
3783 Kind = CK_BlockPointerToObjCPointerCast;
3784 } else {
3785 Kind = CK_CPointerToObjCPointerCast;
3786 }
3787 } else if (ToType->isBlockPointerType()) {
3788 if (!FromType->isBlockPointerType())
3789 Kind = CK_AnyPointerToBlockPointerCast;
3790 }
3791
3792 // We shouldn't fall into this case unless it's valid for other
3793 // reasons.
3795 Kind = CK_NullToPointer;
3796
3797 return false;
3798}
3799
3801 QualType ToType,
3802 bool InOverloadResolution,
3803 QualType &ConvertedType) {
3804 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3805 if (!ToTypePtr)
3806 return false;
3807
3808 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3810 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3812 ConvertedType = ToType;
3813 return true;
3814 }
3815
3816 // Otherwise, both types have to be member pointers.
3817 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3818 if (!FromTypePtr)
3819 return false;
3820
3821 // A pointer to member of B can be converted to a pointer to member of D,
3822 // where D is derived from B (C++ 4.11p2).
3823 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3824 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3825
3826 if (!declaresSameEntity(FromClass, ToClass) &&
3827 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3828 ConvertedType = Context.getMemberPointerType(
3829 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3830 return true;
3831 }
3832
3833 return false;
3834}
3835
3837 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3838 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3839 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3840 // Lock down the inheritance model right now in MS ABI, whether or not the
3841 // pointee types are the same.
3842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3843 (void)isCompleteType(CheckLoc, FromType);
3844 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3845 }
3846
3847 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3848 if (!FromPtrType) {
3849 // This must be a null pointer to member pointer conversion
3850 Kind = CK_NullToMemberPointer;
3852 }
3853
3854 // T == T, modulo cv
3856 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3857 ToPtrType->getPointeeType()))
3859
3860 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3861 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3862
3863 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3864 const CXXRecordDecl *Cls) {
3865 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3866 PD << Qual;
3867 else
3868 PD << Context.getCanonicalTagType(Cls);
3869 };
3870 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3871 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3872 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3873 return PD;
3874 };
3875
3876 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3878 std::swap(Base, Derived);
3879
3880 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3881 /*DetectVirtual=*/true);
3882 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3884
3885 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3886 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3887 PD << int(Direction);
3888 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3889 Diag(CheckLoc, PD);
3891 }
3892
3893 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3894 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3895 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3896 Diag(CheckLoc, PD);
3898 }
3899
3900 // Must be a base to derived member conversion.
3901 BuildBasePathArray(Paths, BasePath);
3903 ? CK_DerivedToBaseMemberPointer
3904 : CK_BaseToDerivedMemberPointer;
3905
3906 if (!IgnoreBaseAccess)
3907 switch (CheckBaseClassAccess(
3908 CheckLoc, Base, Derived, Paths.front(),
3910 ? diag::err_upcast_to_inaccessible_base
3911 : diag::err_downcast_from_inaccessible_base,
3912 [&](PartialDiagnostic &PD) {
3913 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3914 DerivedQual = ToPtrType->getQualifier();
3915 if (Direction == MemberPointerConversionDirection::Upcast)
3916 std::swap(BaseQual, DerivedQual);
3917 DiagCls(PD, DerivedQual, Derived);
3918 DiagCls(PD, BaseQual, Base);
3919 })) {
3921 case Sema::AR_delayed:
3922 case Sema::AR_dependent:
3923 // Optimistically assume that the delayed and dependent cases
3924 // will work out.
3925 break;
3926
3929 }
3930
3932}
3933
3934/// Determine whether the lifetime conversion between the two given
3935/// qualifiers sets is nontrivial.
3937 Qualifiers ToQuals) {
3938 // Converting anything to const __unsafe_unretained is trivial.
3939 if (ToQuals.hasConst() &&
3941 return false;
3942
3943 return true;
3944}
3945
3946/// Perform a single iteration of the loop for checking if a qualification
3947/// conversion is valid.
3948///
3949/// Specifically, check whether any change between the qualifiers of \p
3950/// FromType and \p ToType is permissible, given knowledge about whether every
3951/// outer layer is const-qualified.
3953 bool CStyle, bool IsTopLevel,
3954 bool &PreviousToQualsIncludeConst,
3955 bool &ObjCLifetimeConversion,
3956 const ASTContext &Ctx) {
3957 Qualifiers FromQuals = FromType.getQualifiers();
3958 Qualifiers ToQuals = ToType.getQualifiers();
3959
3960 // Ignore __unaligned qualifier.
3961 FromQuals.removeUnaligned();
3962
3963 // Objective-C ARC:
3964 // Check Objective-C lifetime conversions.
3965 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3966 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3967 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3968 ObjCLifetimeConversion = true;
3969 FromQuals.removeObjCLifetime();
3970 ToQuals.removeObjCLifetime();
3971 } else {
3972 // Qualification conversions cannot cast between different
3973 // Objective-C lifetime qualifiers.
3974 return false;
3975 }
3976 }
3977
3978 // Allow addition/removal of GC attributes but not changing GC attributes.
3979 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3980 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3981 FromQuals.removeObjCGCAttr();
3982 ToQuals.removeObjCGCAttr();
3983 }
3984
3985 // __ptrauth qualifiers must match exactly.
3986 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3987 return false;
3988
3989 // -- for every j > 0, if const is in cv 1,j then const is in cv
3990 // 2,j, and similarly for volatile.
3991 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3992 return false;
3993
3994 // If address spaces mismatch:
3995 // - in top level it is only valid to convert to addr space that is a
3996 // superset in all cases apart from C-style casts where we allow
3997 // conversions between overlapping address spaces.
3998 // - in non-top levels it is not a valid conversion.
3999 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
4000 (!IsTopLevel ||
4001 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
4002 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
4003 return false;
4004
4005 // -- if the cv 1,j and cv 2,j are different, then const is in
4006 // every cv for 0 < k < j.
4007 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
4008 !PreviousToQualsIncludeConst)
4009 return false;
4010
4011 // The following wording is from C++20, where the result of the conversion
4012 // is T3, not T2.
4013 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
4014 // "array of unknown bound of"
4015 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
4016 return false;
4017
4018 // -- if the resulting P3,i is different from P1,i [...], then const is
4019 // added to every cv 3_k for 0 < k < i.
4020 if (!CStyle && FromType->isConstantArrayType() &&
4021 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
4022 return false;
4023
4024 // Keep track of whether all prior cv-qualifiers in the "to" type
4025 // include const.
4026 PreviousToQualsIncludeConst =
4027 PreviousToQualsIncludeConst && ToQuals.hasConst();
4028 return true;
4029}
4030
4031bool
4033 bool CStyle, bool &ObjCLifetimeConversion) {
4034 FromType = Context.getCanonicalType(FromType);
4035 ToType = Context.getCanonicalType(ToType);
4036 ObjCLifetimeConversion = false;
4037
4038 // If FromType and ToType are the same type, this is not a
4039 // qualification conversion.
4040 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
4041 return false;
4042
4043 // (C++ 4.4p4):
4044 // A conversion can add cv-qualifiers at levels other than the first
4045 // in multi-level pointers, subject to the following rules: [...]
4046 bool PreviousToQualsIncludeConst = true;
4047 bool UnwrappedAnyPointer = false;
4048 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
4049 if (!isQualificationConversionStep(FromType, ToType, CStyle,
4050 !UnwrappedAnyPointer,
4051 PreviousToQualsIncludeConst,
4052 ObjCLifetimeConversion, getASTContext()))
4053 return false;
4054 UnwrappedAnyPointer = true;
4055 }
4056
4057 // We are left with FromType and ToType being the pointee types
4058 // after unwrapping the original FromType and ToType the same number
4059 // of times. If we unwrapped any pointers, and if FromType and
4060 // ToType have the same unqualified type (since we checked
4061 // qualifiers above), then this is a qualification conversion.
4062 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
4063}
4064
4065/// - Determine whether this is a conversion from a scalar type to an
4066/// atomic type.
4067///
4068/// If successful, updates \c SCS's second and third steps in the conversion
4069/// sequence to finish the conversion.
4070static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4071 bool InOverloadResolution,
4073 bool CStyle) {
4074 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4075 if (!ToAtomic)
4076 return false;
4077
4079 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4080 InOverloadResolution, InnerSCS,
4081 CStyle, /*AllowObjCWritebackConversion=*/false))
4082 return false;
4083
4084 SCS.Second = InnerSCS.Second;
4085 SCS.setToType(1, InnerSCS.getToType(1));
4086 SCS.Third = InnerSCS.Third;
4089 SCS.setToType(2, InnerSCS.getToType(2));
4090 return true;
4091}
4092
4094 QualType ToType,
4095 bool InOverloadResolution,
4097 bool CStyle) {
4098 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4099 if (!ToOBT)
4100 return false;
4101
4102 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4103 QualType FromType = From->getType();
4104 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4105 return false;
4106
4108 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4109 InOverloadResolution, InnerSCS, CStyle,
4110 /*AllowObjCWritebackConversion=*/false))
4111 return false;
4112
4113 SCS.Second = InnerSCS.Second;
4114 SCS.setToType(1, InnerSCS.getToType(1));
4115 SCS.Third = InnerSCS.Third;
4118 SCS.setToType(2, InnerSCS.getToType(2));
4119 return true;
4120}
4121
4124 QualType Type) {
4125 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4126 if (CtorType->getNumParams() > 0) {
4127 QualType FirstArg = CtorType->getParamType(0);
4128 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4129 return true;
4130 }
4131 return false;
4132}
4133
4134static OverloadingResult
4136 CXXRecordDecl *To,
4138 OverloadCandidateSet &CandidateSet,
4139 bool AllowExplicit) {
4141 for (auto *D : S.LookupConstructors(To)) {
4142 auto Info = getConstructorInfo(D);
4143 if (!Info)
4144 continue;
4145
4146 bool Usable = !Info.Constructor->isInvalidDecl() &&
4147 S.isInitListConstructor(Info.Constructor);
4148 if (Usable) {
4149 bool SuppressUserConversions = false;
4150 if (Info.ConstructorTmpl)
4151 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4152 /*ExplicitArgs*/ nullptr, From,
4153 CandidateSet, SuppressUserConversions,
4154 /*PartialOverloading*/ false,
4155 AllowExplicit);
4156 else
4157 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4158 CandidateSet, SuppressUserConversions,
4159 /*PartialOverloading*/ false, AllowExplicit);
4160 }
4161 }
4162
4163 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4164
4166 switch (auto Result =
4167 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4168 case OR_Deleted:
4169 case OR_Success: {
4170 // Record the standard conversion we used and the conversion function.
4172 QualType ThisType = Constructor->getFunctionObjectParameterType();
4173 // Initializer lists don't have conversions as such.
4175 User.HadMultipleCandidates = HadMultipleCandidates;
4177 User.FoundConversionFunction = Best->FoundDecl;
4179 User.After.setFromType(ThisType);
4180 User.After.setAllToTypes(ToType);
4181 return Result;
4182 }
4183
4185 return OR_No_Viable_Function;
4186 case OR_Ambiguous:
4187 return OR_Ambiguous;
4188 }
4189
4190 llvm_unreachable("Invalid OverloadResult!");
4191}
4192
4193/// Determines whether there is a user-defined conversion sequence
4194/// (C++ [over.ics.user]) that converts expression From to the type
4195/// ToType. If such a conversion exists, User will contain the
4196/// user-defined conversion sequence that performs such a conversion
4197/// and this routine will return true. Otherwise, this routine returns
4198/// false and User is unspecified.
4199///
4200/// \param AllowExplicit true if the conversion should consider C++0x
4201/// "explicit" conversion functions as well as non-explicit conversion
4202/// functions (C++0x [class.conv.fct]p2).
4203///
4204/// \param AllowObjCConversionOnExplicit true if the conversion should
4205/// allow an extra Objective-C pointer conversion on uses of explicit
4206/// constructors. Requires \c AllowExplicit to also be set.
4207static OverloadingResult
4210 OverloadCandidateSet &CandidateSet,
4211 AllowedExplicit AllowExplicit,
4212 bool AllowObjCConversionOnExplicit) {
4213 assert(AllowExplicit != AllowedExplicit::None ||
4214 !AllowObjCConversionOnExplicit);
4216
4217 // Whether we will only visit constructors.
4218 bool ConstructorsOnly = false;
4219
4220 // If the type we are conversion to is a class type, enumerate its
4221 // constructors.
4222 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4223 // C++ [over.match.ctor]p1:
4224 // When objects of class type are direct-initialized (8.5), or
4225 // copy-initialized from an expression of the same or a
4226 // derived class type (8.5), overload resolution selects the
4227 // constructor. [...] For copy-initialization, the candidate
4228 // functions are all the converting constructors (12.3.1) of
4229 // that class. The argument list is the expression-list within
4230 // the parentheses of the initializer.
4231 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4232 (From->getType()->isRecordType() &&
4233 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4234 ConstructorsOnly = true;
4235
4236 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4237 // We're not going to find any constructors.
4238 } else if (auto *ToRecordDecl =
4239 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4240 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4241
4242 Expr **Args = &From;
4243 unsigned NumArgs = 1;
4244 bool ListInitializing = false;
4245 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4246 // But first, see if there is an init-list-constructor that will work.
4248 S, From, ToType, ToRecordDecl, User, CandidateSet,
4249 AllowExplicit == AllowedExplicit::All);
4251 return Result;
4252 // Never mind.
4253 CandidateSet.clear(
4255
4256 // If we're list-initializing, we pass the individual elements as
4257 // arguments, not the entire list.
4258 Args = InitList->getInits();
4259 NumArgs = InitList->getNumInits();
4260 ListInitializing = true;
4261 }
4262
4263 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4264 auto Info = getConstructorInfo(D);
4265 if (!Info)
4266 continue;
4267
4268 bool Usable = !Info.Constructor->isInvalidDecl();
4269 if (!ListInitializing)
4270 Usable = Usable && Info.Constructor->isConvertingConstructor(
4271 /*AllowExplicit*/ true);
4272 if (Usable) {
4273 bool SuppressUserConversions = !ConstructorsOnly;
4274 // C++20 [over.best.ics.general]/4.5:
4275 // if the target is the first parameter of a constructor [of class
4276 // X] and the constructor [...] is a candidate by [...] the second
4277 // phase of [over.match.list] when the initializer list has exactly
4278 // one element that is itself an initializer list, [...] and the
4279 // conversion is to X or reference to cv X, user-defined conversion
4280 // sequences are not considered.
4281 if (SuppressUserConversions && ListInitializing) {
4282 SuppressUserConversions =
4283 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4284 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4285 ToType);
4286 }
4287 if (Info.ConstructorTmpl)
4289 Info.ConstructorTmpl, Info.FoundDecl,
4290 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4291 CandidateSet, SuppressUserConversions,
4292 /*PartialOverloading*/ false,
4293 AllowExplicit == AllowedExplicit::All);
4294 else
4295 // Allow one user-defined conversion when user specifies a
4296 // From->ToType conversion via an static cast (c-style, etc).
4297 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4298 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4299 SuppressUserConversions,
4300 /*PartialOverloading*/ false,
4301 AllowExplicit == AllowedExplicit::All);
4302 }
4303 }
4304 }
4305 }
4306
4307 // Enumerate conversion functions, if we're allowed to.
4308 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4309 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4310 // No conversion functions from incomplete types.
4311 } else if (const RecordType *FromRecordType =
4312 From->getType()->getAsCanonical<RecordType>()) {
4313 if (auto *FromRecordDecl =
4314 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4315 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4316 // Add all of the conversion functions as candidates.
4317 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4318 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4319 DeclAccessPair FoundDecl = I.getPair();
4320 NamedDecl *D = FoundDecl.getDecl();
4321 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4322 if (isa<UsingShadowDecl>(D))
4323 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4324
4325 CXXConversionDecl *Conv;
4326 FunctionTemplateDecl *ConvTemplate;
4327 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4328 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4329 else
4330 Conv = cast<CXXConversionDecl>(D);
4331
4332 if (ConvTemplate)
4334 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4335 CandidateSet, AllowObjCConversionOnExplicit,
4336 AllowExplicit != AllowedExplicit::None);
4337 else
4338 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4339 CandidateSet, AllowObjCConversionOnExplicit,
4340 AllowExplicit != AllowedExplicit::None);
4341 }
4342 }
4343 }
4344
4345 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4346
4348 switch (auto Result =
4349 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4350 case OR_Success:
4351 case OR_Deleted:
4352 // Record the standard conversion we used and the conversion function.
4354 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4355 // C++ [over.ics.user]p1:
4356 // If the user-defined conversion is specified by a
4357 // constructor (12.3.1), the initial standard conversion
4358 // sequence converts the source type to the type required by
4359 // the argument of the constructor.
4360 //
4361 if (isa<InitListExpr>(From)) {
4362 // Initializer lists don't have conversions as such.
4364 User.Before.FromBracedInitList = true;
4365 } else {
4366 if (Best->Conversions[0].isEllipsis())
4367 User.EllipsisConversion = true;
4368 else {
4369 User.Before = Best->Conversions[0].Standard;
4370 User.EllipsisConversion = false;
4371 }
4372 }
4373 User.HadMultipleCandidates = HadMultipleCandidates;
4375 User.FoundConversionFunction = Best->FoundDecl;
4377 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4378 User.After.setAllToTypes(ToType);
4379 return Result;
4380 }
4381 if (CXXConversionDecl *Conversion
4382 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4383
4384 assert(Best->HasFinalConversion);
4385
4386 // C++ [over.ics.user]p1:
4387 //
4388 // [...] If the user-defined conversion is specified by a
4389 // conversion function (12.3.2), the initial standard
4390 // conversion sequence converts the source type to the
4391 // implicit object parameter of the conversion function.
4392 User.Before = Best->Conversions[0].Standard;
4393 User.HadMultipleCandidates = HadMultipleCandidates;
4394 User.ConversionFunction = Conversion;
4395 User.FoundConversionFunction = Best->FoundDecl;
4396 User.EllipsisConversion = false;
4397
4398 // C++ [over.ics.user]p2:
4399 // The second standard conversion sequence converts the
4400 // result of the user-defined conversion to the target type
4401 // for the sequence. Since an implicit conversion sequence
4402 // is an initialization, the special rules for
4403 // initialization by user-defined conversion apply when
4404 // selecting the best user-defined conversion for a
4405 // user-defined conversion sequence (see 13.3.3 and
4406 // 13.3.3.1).
4407 User.After = Best->FinalConversion;
4408 return Result;
4409 }
4410 llvm_unreachable("Not a constructor or conversion function?");
4411
4413 return OR_No_Viable_Function;
4414
4415 case OR_Ambiguous:
4416 return OR_Ambiguous;
4417 }
4418
4419 llvm_unreachable("Invalid OverloadResult!");
4420}
4421
4422bool
4425 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4427 OverloadingResult OvResult =
4428 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4429 CandidateSet, AllowedExplicit::None, false);
4430
4431 if (!(OvResult == OR_Ambiguous ||
4432 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4433 return false;
4434
4435 auto Cands = CandidateSet.CompleteCandidates(
4436 *this,
4438 From);
4439 if (OvResult == OR_Ambiguous)
4440 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4441 << From->getType() << ToType << From->getSourceRange();
4442 else { // OR_No_Viable_Function && !CandidateSet.empty()
4443 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4444 diag::err_typecheck_nonviable_condition_incomplete,
4445 From->getType(), From->getSourceRange()))
4446 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4447 << false << From->getType() << From->getSourceRange() << ToType;
4448 }
4449
4450 CandidateSet.NoteCandidates(
4451 *this, From, Cands);
4452 return true;
4453}
4454
4455// Helper for compareConversionFunctions that gets the FunctionType that the
4456// conversion-operator return value 'points' to, or nullptr.
4457static const FunctionType *
4459 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4460 const PointerType *RetPtrTy =
4461 ConvFuncTy->getReturnType()->getAs<PointerType>();
4462
4463 if (!RetPtrTy)
4464 return nullptr;
4465
4466 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4467}
4468
4469/// Compare the user-defined conversion functions or constructors
4470/// of two user-defined conversion sequences to determine whether any ordering
4471/// is possible.
4474 FunctionDecl *Function2) {
4475 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4476 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4477 if (!Conv1 || !Conv2)
4479
4480 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4482
4483 // Objective-C++:
4484 // If both conversion functions are implicitly-declared conversions from
4485 // a lambda closure type to a function pointer and a block pointer,
4486 // respectively, always prefer the conversion to a function pointer,
4487 // because the function pointer is more lightweight and is more likely
4488 // to keep code working.
4489 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4490 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4491 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4492 if (Block1 != Block2)
4493 return Block1 ? ImplicitConversionSequence::Worse
4495 }
4496
4497 // In order to support multiple calling conventions for the lambda conversion
4498 // operator (such as when the free and member function calling convention is
4499 // different), prefer the 'free' mechanism, followed by the calling-convention
4500 // of operator(). The latter is in place to support the MSVC-like solution of
4501 // defining ALL of the possible conversions in regards to calling-convention.
4502 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4503 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4504
4505 if (Conv1FuncRet && Conv2FuncRet &&
4506 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4507 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4508 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4509
4510 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4511 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4512
4513 CallingConv CallOpCC =
4514 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4516 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4518 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4519
4520 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4521 for (CallingConv CC : PrefOrder) {
4522 if (Conv1CC == CC)
4524 if (Conv2CC == CC)
4526 }
4527 }
4528
4530}
4531
4538
4539/// CompareImplicitConversionSequences - Compare two implicit
4540/// conversion sequences to determine whether one is better than the
4541/// other or if they are indistinguishable (C++ 13.3.3.2).
4544 const ImplicitConversionSequence& ICS1,
4545 const ImplicitConversionSequence& ICS2)
4546{
4547 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4548 // conversion sequences (as defined in 13.3.3.1)
4549 // -- a standard conversion sequence (13.3.3.1.1) is a better
4550 // conversion sequence than a user-defined conversion sequence or
4551 // an ellipsis conversion sequence, and
4552 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4553 // conversion sequence than an ellipsis conversion sequence
4554 // (13.3.3.1.3).
4555 //
4556 // C++0x [over.best.ics]p10:
4557 // For the purpose of ranking implicit conversion sequences as
4558 // described in 13.3.3.2, the ambiguous conversion sequence is
4559 // treated as a user-defined sequence that is indistinguishable
4560 // from any other user-defined conversion sequence.
4561
4562 // String literal to 'char *' conversion has been deprecated in C++03. It has
4563 // been removed from C++11. We still accept this conversion, if it happens at
4564 // the best viable function. Otherwise, this conversion is considered worse
4565 // than ellipsis conversion. Consider this as an extension; this is not in the
4566 // standard. For example:
4567 //
4568 // int &f(...); // #1
4569 // void f(char*); // #2
4570 // void g() { int &r = f("foo"); }
4571 //
4572 // In C++03, we pick #2 as the best viable function.
4573 // In C++11, we pick #1 as the best viable function, because ellipsis
4574 // conversion is better than string-literal to char* conversion (since there
4575 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4576 // convert arguments, #2 would be the best viable function in C++11.
4577 // If the best viable function has this conversion, a warning will be issued
4578 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4579
4580 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4583 // Ill-formedness must not differ
4584 ICS1.isBad() == ICS2.isBad())
4588
4589 if (ICS1.getKindRank() < ICS2.getKindRank())
4591 if (ICS2.getKindRank() < ICS1.getKindRank())
4593
4594 // The following checks require both conversion sequences to be of
4595 // the same kind.
4596 if (ICS1.getKind() != ICS2.getKind())
4598
4601
4602 // Two implicit conversion sequences of the same form are
4603 // indistinguishable conversion sequences unless one of the
4604 // following rules apply: (C++ 13.3.3.2p3):
4605
4606 // List-initialization sequence L1 is a better conversion sequence than
4607 // list-initialization sequence L2 if:
4608 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4609 // if not that,
4610 // — L1 and L2 convert to arrays of the same element type, and either the
4611 // number of elements n_1 initialized by L1 is less than the number of
4612 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4613 // an array of unknown bound and L1 does not,
4614 // even if one of the other rules in this paragraph would otherwise apply.
4615 if (!ICS1.isBad()) {
4616 bool StdInit1 = false, StdInit2 = false;
4619 nullptr);
4622 nullptr);
4623 if (StdInit1 != StdInit2)
4624 return StdInit1 ? ImplicitConversionSequence::Better
4626
4629 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4631 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4633 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4634 CAT2->getElementType())) {
4635 // Both to arrays of the same element type
4636 if (CAT1->getSize() != CAT2->getSize())
4637 // Different sized, the smaller wins
4638 return CAT1->getSize().ult(CAT2->getSize())
4643 // One is incomplete, it loses
4647 }
4648 }
4649 }
4650
4651 if (ICS1.isStandard())
4652 // Standard conversion sequence S1 is a better conversion sequence than
4653 // standard conversion sequence S2 if [...]
4655 ICS1.Standard, ICS2.Standard);
4656 else if (ICS1.isUserDefined()) {
4657 // With lazy template loading, it is possible to find non-canonical
4658 // FunctionDecls, depending on when redecl chains are completed. Make sure
4659 // to compare the canonical decls of conversion functions. This avoids
4660 // ambiguity problems for templated conversion operators.
4661 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4662 if (ConvFunc1)
4663 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4664 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4665 if (ConvFunc2)
4666 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4667 // User-defined conversion sequence U1 is a better conversion
4668 // sequence than another user-defined conversion sequence U2 if
4669 // they contain the same user-defined conversion function or
4670 // constructor and if the second standard conversion sequence of
4671 // U1 is better than the second standard conversion sequence of
4672 // U2 (C++ 13.3.3.2p3).
4673 if (ConvFunc1 == ConvFunc2)
4675 ICS1.UserDefined.After,
4676 ICS2.UserDefined.After);
4677 else
4681 }
4682
4683 return Result;
4684}
4685
4686// Per 13.3.3.2p3, compare the given standard conversion sequences to
4687// determine if one is a proper subset of the other.
4690 const StandardConversionSequence& SCS1,
4691 const StandardConversionSequence& SCS2) {
4694
4695 // the identity conversion sequence is considered to be a subsequence of
4696 // any non-identity conversion sequence
4697 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4699 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4701
4702 if (SCS1.Second != SCS2.Second) {
4703 if (SCS1.Second == ICK_Identity)
4705 else if (SCS2.Second == ICK_Identity)
4707 else
4709 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4711
4712 if (SCS1.Third == SCS2.Third) {
4713 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4715 }
4716
4717 if (SCS1.Third == ICK_Identity)
4721
4722 if (SCS2.Third == ICK_Identity)
4726
4728}
4729
4730/// Determine whether one of the given reference bindings is better
4731/// than the other based on what kind of bindings they are.
4732static bool
4734 const StandardConversionSequence &SCS2) {
4735 // C++0x [over.ics.rank]p3b4:
4736 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4737 // implicit object parameter of a non-static member function declared
4738 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4739 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4740 // lvalue reference to a function lvalue and S2 binds an rvalue
4741 // reference*.
4742 //
4743 // FIXME: Rvalue references. We're going rogue with the above edits,
4744 // because the semantics in the current C++0x working paper (N3225 at the
4745 // time of this writing) break the standard definition of std::forward
4746 // and std::reference_wrapper when dealing with references to functions.
4747 // Proposed wording changes submitted to CWG for consideration.
4750 return false;
4751
4752 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4753 SCS2.IsLvalueReference) ||
4756}
4757
4763
4764/// Returns kind of fixed enum promotion the \a SCS uses.
4765static FixedEnumPromotion
4767
4768 if (SCS.Second != ICK_Integral_Promotion)
4770
4771 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4772 if (!Enum)
4774
4775 if (!Enum->isFixed())
4777
4778 QualType UnderlyingType = Enum->getIntegerType();
4779 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4781
4783}
4784
4785/// CompareStandardConversionSequences - Compare two standard
4786/// conversion sequences to determine whether one is better than the
4787/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4790 const StandardConversionSequence& SCS1,
4791 const StandardConversionSequence& SCS2)
4792{
4793 // Standard conversion sequence S1 is a better conversion sequence
4794 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4795
4796 // -- S1 is a proper subsequence of S2 (comparing the conversion
4797 // sequences in the canonical form defined by 13.3.3.1.1,
4798 // excluding any Lvalue Transformation; the identity conversion
4799 // sequence is considered to be a subsequence of any
4800 // non-identity conversion sequence) or, if not that,
4803 return CK;
4804
4805 // -- the rank of S1 is better than the rank of S2 (by the rules
4806 // defined below), or, if not that,
4807 ImplicitConversionRank Rank1 = SCS1.getRank();
4808 ImplicitConversionRank Rank2 = SCS2.getRank();
4809 if (Rank1 < Rank2)
4811 else if (Rank2 < Rank1)
4813
4814 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4815 // are indistinguishable unless one of the following rules
4816 // applies:
4817
4818 // A conversion that is not a conversion of a pointer, or
4819 // pointer to member, to bool is better than another conversion
4820 // that is such a conversion.
4822 return SCS2.isPointerConversionToBool()
4825
4826 // C++14 [over.ics.rank]p4b2:
4827 // This is retroactively applied to C++11 by CWG 1601.
4828 //
4829 // A conversion that promotes an enumeration whose underlying type is fixed
4830 // to its underlying type is better than one that promotes to the promoted
4831 // underlying type, if the two are different.
4834 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4835 FEP1 != FEP2)
4839
4840 // C++ [over.ics.rank]p4b2:
4841 //
4842 // If class B is derived directly or indirectly from class A,
4843 // conversion of B* to A* is better than conversion of B* to
4844 // void*, and conversion of A* to void* is better than conversion
4845 // of B* to void*.
4846 bool SCS1ConvertsToVoid
4848 bool SCS2ConvertsToVoid
4850 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4851 // Exactly one of the conversion sequences is a conversion to
4852 // a void pointer; it's the worse conversion.
4853 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4855 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4856 // Neither conversion sequence converts to a void pointer; compare
4857 // their derived-to-base conversions.
4859 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4860 return DerivedCK;
4861 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4862 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4863 // Both conversion sequences are conversions to void
4864 // pointers. Compare the source types to determine if there's an
4865 // inheritance relationship in their sources.
4866 QualType FromType1 = SCS1.getFromType();
4867 QualType FromType2 = SCS2.getFromType();
4868
4869 // Adjust the types we're converting from via the array-to-pointer
4870 // conversion, if we need to.
4871 if (SCS1.First == ICK_Array_To_Pointer)
4872 FromType1 = S.Context.getArrayDecayedType(FromType1);
4873 if (SCS2.First == ICK_Array_To_Pointer)
4874 FromType2 = S.Context.getArrayDecayedType(FromType2);
4875
4876 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4877 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4878
4879 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4881 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4883
4884 // Objective-C++: If one interface is more specific than the
4885 // other, it is the better one.
4886 const ObjCObjectPointerType* FromObjCPtr1
4887 = FromType1->getAs<ObjCObjectPointerType>();
4888 const ObjCObjectPointerType* FromObjCPtr2
4889 = FromType2->getAs<ObjCObjectPointerType>();
4890 if (FromObjCPtr1 && FromObjCPtr2) {
4891 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4892 FromObjCPtr2);
4893 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4894 FromObjCPtr1);
4895 if (AssignLeft != AssignRight) {
4896 return AssignLeft? ImplicitConversionSequence::Better
4898 }
4899 }
4900 }
4901
4902 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4903 // Check for a better reference binding based on the kind of bindings.
4904 if (isBetterReferenceBindingKind(SCS1, SCS2))
4906 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4908 }
4909
4910 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4911 // bullet 3).
4913 = CompareQualificationConversions(S, SCS1, SCS2))
4914 return QualCK;
4915
4918 return ObtCK;
4919
4920 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4921 // C++ [over.ics.rank]p3b4:
4922 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4923 // which the references refer are the same type except for
4924 // top-level cv-qualifiers, and the type to which the reference
4925 // initialized by S2 refers is more cv-qualified than the type
4926 // to which the reference initialized by S1 refers.
4927 QualType T1 = SCS1.getToType(2);
4928 QualType T2 = SCS2.getToType(2);
4929 T1 = S.Context.getCanonicalType(T1);
4930 T2 = S.Context.getCanonicalType(T2);
4931 Qualifiers T1Quals, T2Quals;
4932 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4933 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4934 if (UnqualT1 == UnqualT2) {
4935 // Objective-C++ ARC: If the references refer to objects with different
4936 // lifetimes, prefer bindings that don't change lifetime.
4942 }
4943
4944 // If the type is an array type, promote the element qualifiers to the
4945 // type for comparison.
4946 if (isa<ArrayType>(T1) && T1Quals)
4947 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4948 if (isa<ArrayType>(T2) && T2Quals)
4949 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4950 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4952 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4954 }
4955 }
4956
4957 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4958 // floating-to-integral conversion if the integral conversion
4959 // is between types of the same size.
4960 // For example:
4961 // void f(float);
4962 // void f(int);
4963 // int main {
4964 // long a;
4965 // f(a);
4966 // }
4967 // Here, MSVC will call f(int) instead of generating a compile error
4968 // as clang will do in standard mode.
4969 if (S.getLangOpts().MSVCCompat &&
4972 SCS2.Second == ICK_Floating_Integral &&
4973 S.Context.getTypeSize(SCS1.getFromType()) ==
4974 S.Context.getTypeSize(SCS1.getToType(2)))
4976
4977 // Prefer a compatible vector conversion over a lax vector conversion
4978 // For example:
4979 //
4980 // typedef float __v4sf __attribute__((__vector_size__(16)));
4981 // void f(vector float);
4982 // void f(vector signed int);
4983 // int main() {
4984 // __v4sf a;
4985 // f(a);
4986 // }
4987 // Here, we'd like to choose f(vector float) and not
4988 // report an ambiguous call error
4989 if (SCS1.Second == ICK_Vector_Conversion &&
4990 SCS2.Second == ICK_Vector_Conversion) {
4991 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4992 SCS1.getFromType(), SCS1.getToType(2));
4993 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4994 SCS2.getFromType(), SCS2.getToType(2));
4995
4996 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4997 return SCS1IsCompatibleVectorConversion
5000 }
5001
5002 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
5004 bool SCS1IsCompatibleSVEVectorConversion =
5005 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
5006 bool SCS2IsCompatibleSVEVectorConversion =
5007 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
5008
5009 if (SCS1IsCompatibleSVEVectorConversion !=
5010 SCS2IsCompatibleSVEVectorConversion)
5011 return SCS1IsCompatibleSVEVectorConversion
5014 }
5015
5016 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
5018 bool SCS1IsCompatibleRVVVectorConversion =
5020 bool SCS2IsCompatibleRVVVectorConversion =
5022
5023 if (SCS1IsCompatibleRVVVectorConversion !=
5024 SCS2IsCompatibleRVVVectorConversion)
5025 return SCS1IsCompatibleRVVVectorConversion
5028 }
5030}
5031
5032/// CompareOverflowBehaviorConversions - Compares two standard conversion
5033/// sequences to determine whether they can be ranked based on their
5034/// OverflowBehaviorType's underlying type.
5050
5051/// CompareQualificationConversions - Compares two standard conversion
5052/// sequences to determine whether they can be ranked based on their
5053/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
5056 const StandardConversionSequence& SCS1,
5057 const StandardConversionSequence& SCS2) {
5058 // C++ [over.ics.rank]p3:
5059 // -- S1 and S2 differ only in their qualification conversion and
5060 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
5061 // [C++98]
5062 // [...] and the cv-qualification signature of type T1 is a proper subset
5063 // of the cv-qualification signature of type T2, and S1 is not the
5064 // deprecated string literal array-to-pointer conversion (4.2).
5065 // [C++2a]
5066 // [...] where T1 can be converted to T2 by a qualification conversion.
5067 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5068 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5070
5071 // FIXME: the example in the standard doesn't use a qualification
5072 // conversion (!)
5073 QualType T1 = SCS1.getToType(2);
5074 QualType T2 = SCS2.getToType(2);
5075 T1 = S.Context.getCanonicalType(T1);
5076 T2 = S.Context.getCanonicalType(T2);
5077 assert(!T1->isReferenceType() && !T2->isReferenceType());
5078 Qualifiers T1Quals, T2Quals;
5079 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5080 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5081
5082 // If the types are the same, we won't learn anything by unwrapping
5083 // them.
5084 if (UnqualT1 == UnqualT2)
5086
5087 // Don't ever prefer a standard conversion sequence that uses the deprecated
5088 // string literal array to pointer conversion.
5089 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5090 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5091
5092 // Objective-C++ ARC:
5093 // Prefer qualification conversions not involving a change in lifetime
5094 // to qualification conversions that do change lifetime.
5097 CanPick1 = false;
5100 CanPick2 = false;
5101
5102 bool ObjCLifetimeConversion;
5103 if (CanPick1 &&
5104 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5105 CanPick1 = false;
5106 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5107 // directions, so we can't short-cut this second check in general.
5108 if (CanPick2 &&
5109 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5110 CanPick2 = false;
5111
5112 if (CanPick1 != CanPick2)
5113 return CanPick1 ? ImplicitConversionSequence::Better
5116}
5117
5118/// CompareDerivedToBaseConversions - Compares two standard conversion
5119/// sequences to determine whether they can be ranked based on their
5120/// various kinds of derived-to-base conversions (C++
5121/// [over.ics.rank]p4b3). As part of these checks, we also look at
5122/// conversions between Objective-C interface types.
5125 const StandardConversionSequence& SCS1,
5126 const StandardConversionSequence& SCS2) {
5127 QualType FromType1 = SCS1.getFromType();
5128 QualType ToType1 = SCS1.getToType(1);
5129 QualType FromType2 = SCS2.getFromType();
5130 QualType ToType2 = SCS2.getToType(1);
5131
5132 // Adjust the types we're converting from via the array-to-pointer
5133 // conversion, if we need to.
5134 if (SCS1.First == ICK_Array_To_Pointer)
5135 FromType1 = S.Context.getArrayDecayedType(FromType1);
5136 if (SCS2.First == ICK_Array_To_Pointer)
5137 FromType2 = S.Context.getArrayDecayedType(FromType2);
5138
5139 // Canonicalize all of the types.
5140 FromType1 = S.Context.getCanonicalType(FromType1);
5141 ToType1 = S.Context.getCanonicalType(ToType1);
5142 FromType2 = S.Context.getCanonicalType(FromType2);
5143 ToType2 = S.Context.getCanonicalType(ToType2);
5144
5145 // C++ [over.ics.rank]p4b3:
5146 //
5147 // If class B is derived directly or indirectly from class A and
5148 // class C is derived directly or indirectly from B,
5149 //
5150 // Compare based on pointer conversions.
5151 if (SCS1.Second == ICK_Pointer_Conversion &&
5153 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5154 FromType1->isPointerType() && FromType2->isPointerType() &&
5155 ToType1->isPointerType() && ToType2->isPointerType()) {
5156 QualType FromPointee1 =
5158 QualType ToPointee1 =
5160 QualType FromPointee2 =
5162 QualType ToPointee2 =
5164
5165 // -- conversion of C* to B* is better than conversion of C* to A*,
5166 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5167 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5169 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5171 }
5172
5173 // -- conversion of B* to A* is better than conversion of C* to A*,
5174 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5175 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5177 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5179 }
5180 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5182 const ObjCObjectPointerType *FromPtr1
5183 = FromType1->getAs<ObjCObjectPointerType>();
5184 const ObjCObjectPointerType *FromPtr2
5185 = FromType2->getAs<ObjCObjectPointerType>();
5186 const ObjCObjectPointerType *ToPtr1
5187 = ToType1->getAs<ObjCObjectPointerType>();
5188 const ObjCObjectPointerType *ToPtr2
5189 = ToType2->getAs<ObjCObjectPointerType>();
5190
5191 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5192 // Apply the same conversion ranking rules for Objective-C pointer types
5193 // that we do for C++ pointers to class types. However, we employ the
5194 // Objective-C pseudo-subtyping relationship used for assignment of
5195 // Objective-C pointer types.
5196 bool FromAssignLeft
5197 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5198 bool FromAssignRight
5199 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5200 bool ToAssignLeft
5201 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5202 bool ToAssignRight
5203 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5204
5205 // A conversion to an a non-id object pointer type or qualified 'id'
5206 // type is better than a conversion to 'id'.
5207 if (ToPtr1->isObjCIdType() &&
5208 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5210 if (ToPtr2->isObjCIdType() &&
5211 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5213
5214 // A conversion to a non-id object pointer type is better than a
5215 // conversion to a qualified 'id' type
5216 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5218 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5220
5221 // A conversion to an a non-Class object pointer type or qualified 'Class'
5222 // type is better than a conversion to 'Class'.
5223 if (ToPtr1->isObjCClassType() &&
5224 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5226 if (ToPtr2->isObjCClassType() &&
5227 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5229
5230 // A conversion to a non-Class object pointer type is better than a
5231 // conversion to a qualified 'Class' type.
5232 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5234 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5236
5237 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5238 if (S.Context.hasSameType(FromType1, FromType2) &&
5239 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5240 (ToAssignLeft != ToAssignRight)) {
5241 if (FromPtr1->isSpecialized()) {
5242 // "conversion of B<A> * to B * is better than conversion of B * to
5243 // C *.
5244 bool IsFirstSame =
5245 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5246 bool IsSecondSame =
5247 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5248 if (IsFirstSame) {
5249 if (!IsSecondSame)
5251 } else if (IsSecondSame)
5253 }
5254 return ToAssignLeft? ImplicitConversionSequence::Worse
5256 }
5257
5258 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5259 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5260 (FromAssignLeft != FromAssignRight))
5261 return FromAssignLeft? ImplicitConversionSequence::Better
5263 }
5264 }
5265
5266 // Ranking of member-pointer types.
5267 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5268 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5269 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5270 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5271 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5272 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5273 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5274 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5275 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5276 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5277 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5278 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5279 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5280 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5282 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5284 }
5285 // conversion of B::* to C::* is better than conversion of A::* to C::*
5286 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5287 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5289 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5291 }
5292 }
5293
5294 if (SCS1.Second == ICK_Derived_To_Base) {
5295 // -- conversion of C to B is better than conversion of C to A,
5296 // -- binding of an expression of type C to a reference of type
5297 // B& is better than binding an expression of type C to a
5298 // reference of type A&,
5299 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5300 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5301 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5303 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5305 }
5306
5307 // -- conversion of B to A is better than conversion of C to A.
5308 // -- binding of an expression of type B to a reference of type
5309 // A& is better than binding an expression of type C to a
5310 // reference of type A&,
5311 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5312 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5313 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5315 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5317 }
5318 }
5319
5321}
5322
5324 if (!T.getQualifiers().hasUnaligned())
5325 return T;
5326
5327 Qualifiers Q;
5328 T = Ctx.getUnqualifiedArrayType(T, Q);
5329 Q.removeUnaligned();
5330 return Ctx.getQualifiedType(T, Q);
5331}
5332
5335 QualType OrigT1, QualType OrigT2,
5336 ReferenceConversions *ConvOut) {
5337 assert(!OrigT1->isReferenceType() &&
5338 "T1 must be the pointee type of the reference type");
5339 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5340
5341 QualType T1 = Context.getCanonicalType(OrigT1);
5342 QualType T2 = Context.getCanonicalType(OrigT2);
5343 Qualifiers T1Quals, T2Quals;
5344 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5345 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5346
5347 ReferenceConversions ConvTmp;
5348 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5349 Conv = ReferenceConversions();
5350
5351 // C++2a [dcl.init.ref]p4:
5352 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5353 // reference-related to "cv2 T2" if T1 is similar to T2, or
5354 // T1 is a base class of T2.
5355 // "cv1 T1" is reference-compatible with "cv2 T2" if
5356 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5357 // "pointer to cv1 T1" via a standard conversion sequence.
5358
5359 // Check for standard conversions we can apply to pointers: derived-to-base
5360 // conversions, ObjC pointer conversions, and function pointer conversions.
5361 // (Qualification conversions are checked last.)
5362 if (UnqualT1 == UnqualT2) {
5363 // Nothing to do.
5364 } else if (isCompleteType(Loc, OrigT2) &&
5365 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5366 Conv |= ReferenceConversions::DerivedToBase;
5367 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5368 UnqualT2->isObjCObjectOrInterfaceType() &&
5369 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5370 Conv |= ReferenceConversions::ObjC;
5371 else if (UnqualT2->isFunctionType() &&
5372 IsFunctionConversion(UnqualT2, UnqualT1)) {
5373 Conv |= ReferenceConversions::Function;
5374 // No need to check qualifiers; function types don't have them.
5375 return Ref_Compatible;
5376 }
5377 bool ConvertedReferent = Conv != 0;
5378
5379 // We can have a qualification conversion. Compute whether the types are
5380 // similar at the same time.
5381 bool PreviousToQualsIncludeConst = true;
5382 bool TopLevel = true;
5383 do {
5384 if (T1 == T2)
5385 break;
5386
5387 // We will need a qualification conversion.
5388 Conv |= ReferenceConversions::Qualification;
5389
5390 // Track whether we performed a qualification conversion anywhere other
5391 // than the top level. This matters for ranking reference bindings in
5392 // overload resolution.
5393 if (!TopLevel)
5394 Conv |= ReferenceConversions::NestedQualification;
5395
5396 // MS compiler ignores __unaligned qualifier for references; do the same.
5397 T1 = withoutUnaligned(Context, T1);
5398 T2 = withoutUnaligned(Context, T2);
5399
5400 // If we find a qualifier mismatch, the types are not reference-compatible,
5401 // but are still be reference-related if they're similar.
5402 bool ObjCLifetimeConversion = false;
5403 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5404 PreviousToQualsIncludeConst,
5405 ObjCLifetimeConversion, getASTContext()))
5406 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5407 ? Ref_Related
5409
5410 // FIXME: Should we track this for any level other than the first?
5411 if (ObjCLifetimeConversion)
5412 Conv |= ReferenceConversions::ObjCLifetime;
5413
5414 TopLevel = false;
5415 } while (Context.UnwrapSimilarTypes(T1, T2));
5416
5417 // At this point, if the types are reference-related, we must either have the
5418 // same inner type (ignoring qualifiers), or must have already worked out how
5419 // to convert the referent.
5420 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5423}
5424
5425/// Look for a user-defined conversion to a value reference-compatible
5426/// with DeclType. Return true if something definite is found.
5427static bool
5429 QualType DeclType, SourceLocation DeclLoc,
5430 Expr *Init, QualType T2, bool AllowRvalues,
5431 bool AllowExplicit) {
5432 assert(T2->isRecordType() && "Can only find conversions of record types.");
5433 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5434 OverloadCandidateSet CandidateSet(
5436 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5437 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5438 NamedDecl *D = *I;
5440 if (isa<UsingShadowDecl>(D))
5441 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5442
5443 FunctionTemplateDecl *ConvTemplate
5444 = dyn_cast<FunctionTemplateDecl>(D);
5445 CXXConversionDecl *Conv;
5446 if (ConvTemplate)
5447 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5448 else
5449 Conv = cast<CXXConversionDecl>(D);
5450
5451 if (AllowRvalues) {
5452 // If we are initializing an rvalue reference, don't permit conversion
5453 // functions that return lvalues.
5454 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5455 const ReferenceType *RefType
5457 if (RefType && !RefType->getPointeeType()->isFunctionType())
5458 continue;
5459 }
5460
5461 if (!ConvTemplate &&
5463 DeclLoc,
5464 Conv->getConversionType()
5469 continue;
5470 } else {
5471 // If the conversion function doesn't return a reference type,
5472 // it can't be considered for this conversion. An rvalue reference
5473 // is only acceptable if its referencee is a function type.
5474
5475 const ReferenceType *RefType =
5477 if (!RefType ||
5478 (!RefType->isLValueReferenceType() &&
5479 !RefType->getPointeeType()->isFunctionType()))
5480 continue;
5481 }
5482
5483 if (ConvTemplate)
5485 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5486 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5487 else
5489 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5490 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5491 }
5492
5493 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5494
5496 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5497 case OR_Success:
5498
5499 assert(Best->HasFinalConversion);
5500
5501 // C++ [over.ics.ref]p1:
5502 //
5503 // [...] If the parameter binds directly to the result of
5504 // applying a conversion function to the argument
5505 // expression, the implicit conversion sequence is a
5506 // user-defined conversion sequence (13.3.3.1.2), with the
5507 // second standard conversion sequence either an identity
5508 // conversion or, if the conversion function returns an
5509 // entity of a type that is a derived class of the parameter
5510 // type, a derived-to-base Conversion.
5511 if (!Best->FinalConversion.DirectBinding)
5512 return false;
5513
5514 ICS.setUserDefined();
5515 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5516 ICS.UserDefined.After = Best->FinalConversion;
5517 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5518 ICS.UserDefined.ConversionFunction = Best->Function;
5519 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5520 ICS.UserDefined.EllipsisConversion = false;
5521 assert(ICS.UserDefined.After.ReferenceBinding &&
5523 "Expected a direct reference binding!");
5524 return true;
5525
5526 case OR_Ambiguous:
5527 ICS.setAmbiguous();
5528 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5529 Cand != CandidateSet.end(); ++Cand)
5530 if (Cand->Best)
5531 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5532 return true;
5533
5535 case OR_Deleted:
5536 // There was no suitable conversion, or we found a deleted
5537 // conversion; continue with other checks.
5538 return false;
5539 }
5540
5541 llvm_unreachable("Invalid OverloadResult!");
5542}
5543
5544/// Compute an implicit conversion sequence for reference
5545/// initialization.
5546static ImplicitConversionSequence
5548 SourceLocation DeclLoc,
5549 bool SuppressUserConversions,
5550 bool AllowExplicit) {
5551 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5552
5553 // Most paths end in a failed conversion.
5556
5557 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5558 QualType T2 = Init->getType();
5559
5560 // If the initializer is the address of an overloaded function, try
5561 // to resolve the overloaded function. If all goes well, T2 is the
5562 // type of the resulting function.
5563 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5566 false, Found))
5567 T2 = Fn->getType();
5568 }
5569
5570 // Compute some basic properties of the types and the initializer.
5571 bool isRValRef = DeclType->isRValueReferenceType();
5572 Expr::Classification InitCategory = Init->Classify(S.Context);
5573
5575 Sema::ReferenceCompareResult RefRelationship =
5576 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5577
5578 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5579 ICS.setStandard();
5581 // FIXME: A reference binding can be a function conversion too. We should
5582 // consider that when ordering reference-to-function bindings.
5583 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5585 : (RefConv & Sema::ReferenceConversions::ObjC)
5587 : ICK_Identity;
5589 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5590 // a reference binding that performs a non-top-level qualification
5591 // conversion as a qualification conversion, not as an identity conversion.
5592 ICS.Standard.Third = (RefConv &
5593 Sema::ReferenceConversions::NestedQualification)
5595 : ICK_Identity;
5596 ICS.Standard.setFromType(T2);
5597 ICS.Standard.setToType(0, T2);
5598 ICS.Standard.setToType(1, T1);
5599 ICS.Standard.setToType(2, T1);
5600 ICS.Standard.ReferenceBinding = true;
5601 ICS.Standard.DirectBinding = BindsDirectly;
5602 ICS.Standard.IsLvalueReference = !isRValRef;
5604 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5607 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5608 ICS.Standard.FromBracedInitList = false;
5609 ICS.Standard.CopyConstructor = nullptr;
5611 };
5612
5613 // C++0x [dcl.init.ref]p5:
5614 // A reference to type "cv1 T1" is initialized by an expression
5615 // of type "cv2 T2" as follows:
5616
5617 // -- If reference is an lvalue reference and the initializer expression
5618 if (!isRValRef) {
5619 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5620 // reference-compatible with "cv2 T2," or
5621 //
5622 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5623 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5624 // C++ [over.ics.ref]p1:
5625 // When a parameter of reference type binds directly (8.5.3)
5626 // to an argument expression, the implicit conversion sequence
5627 // is the identity conversion, unless the argument expression
5628 // has a type that is a derived class of the parameter type,
5629 // in which case the implicit conversion sequence is a
5630 // derived-to-base Conversion (13.3.3.1).
5631 SetAsReferenceBinding(/*BindsDirectly=*/true);
5632
5633 // Nothing more to do: the inaccessibility/ambiguity check for
5634 // derived-to-base conversions is suppressed when we're
5635 // computing the implicit conversion sequence (C++
5636 // [over.best.ics]p2).
5637 return ICS;
5638 }
5639
5640 // -- has a class type (i.e., T2 is a class type), where T1 is
5641 // not reference-related to T2, and can be implicitly
5642 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5643 // is reference-compatible with "cv3 T3" 92) (this
5644 // conversion is selected by enumerating the applicable
5645 // conversion functions (13.3.1.6) and choosing the best
5646 // one through overload resolution (13.3)),
5647 if (!SuppressUserConversions && T2->isRecordType() &&
5648 S.isCompleteType(DeclLoc, T2) &&
5649 RefRelationship == Sema::Ref_Incompatible) {
5650 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5651 Init, T2, /*AllowRvalues=*/false,
5652 AllowExplicit))
5653 return ICS;
5654 }
5655 }
5656
5657 // -- Otherwise, the reference shall be an lvalue reference to a
5658 // non-volatile const type (i.e., cv1 shall be const), or the reference
5659 // shall be an rvalue reference.
5660 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5661 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5663 return ICS;
5664 }
5665
5666 // -- If the initializer expression
5667 //
5668 // -- is an xvalue, class prvalue, array prvalue or function
5669 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5670 if (RefRelationship == Sema::Ref_Compatible &&
5671 (InitCategory.isXValue() ||
5672 (InitCategory.isPRValue() &&
5673 (T2->isRecordType() || T2->isArrayType())) ||
5674 (InitCategory.isLValue() && T2->isFunctionType()))) {
5675 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5676 // binding unless we're binding to a class prvalue.
5677 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5678 // allow the use of rvalue references in C++98/03 for the benefit of
5679 // standard library implementors; therefore, we need the xvalue check here.
5680 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5681 !(InitCategory.isPRValue() || T2->isRecordType()));
5682 return ICS;
5683 }
5684
5685 // -- has a class type (i.e., T2 is a class type), where T1 is not
5686 // reference-related to T2, and can be implicitly converted to
5687 // an xvalue, class prvalue, or function lvalue of type
5688 // "cv3 T3", where "cv1 T1" is reference-compatible with
5689 // "cv3 T3",
5690 //
5691 // then the reference is bound to the value of the initializer
5692 // expression in the first case and to the result of the conversion
5693 // in the second case (or, in either case, to an appropriate base
5694 // class subobject).
5695 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5696 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5697 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5698 Init, T2, /*AllowRvalues=*/true,
5699 AllowExplicit)) {
5700 // In the second case, if the reference is an rvalue reference
5701 // and the second standard conversion sequence of the
5702 // user-defined conversion sequence includes an lvalue-to-rvalue
5703 // conversion, the program is ill-formed.
5704 if (ICS.isUserDefined() && isRValRef &&
5707
5708 return ICS;
5709 }
5710
5711 // A temporary of function type cannot be created; don't even try.
5712 if (T1->isFunctionType())
5713 return ICS;
5714
5715 // -- Otherwise, a temporary of type "cv1 T1" is created and
5716 // initialized from the initializer expression using the
5717 // rules for a non-reference copy initialization (8.5). The
5718 // reference is then bound to the temporary. If T1 is
5719 // reference-related to T2, cv1 must be the same
5720 // cv-qualification as, or greater cv-qualification than,
5721 // cv2; otherwise, the program is ill-formed.
5722 if (RefRelationship == Sema::Ref_Related) {
5723 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5724 // we would be reference-compatible or reference-compatible with
5725 // added qualification. But that wasn't the case, so the reference
5726 // initialization fails.
5727 //
5728 // Note that we only want to check address spaces and cvr-qualifiers here.
5729 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5730 Qualifiers T1Quals = T1.getQualifiers();
5731 Qualifiers T2Quals = T2.getQualifiers();
5732 T1Quals.removeObjCGCAttr();
5733 T1Quals.removeObjCLifetime();
5734 T2Quals.removeObjCGCAttr();
5735 T2Quals.removeObjCLifetime();
5736 // MS compiler ignores __unaligned qualifier for references; do the same.
5737 T1Quals.removeUnaligned();
5738 T2Quals.removeUnaligned();
5739 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5740 return ICS;
5741 }
5742
5743 // If at least one of the types is a class type, the types are not
5744 // related, and we aren't allowed any user conversions, the
5745 // reference binding fails. This case is important for breaking
5746 // recursion, since TryImplicitConversion below will attempt to
5747 // create a temporary through the use of a copy constructor.
5748 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5749 (T1->isRecordType() || T2->isRecordType()))
5750 return ICS;
5751
5752 // If T1 is reference-related to T2 and the reference is an rvalue
5753 // reference, the initializer expression shall not be an lvalue.
5754 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5755 Init->Classify(S.Context).isLValue()) {
5757 return ICS;
5758 }
5759
5760 // C++ [over.ics.ref]p2:
5761 // When a parameter of reference type is not bound directly to
5762 // an argument expression, the conversion sequence is the one
5763 // required to convert the argument expression to the
5764 // underlying type of the reference according to
5765 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5766 // to copy-initializing a temporary of the underlying type with
5767 // the argument expression. Any difference in top-level
5768 // cv-qualification is subsumed by the initialization itself
5769 // and does not constitute a conversion.
5770 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5771 AllowedExplicit::None,
5772 /*InOverloadResolution=*/false,
5773 /*CStyle=*/false,
5774 /*AllowObjCWritebackConversion=*/false,
5775 /*AllowObjCConversionOnExplicit=*/false);
5776
5777 // Of course, that's still a reference binding.
5778 if (ICS.isStandard()) {
5779 ICS.Standard.ReferenceBinding = true;
5780 ICS.Standard.IsLvalueReference = !isRValRef;
5781 ICS.Standard.BindsToFunctionLvalue = false;
5782 ICS.Standard.BindsToRvalue = true;
5785 } else if (ICS.isUserDefined()) {
5786 const ReferenceType *LValRefType =
5789
5790 // C++ [over.ics.ref]p3:
5791 // Except for an implicit object parameter, for which see 13.3.1, a
5792 // standard conversion sequence cannot be formed if it requires [...]
5793 // binding an rvalue reference to an lvalue other than a function
5794 // lvalue.
5795 // Note that the function case is not possible here.
5796 if (isRValRef && LValRefType) {
5798 return ICS;
5799 }
5800
5802 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5804 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5808 }
5809
5810 return ICS;
5811}
5812
5813static ImplicitConversionSequence
5814TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5815 bool SuppressUserConversions,
5816 bool InOverloadResolution,
5817 bool AllowObjCWritebackConversion,
5818 bool AllowExplicit = false);
5819
5820/// TryListConversion - Try to copy-initialize a value of type ToType from the
5821/// initializer list From.
5822static ImplicitConversionSequence
5824 bool SuppressUserConversions,
5825 bool InOverloadResolution,
5826 bool AllowObjCWritebackConversion) {
5827 // C++11 [over.ics.list]p1:
5828 // When an argument is an initializer list, it is not an expression and
5829 // special rules apply for converting it to a parameter type.
5830
5832 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5833
5834 // We need a complete type for what follows. With one C++20 exception,
5835 // incomplete types can never be initialized from init lists.
5836 QualType InitTy = ToType;
5837 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5838 if (AT && S.getLangOpts().CPlusPlus20)
5839 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5840 // C++20 allows list initialization of an incomplete array type.
5841 InitTy = IAT->getElementType();
5842 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5843 return Result;
5844
5845 // C++20 [over.ics.list]/2:
5846 // If the initializer list is a designated-initializer-list, a conversion
5847 // is only possible if the parameter has an aggregate type
5848 //
5849 // FIXME: The exception for reference initialization here is not part of the
5850 // language rules, but follow other compilers in adding it as a tentative DR
5851 // resolution.
5852 bool IsDesignatedInit = From->hasDesignatedInit();
5853 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5854 IsDesignatedInit)
5855 return Result;
5856
5857 // Per DR1467 and DR2137:
5858 // If the parameter type is an aggregate class X and the initializer list
5859 // has a single element of type cv U, where U is X or a class derived from
5860 // X, the implicit conversion sequence is the one required to convert the
5861 // element to the parameter type.
5862 //
5863 // Otherwise, if the parameter type is a character array [... ]
5864 // and the initializer list has a single element that is an
5865 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5866 // implicit conversion sequence is the identity conversion.
5867 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5868 if (ToType->isRecordType() && ToType->isAggregateType()) {
5869 QualType InitType = From->getInit(0)->getType();
5870 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5871 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5872 return TryCopyInitialization(S, From->getInit(0), ToType,
5873 SuppressUserConversions,
5874 InOverloadResolution,
5875 AllowObjCWritebackConversion);
5876 }
5877
5878 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5879 InitializedEntity Entity =
5881 /*Consumed=*/false);
5882 if (S.CanPerformCopyInitialization(Entity, From)) {
5883 Result.setStandard();
5884 Result.Standard.setAsIdentityConversion();
5885 Result.Standard.setFromType(ToType);
5886 Result.Standard.setAllToTypes(ToType);
5887 return Result;
5888 }
5889 }
5890 }
5891
5892 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5893 // C++11 [over.ics.list]p2:
5894 // If the parameter type is std::initializer_list<X> or "array of X" and
5895 // all the elements can be implicitly converted to X, the implicit
5896 // conversion sequence is the worst conversion necessary to convert an
5897 // element of the list to X.
5898 //
5899 // C++14 [over.ics.list]p3:
5900 // Otherwise, if the parameter type is "array of N X", if the initializer
5901 // list has exactly N elements or if it has fewer than N elements and X is
5902 // default-constructible, and if all the elements of the initializer list
5903 // can be implicitly converted to X, the implicit conversion sequence is
5904 // the worst conversion necessary to convert an element of the list to X.
5905 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5906 unsigned e = From->getNumInits();
5909 QualType());
5910 QualType ContTy = ToType;
5911 bool IsUnbounded = false;
5912 if (AT) {
5913 InitTy = AT->getElementType();
5914 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5915 if (CT->getSize().ult(e)) {
5916 // Too many inits, fatally bad
5918 ToType);
5919 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5920 return Result;
5921 }
5922 if (CT->getSize().ugt(e)) {
5923 // Need an init from empty {}, is there one?
5924 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5925 From->getEndLoc(), /*isExplicit=*/false);
5926 EmptyList.setType(S.Context.VoidTy);
5927 DfltElt = TryListConversion(
5928 S, &EmptyList, InitTy, SuppressUserConversions,
5929 InOverloadResolution, AllowObjCWritebackConversion);
5930 if (DfltElt.isBad()) {
5931 // No {} init, fatally bad
5933 ToType);
5934 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5935 return Result;
5936 }
5937 }
5938 } else {
5939 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5940 IsUnbounded = true;
5941 if (!e) {
5942 // Cannot convert to zero-sized.
5944 ToType);
5945 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5946 return Result;
5947 }
5948 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5949 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5951 }
5952 }
5953
5954 Result.setStandard();
5955 Result.Standard.setAsIdentityConversion();
5956 Result.Standard.setFromType(InitTy);
5957 Result.Standard.setAllToTypes(InitTy);
5958 for (unsigned i = 0; i < e; ++i) {
5959 Expr *Init = From->getInit(i);
5961 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5962 AllowObjCWritebackConversion);
5963
5964 // Keep the worse conversion seen so far.
5965 // FIXME: Sequences are not totally ordered, so 'worse' can be
5966 // ambiguous. CWG has been informed.
5968 Result) ==
5970 Result = ICS;
5971 // Bail as soon as we find something unconvertible.
5972 if (Result.isBad()) {
5973 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5974 return Result;
5975 }
5976 }
5977 }
5978
5979 // If we needed any implicit {} initialization, compare that now.
5980 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5981 // has been informed that this might not be the best thing.
5982 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5983 S, From->getEndLoc(), DfltElt, Result) ==
5985 Result = DfltElt;
5986 // Record the type being initialized so that we may compare sequences
5987 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5988 return Result;
5989 }
5990
5991 // C++14 [over.ics.list]p4:
5992 // C++11 [over.ics.list]p3:
5993 // Otherwise, if the parameter is a non-aggregate class X and overload
5994 // resolution chooses a single best constructor [...] the implicit
5995 // conversion sequence is a user-defined conversion sequence. If multiple
5996 // constructors are viable but none is better than the others, the
5997 // implicit conversion sequence is a user-defined conversion sequence.
5998 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5999 // This function can deal with initializer lists.
6000 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
6001 AllowedExplicit::None,
6002 InOverloadResolution, /*CStyle=*/false,
6003 AllowObjCWritebackConversion,
6004 /*AllowObjCConversionOnExplicit=*/false);
6005 }
6006
6007 // C++14 [over.ics.list]p5:
6008 // C++11 [over.ics.list]p4:
6009 // Otherwise, if the parameter has an aggregate type which can be
6010 // initialized from the initializer list [...] the implicit conversion
6011 // sequence is a user-defined conversion sequence.
6012 if (ToType->isAggregateType()) {
6013 // Type is an aggregate, argument is an init list. At this point it comes
6014 // down to checking whether the initialization works.
6015 // FIXME: Find out whether this parameter is consumed or not.
6016 InitializedEntity Entity =
6018 /*Consumed=*/false);
6020 From)) {
6021 Result.setUserDefined();
6022 Result.UserDefined.Before.setAsIdentityConversion();
6023 // Initializer lists don't have a type.
6024 Result.UserDefined.Before.setFromType(QualType());
6025 Result.UserDefined.Before.setAllToTypes(QualType());
6026
6027 Result.UserDefined.After.setAsIdentityConversion();
6028 Result.UserDefined.After.setFromType(ToType);
6029 Result.UserDefined.After.setAllToTypes(ToType);
6030 Result.UserDefined.ConversionFunction = nullptr;
6031 }
6032 return Result;
6033 }
6034
6035 // C++14 [over.ics.list]p6:
6036 // C++11 [over.ics.list]p5:
6037 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
6038 if (ToType->isReferenceType()) {
6039 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
6040 // mention initializer lists in any way. So we go by what list-
6041 // initialization would do and try to extrapolate from that.
6042
6043 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
6044
6045 // If the initializer list has a single element that is reference-related
6046 // to the parameter type, we initialize the reference from that.
6047 if (From->getNumInits() == 1 && !IsDesignatedInit) {
6048 Expr *Init = From->getInit(0);
6049
6050 QualType T2 = Init->getType();
6051
6052 // If the initializer is the address of an overloaded function, try
6053 // to resolve the overloaded function. If all goes well, T2 is the
6054 // type of the resulting function.
6055 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
6058 Init, ToType, false, Found))
6059 T2 = Fn->getType();
6060 }
6061
6062 // Compute some basic properties of the types and the initializer.
6063 Sema::ReferenceCompareResult RefRelationship =
6064 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
6065
6066 if (RefRelationship >= Sema::Ref_Related) {
6067 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
6068 SuppressUserConversions,
6069 /*AllowExplicit=*/false);
6070 }
6071 }
6072
6073 // Otherwise, we bind the reference to a temporary created from the
6074 // initializer list.
6075 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6076 InOverloadResolution,
6077 AllowObjCWritebackConversion);
6078 if (Result.isFailure())
6079 return Result;
6080 assert(!Result.isEllipsis() &&
6081 "Sub-initialization cannot result in ellipsis conversion.");
6082
6083 // Can we even bind to a temporary?
6084 if (ToType->isRValueReferenceType() ||
6085 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6086 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6087 Result.UserDefined.After;
6088 SCS.ReferenceBinding = true;
6090 SCS.BindsToRvalue = true;
6091 SCS.BindsToFunctionLvalue = false;
6094 SCS.FromBracedInitList = false;
6095
6096 } else
6098 From, ToType);
6099 return Result;
6100 }
6101
6102 // C++14 [over.ics.list]p7:
6103 // C++11 [over.ics.list]p6:
6104 // Otherwise, if the parameter type is not a class:
6105 if (!ToType->isRecordType()) {
6106 // - if the initializer list has one element that is not itself an
6107 // initializer list, the implicit conversion sequence is the one
6108 // required to convert the element to the parameter type.
6109 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6110 // single integer.
6111 unsigned NumInits = From->getNumInits();
6112 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6113 !isa<EmbedExpr>(From->getInit(0))) {
6115 S, From->getInit(0), ToType, SuppressUserConversions,
6116 InOverloadResolution, AllowObjCWritebackConversion);
6117 if (Result.isStandard())
6118 Result.Standard.FromBracedInitList = true;
6119 }
6120 // - if the initializer list has no elements, the implicit conversion
6121 // sequence is the identity conversion.
6122 else if (NumInits == 0) {
6123 Result.setStandard();
6124 Result.Standard.setAsIdentityConversion();
6125 Result.Standard.setFromType(ToType);
6126 Result.Standard.setAllToTypes(ToType);
6127 }
6128 return Result;
6129 }
6130
6131 // C++14 [over.ics.list]p8:
6132 // C++11 [over.ics.list]p7:
6133 // In all cases other than those enumerated above, no conversion is possible
6134 return Result;
6135}
6136
6137/// TryCopyInitialization - Try to copy-initialize a value of type
6138/// ToType from the expression From. Return the implicit conversion
6139/// sequence required to pass this argument, which may be a bad
6140/// conversion sequence (meaning that the argument cannot be passed to
6141/// a parameter of this type). If @p SuppressUserConversions, then we
6142/// do not permit any user-defined conversion sequences.
6143static ImplicitConversionSequence
6145 bool SuppressUserConversions,
6146 bool InOverloadResolution,
6147 bool AllowObjCWritebackConversion,
6148 bool AllowExplicit) {
6149 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6150 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6151 InOverloadResolution,AllowObjCWritebackConversion);
6152
6153 if (ToType->isReferenceType())
6154 return TryReferenceInit(S, From, ToType,
6155 /*FIXME:*/ From->getBeginLoc(),
6156 SuppressUserConversions, AllowExplicit);
6157
6158 return TryImplicitConversion(S, From, ToType,
6159 SuppressUserConversions,
6160 AllowedExplicit::None,
6161 InOverloadResolution,
6162 /*CStyle=*/false,
6163 AllowObjCWritebackConversion,
6164 /*AllowObjCConversionOnExplicit=*/false);
6165}
6166
6167static bool TryCopyInitialization(const CanQualType FromQTy,
6168 const CanQualType ToQTy,
6169 Sema &S,
6170 SourceLocation Loc,
6171 ExprValueKind FromVK) {
6172 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6174 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6175
6176 return !ICS.isBad();
6177}
6178
6179/// TryObjectArgumentInitialization - Try to initialize the object
6180/// parameter of the given member function (@c Method) from the
6181/// expression @p From.
6183 Sema &S, SourceLocation Loc, QualType FromType,
6184 Expr::Classification FromClassification, CXXMethodDecl *Method,
6185 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6186 QualType ExplicitParameterType = QualType(),
6187 bool SuppressUserConversion = false) {
6188
6189 // We need to have an object of class type.
6190 if (const auto *PT = FromType->getAs<PointerType>()) {
6191 FromType = PT->getPointeeType();
6192
6193 // When we had a pointer, it's implicitly dereferenced, so we
6194 // better have an lvalue.
6195 assert(FromClassification.isLValue());
6196 }
6197
6198 auto ValueKindFromClassification = [](Expr::Classification C) {
6199 if (C.isPRValue())
6200 return clang::VK_PRValue;
6201 if (C.isXValue())
6202 return VK_XValue;
6203 return clang::VK_LValue;
6204 };
6205
6206 if (Method->isExplicitObjectMemberFunction()) {
6207 if (ExplicitParameterType.isNull())
6208 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6209 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6210 ValueKindFromClassification(FromClassification));
6212 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6213 /*InOverloadResolution=*/true, false);
6214 if (ICS.isBad())
6215 ICS.Bad.FromExpr = nullptr;
6216 return ICS;
6217 }
6218
6219 assert(FromType->isRecordType());
6220
6221 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6222 // C++98 [class.dtor]p2:
6223 // A destructor can be invoked for a const, volatile or const volatile
6224 // object.
6225 // C++98 [over.match.funcs]p4:
6226 // For static member functions, the implicit object parameter is considered
6227 // to match any object (since if the function is selected, the object is
6228 // discarded).
6229 Qualifiers Quals = Method->getMethodQualifiers();
6230 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6231 Quals.addConst();
6232 Quals.addVolatile();
6233 }
6234
6235 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6236
6237 // Set up the conversion sequence as a "bad" conversion, to allow us
6238 // to exit early.
6240
6241 // C++0x [over.match.funcs]p4:
6242 // For non-static member functions, the type of the implicit object
6243 // parameter is
6244 //
6245 // - "lvalue reference to cv X" for functions declared without a
6246 // ref-qualifier or with the & ref-qualifier
6247 // - "rvalue reference to cv X" for functions declared with the &&
6248 // ref-qualifier
6249 //
6250 // where X is the class of which the function is a member and cv is the
6251 // cv-qualification on the member function declaration.
6252 //
6253 // However, when finding an implicit conversion sequence for the argument, we
6254 // are not allowed to perform user-defined conversions
6255 // (C++ [over.match.funcs]p5). We perform a simplified version of
6256 // reference binding here, that allows class rvalues to bind to
6257 // non-constant references.
6258
6259 // First check the qualifiers.
6260 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6261 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6262 if (ImplicitParamType.getCVRQualifiers() !=
6263 FromTypeCanon.getLocalCVRQualifiers() &&
6264 !ImplicitParamType.isAtLeastAsQualifiedAs(
6265 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6267 FromType, ImplicitParamType);
6268 return ICS;
6269 }
6270
6271 if (FromTypeCanon.hasAddressSpace()) {
6272 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6273 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6274 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6275 S.getASTContext())) {
6277 FromType, ImplicitParamType);
6278 return ICS;
6279 }
6280 }
6281
6282 // Check that we have either the same type or a derived type. It
6283 // affects the conversion rank.
6284 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6285 ImplicitConversionKind SecondKind;
6286 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6287 SecondKind = ICK_Identity;
6288 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6289 SecondKind = ICK_Derived_To_Base;
6290 } else if (!Method->isExplicitObjectMemberFunction()) {
6292 FromType, ImplicitParamType);
6293 return ICS;
6294 }
6295
6296 // Check the ref-qualifier.
6297 switch (Method->getRefQualifier()) {
6298 case RQ_None:
6299 // Do nothing; we don't care about lvalueness or rvalueness.
6300 break;
6301
6302 case RQ_LValue:
6303 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6304 // non-const lvalue reference cannot bind to an rvalue
6306 ImplicitParamType);
6307 return ICS;
6308 }
6309 break;
6310
6311 case RQ_RValue:
6312 if (!FromClassification.isRValue()) {
6313 // rvalue reference cannot bind to an lvalue
6315 ImplicitParamType);
6316 return ICS;
6317 }
6318 break;
6319 }
6320
6321 // Success. Mark this as a reference binding.
6322 ICS.setStandard();
6324 ICS.Standard.Second = SecondKind;
6325 ICS.Standard.setFromType(FromType);
6326 ICS.Standard.setAllToTypes(ImplicitParamType);
6327 ICS.Standard.ReferenceBinding = true;
6328 ICS.Standard.DirectBinding = true;
6329 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6330 ICS.Standard.BindsToFunctionLvalue = false;
6331 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6332 ICS.Standard.FromBracedInitList = false;
6334 = (Method->getRefQualifier() == RQ_None);
6335 return ICS;
6336}
6337
6338/// PerformObjectArgumentInitialization - Perform initialization of
6339/// the implicit object parameter for the given Method with the given
6340/// expression.
6342 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6344 QualType FromRecordType, DestType;
6345 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6346
6347 if (getLangOpts().HLSL &&
6350 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6351 /*BasePath=*/nullptr, VK_PRValue,
6353 }
6354
6355 Expr::Classification FromClassification;
6356 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6357 FromRecordType = PT->getPointeeType();
6358 DestType = Method->getThisType();
6359 FromClassification = Expr::Classification::makeSimpleLValue();
6360 } else {
6361 FromRecordType = From->getType();
6362 DestType = ImplicitParamRecordType;
6363 FromClassification = From->Classify(Context);
6364
6365 // CWG2813 [expr.call]p6:
6366 // If the function is an implicit object member function, the object
6367 // expression of the class member access shall be a glvalue [...]
6368 if (From->isPRValue()) {
6369 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6370 Method->getRefQualifier() !=
6372 }
6373 }
6374
6375 // Note that we always use the true parent context when performing
6376 // the actual argument initialization.
6378 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6379 Method->getParent());
6380 if (ICS.isBad()) {
6381 switch (ICS.Bad.Kind) {
6383 Qualifiers FromQs = FromRecordType.getQualifiers();
6384 Qualifiers ToQs = DestType.getQualifiers();
6385 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6386 if (CVR) {
6387 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6388 << Method->getDeclName() << FromRecordType << (CVR - 1)
6389 << From->getSourceRange();
6390 Diag(Method->getLocation(), diag::note_previous_decl)
6391 << Method->getDeclName();
6392 return ExprError();
6393 }
6394 break;
6395 }
6396
6399 bool IsRValueQualified =
6400 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6401 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6402 << Method->getDeclName() << FromClassification.isRValue()
6403 << IsRValueQualified;
6404 Diag(Method->getLocation(), diag::note_previous_decl)
6405 << Method->getDeclName();
6406 return ExprError();
6407 }
6408
6411 break;
6412
6415 llvm_unreachable("Lists are not objects");
6416 }
6417
6418 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6419 << ImplicitParamRecordType << FromRecordType
6420 << From->getSourceRange();
6421 }
6422
6423 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6424 ExprResult FromRes =
6425 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6426 if (FromRes.isInvalid())
6427 return ExprError();
6428 From = FromRes.get();
6429 }
6430
6431 if (!Context.hasSameType(From->getType(), DestType)) {
6432 CastKind CK;
6433 QualType PteeTy = DestType->getPointeeType();
6434 LangAS DestAS =
6435 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6436 if (FromRecordType.getAddressSpace() != DestAS)
6437 CK = CK_AddressSpaceConversion;
6438 else
6439 CK = CK_NoOp;
6440 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6441 }
6442 return From;
6443}
6444
6445/// TryContextuallyConvertToBool - Attempt to contextually convert the
6446/// expression From to bool (C++0x [conv]p3).
6449 // C++ [dcl.init]/17.8:
6450 // - Otherwise, if the initialization is direct-initialization, the source
6451 // type is std::nullptr_t, and the destination type is bool, the initial
6452 // value of the object being initialized is false.
6453 if (From->getType()->isNullPtrType())
6455 S.Context.BoolTy,
6456 From->isGLValue());
6457
6458 // All other direct-initialization of bool is equivalent to an implicit
6459 // conversion to bool in which explicit conversions are permitted.
6460 return TryImplicitConversion(S, From, S.Context.BoolTy,
6461 /*SuppressUserConversions=*/false,
6462 AllowedExplicit::Conversions,
6463 /*InOverloadResolution=*/false,
6464 /*CStyle=*/false,
6465 /*AllowObjCWritebackConversion=*/false,
6466 /*AllowObjCConversionOnExplicit=*/false);
6467}
6468
6470 if (checkPlaceholderForOverload(*this, From))
6471 return ExprError();
6472 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6473 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6474
6476 if (!ICS.isBad())
6477 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6480 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6481 << From->getType() << From->getSourceRange();
6482 return ExprError();
6483}
6484
6485/// Check that the specified conversion is permitted in a converted constant
6486/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6487/// is acceptable.
6490 // Since we know that the target type is an integral or unscoped enumeration
6491 // type, most conversion kinds are impossible. All possible First and Third
6492 // conversions are fine.
6493 switch (SCS.Second) {
6494 case ICK_Identity:
6496 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6498 return true;
6499
6501 // Conversion from an integral or unscoped enumeration type to bool is
6502 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6503 // conversion, so we allow it in a converted constant expression.
6504 //
6505 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6506 // a lot of popular code. We should at least add a warning for this
6507 // (non-conforming) extension.
6509 SCS.getToType(2)->isBooleanType();
6510
6512 case ICK_Pointer_Member:
6513 // C++1z: null pointer conversions and null member pointer conversions are
6514 // only permitted if the source type is std::nullptr_t.
6515 return SCS.getFromType()->isNullPtrType();
6516
6529 case ICK_Vector_Splat:
6530 case ICK_Complex_Real:
6541 return false;
6542
6547 llvm_unreachable("found a first conversion kind in Second");
6548
6550 case ICK_Qualification:
6551 llvm_unreachable("found a third conversion kind in Second");
6552
6554 break;
6555 }
6556
6557 llvm_unreachable("unknown conversion kind");
6558}
6559
6560/// BuildConvertedConstantExpression - Check that the expression From is a
6561/// converted constant expression of type T, perform the conversion but
6562/// does not evaluate the expression
6564 QualType T, CCEKind CCE,
6565 NamedDecl *Dest,
6566 APValue &PreNarrowingValue) {
6567 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6569 CCE == CCEKind::PackIndex);
6570 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6571 "converted constant expression outside C++11 or TTP matching");
6572
6573 if (checkPlaceholderForOverload(S, From))
6574 return ExprError();
6575
6576 if (From->containsErrors()) {
6577 if (S.Context.hasSameType(From->getType(), T))
6578 return From;
6579
6580 // The expression already has errors, so the correct cast kind can't be
6581 // determined. Use RecoveryExpr to keep the expected type T and mark the
6582 // result as invalid, preventing further cascading errors.
6583 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6584 T);
6585 }
6586
6587 // C++1z [expr.const]p3:
6588 // A converted constant expression of type T is an expression,
6589 // implicitly converted to type T, where the converted
6590 // expression is a constant expression and the implicit conversion
6591 // sequence contains only [... list of conversions ...].
6593 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6595 : TryCopyInitialization(S, From, T,
6596 /*SuppressUserConversions=*/false,
6597 /*InOverloadResolution=*/false,
6598 /*AllowObjCWritebackConversion=*/false,
6599 /*AllowExplicit=*/false);
6600 StandardConversionSequence *SCS = nullptr;
6601 switch (ICS.getKind()) {
6603 SCS = &ICS.Standard;
6604 break;
6606 if (T->isRecordType())
6607 SCS = &ICS.UserDefined.Before;
6608 else
6609 SCS = &ICS.UserDefined.After;
6610 break;
6614 return S.Diag(From->getBeginLoc(),
6615 diag::err_typecheck_converted_constant_expression)
6616 << From->getType() << From->getSourceRange() << T;
6617 return ExprError();
6618
6621 llvm_unreachable("bad conversion in converted constant expression");
6622 }
6623
6624 // Check that we would only use permitted conversions.
6625 if (!CheckConvertedConstantConversions(S, *SCS)) {
6626 return S.Diag(From->getBeginLoc(),
6627 diag::err_typecheck_converted_constant_expression_disallowed)
6628 << From->getType() << From->getSourceRange() << T;
6629 }
6630 // [...] and where the reference binding (if any) binds directly.
6631 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6632 return S.Diag(From->getBeginLoc(),
6633 diag::err_typecheck_converted_constant_expression_indirect)
6634 << From->getType() << From->getSourceRange() << T;
6635 }
6636 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6637 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6638 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6639 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6640 // case explicitly.
6641 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6642 return S.Diag(From->getBeginLoc(),
6643 diag::err_reference_bind_to_bitfield_in_cce)
6644 << From->getSourceRange();
6645 }
6646
6647 // Usually we can simply apply the ImplicitConversionSequence we formed
6648 // earlier, but that's not guaranteed to work when initializing an object of
6649 // class type.
6651 bool IsTemplateArgument =
6653 if (T->isRecordType()) {
6654 assert(IsTemplateArgument &&
6655 "unexpected class type converted constant expr");
6659 SourceLocation(), From);
6660 } else {
6661 Result =
6663 }
6664 if (Result.isInvalid())
6665 return Result;
6666
6667 // C++2a [intro.execution]p5:
6668 // A full-expression is [...] a constant-expression [...]
6669 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6670 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6671 IsTemplateArgument);
6672 if (Result.isInvalid())
6673 return Result;
6674
6675 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6676
6677 // Check for a narrowing implicit conversion.
6678 bool ReturnPreNarrowingValue = false;
6679 QualType PreNarrowingType;
6680 switch (SCS->getNarrowingKind(
6681 S.Context, Result.get(), PreNarrowingValue, PreNarrowingType,
6682 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6684 // Implicit conversion to a narrower type, and the value is not a constant
6685 // expression. We'll diagnose this in a moment.
6686 case NK_Not_Narrowing:
6687 break;
6688
6690 if (CCE == CCEKind::ArrayBound &&
6691 PreNarrowingType->isIntegralOrEnumerationType() &&
6692 PreNarrowingValue.isInt()) {
6693 // Don't diagnose array bound narrowing here; we produce more precise
6694 // errors by allowing the un-narrowed value through.
6695 ReturnPreNarrowingValue = true;
6696 break;
6697 }
6698 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6699 << CCE << /*Constant*/ 1
6700 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6701 // If this is an SFINAE Context, treat the result as invalid so it stops
6702 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6703 // FIXME: Should do this whenever the above diagnostic is an error, but
6704 // without further changes this would degrade some other diagnostics.
6705 if (S.isSFINAEContext())
6706 return ExprError();
6707 break;
6708
6710 // Implicit conversion to a narrower type, but the expression is
6711 // value-dependent so we can't tell whether it's actually narrowing.
6712 // For matching the parameters of a TTP, the conversion is ill-formed
6713 // if it may narrow.
6714 if (CCE != CCEKind::TempArgStrict)
6715 break;
6716 [[fallthrough]];
6717 case NK_Type_Narrowing:
6718 // FIXME: It would be better to diagnose that the expression is not a
6719 // constant expression.
6720 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6721 << CCE << /*Constant*/ 0 << From->getType() << T;
6722 if (S.isSFINAEContext())
6723 return ExprError();
6724 break;
6725 }
6726 if (!ReturnPreNarrowingValue)
6727 PreNarrowingValue = {};
6728
6729 return Result;
6730}
6731
6732/// CheckConvertedConstantExpression - Check that the expression From is a
6733/// converted constant expression of type T, perform the conversion and produce
6734/// the converted expression, per C++11 [expr.const]p3.
6737 CCEKind CCE, bool RequireInt,
6738 NamedDecl *Dest) {
6739
6740 APValue PreNarrowingValue;
6742 PreNarrowingValue);
6743 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6744 Value = APValue();
6745 return Result;
6746 }
6747 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6748 RequireInt, PreNarrowingValue);
6749}
6750
6752 CCEKind CCE,
6753 NamedDecl *Dest) {
6754 APValue PreNarrowingValue;
6755 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6756 PreNarrowingValue);
6757}
6758
6760 APValue &Value, CCEKind CCE,
6761 NamedDecl *Dest) {
6762 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6763 Dest);
6764}
6765
6767 llvm::APSInt &Value,
6768 CCEKind CCE) {
6769 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6770
6771 APValue V;
6772 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6773 /*Dest=*/nullptr);
6774 if (!R.isInvalid() && !R.get()->isValueDependent())
6775 Value = V.getInt();
6776 return R;
6777}
6778
6781 CCEKind CCE, bool RequireInt,
6782 const APValue &PreNarrowingValue) {
6783
6784 ExprResult Result = E;
6785 // Check the expression is a constant expression.
6788 Expr::EvalResult Eval;
6789 Eval.Diag = &Notes;
6790 Eval.ExtendedDiag = &MSWarning;
6791
6792 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6793
6794 ConstantExprKind Kind;
6795 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6796 Kind = ConstantExprKind::ClassTemplateArgument;
6797 else if (CCE == CCEKind::TemplateArg)
6798 Kind = ConstantExprKind::NonClassTemplateArgument;
6799 else
6800 Kind = ConstantExprKind::Normal;
6801
6802 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6803 (RequireInt && !Eval.Val.isInt())) {
6804 // The expression can't be folded, so we can't keep it at this position in
6805 // the AST.
6806 Result = ExprError();
6807 } else {
6808 Value = Eval.Val;
6809 // For -fms-compatibility mode we relax some requirements
6810 // for constant folding in non-SFINAE contexts
6811 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6812 if (Notes.empty() && !CantFold) {
6813 for (auto &Info : MSWarning)
6814 Diag(Info.first, Info.second);
6815 // It's a constant expression.
6816 Expr *E = Result.get();
6817 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6818 // We expect a ConstantExpr to have a value associated with it
6819 // by this point.
6820 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6821 "ConstantExpr has no value associated with it");
6822 (void)CE;
6823 } else {
6825 }
6826 if (!PreNarrowingValue.isAbsent())
6827 Value = std::move(PreNarrowingValue);
6828 return E;
6829 }
6830 }
6831
6832 // It's not a constant expression. Produce an appropriate diagnostic.
6833 if (Notes.size() == 1 &&
6834 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6835 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6836 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6837 diag::note_constexpr_invalid_template_arg) {
6838 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6839 for (unsigned I = 0; I < Notes.size(); ++I)
6840 Diag(Notes[I].first, Notes[I].second);
6841 } else {
6842 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6843 << CCE << E->getSourceRange();
6844 for (unsigned I = 0; I < Notes.size(); ++I)
6845 Diag(Notes[I].first, Notes[I].second);
6846 }
6847 return ExprError();
6848}
6849
6850/// dropPointerConversions - If the given standard conversion sequence
6851/// involves any pointer conversions, remove them. This may change
6852/// the result type of the conversion sequence.
6854 if (SCS.Second == ICK_Pointer_Conversion) {
6855 SCS.Second = ICK_Identity;
6856 SCS.Dimension = ICK_Identity;
6857 SCS.Third = ICK_Identity;
6858 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6859 }
6860}
6861
6862/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6863/// convert the expression From to an Objective-C pointer type.
6864static ImplicitConversionSequence
6866 // Do an implicit conversion to 'id'.
6869 = TryImplicitConversion(S, From, Ty,
6870 // FIXME: Are these flags correct?
6871 /*SuppressUserConversions=*/false,
6872 AllowedExplicit::Conversions,
6873 /*InOverloadResolution=*/false,
6874 /*CStyle=*/false,
6875 /*AllowObjCWritebackConversion=*/false,
6876 /*AllowObjCConversionOnExplicit=*/true);
6877
6878 // Strip off any final conversions to 'id'.
6879 switch (ICS.getKind()) {
6884 break;
6885
6888 break;
6889
6892 break;
6893 }
6894
6895 return ICS;
6896}
6897
6899 if (checkPlaceholderForOverload(*this, From))
6900 return ExprError();
6901
6902 QualType Ty = Context.getObjCIdType();
6905 if (!ICS.isBad())
6906 return PerformImplicitConversion(From, Ty, ICS,
6908 return ExprResult();
6909}
6910
6911static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6912 const Expr *Base = nullptr;
6913 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6914 "expected a member expression");
6915
6916 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6917 M && !M->isImplicitAccess())
6918 Base = M->getBase();
6919 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6920 M && !M->isImplicitAccess())
6921 Base = M->getBase();
6922
6923 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6924
6925 if (T->isPointerType())
6926 T = T->getPointeeType();
6927
6928 return T;
6929}
6930
6932 const FunctionDecl *Fun) {
6933 QualType ObjType = Obj->getType();
6934 if (ObjType->isPointerType()) {
6935 ObjType = ObjType->getPointeeType();
6936 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6938 /*CanOverflow=*/false, FPOptionsOverride());
6939 }
6940 return Obj;
6941}
6942
6950
6952 Expr *Object, MultiExprArg &Args,
6953 SmallVectorImpl<Expr *> &NewArgs) {
6954 assert(Method->isExplicitObjectMemberFunction() &&
6955 "Method is not an explicit member function");
6956 assert(NewArgs.empty() && "NewArgs should be empty");
6957
6958 NewArgs.reserve(Args.size() + 1);
6959 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6960 NewArgs.push_back(This);
6961 NewArgs.append(Args.begin(), Args.end());
6962 Args = NewArgs;
6964 Method, Object->getBeginLoc());
6965}
6966
6967/// Determine whether the provided type is an integral type, or an enumeration
6968/// type of a permitted flavor.
6970 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6971 : T->isIntegralOrUnscopedEnumerationType();
6972}
6973
6974static ExprResult
6977 QualType T, UnresolvedSetImpl &ViableConversions) {
6978
6979 if (Converter.Suppress)
6980 return ExprError();
6981
6982 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6983 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6984 CXXConversionDecl *Conv =
6985 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6987 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6988 }
6989 return From;
6990}
6991
6992static bool
6995 QualType T, bool HadMultipleCandidates,
6996 UnresolvedSetImpl &ExplicitConversions) {
6997 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6998 DeclAccessPair Found = ExplicitConversions[0];
6999 CXXConversionDecl *Conversion =
7000 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
7001
7002 // The user probably meant to invoke the given explicit
7003 // conversion; use it.
7004 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
7005 std::string TypeStr;
7006 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
7007
7008 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
7010 "static_cast<" + TypeStr + ">(")
7012 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
7013 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
7014
7015 // If we aren't in a SFINAE context, build a call to the
7016 // explicit conversion function.
7017 if (SemaRef.isSFINAEContext())
7018 return true;
7019
7020 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
7021 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7022 HadMultipleCandidates);
7023 if (Result.isInvalid())
7024 return true;
7025
7026 // Replace the conversion with a RecoveryExpr, so we don't try to
7027 // instantiate it later, but can further diagnose here.
7028 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
7029 From, Result.get()->getType());
7030 if (Result.isInvalid())
7031 return true;
7032 From = Result.get();
7033 }
7034 return false;
7035}
7036
7037static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
7039 QualType T, bool HadMultipleCandidates,
7041 CXXConversionDecl *Conversion =
7042 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
7043 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
7044
7045 QualType ToType = Conversion->getConversionType().getNonReferenceType();
7046 if (!Converter.SuppressConversion) {
7047 if (SemaRef.isSFINAEContext())
7048 return true;
7049
7050 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
7051 << From->getSourceRange();
7052 }
7053
7054 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7055 HadMultipleCandidates);
7056 if (Result.isInvalid())
7057 return true;
7058 // Record usage of conversion in an implicit cast.
7059 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
7060 CK_UserDefinedConversion, Result.get(),
7061 nullptr, Result.get()->getValueKind(),
7062 SemaRef.CurFPFeatureOverrides());
7063 return false;
7064}
7065
7067 Sema &SemaRef, SourceLocation Loc, Expr *From,
7069 if (!Converter.match(From->getType()) && !Converter.Suppress)
7070 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
7071 << From->getSourceRange();
7072
7073 return SemaRef.DefaultLvalueConversion(From);
7074}
7075
7076static void
7078 UnresolvedSetImpl &ViableConversions,
7079 OverloadCandidateSet &CandidateSet) {
7080 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7081 NamedDecl *D = FoundDecl.getDecl();
7082 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7083 if (isa<UsingShadowDecl>(D))
7084 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7085
7086 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7088 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7089 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7090 continue;
7091 }
7093 SemaRef.AddConversionCandidate(
7094 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7095 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7096 }
7097}
7098
7099/// Attempt to convert the given expression to a type which is accepted
7100/// by the given converter.
7101///
7102/// This routine will attempt to convert an expression of class type to a
7103/// type accepted by the specified converter. In C++11 and before, the class
7104/// must have a single non-explicit conversion function converting to a matching
7105/// type. In C++1y, there can be multiple such conversion functions, but only
7106/// one target type.
7107///
7108/// \param Loc The source location of the construct that requires the
7109/// conversion.
7110///
7111/// \param From The expression we're converting from.
7112///
7113/// \param Converter Used to control and diagnose the conversion process.
7114///
7115/// \returns The expression, converted to an integral or enumeration type if
7116/// successful.
7118 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7119 // We can't perform any more checking for type-dependent expressions.
7120 if (From->isTypeDependent())
7121 return From;
7122
7123 // Process placeholders immediately.
7124 if (From->hasPlaceholderType()) {
7125 ExprResult result = CheckPlaceholderExpr(From);
7126 if (result.isInvalid())
7127 return result;
7128 From = result.get();
7129 }
7130
7131 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7132 ExprResult Converted = DefaultLvalueConversion(From);
7133 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7134 From = Converted.isUsable() ? Converted.get() : nullptr;
7135 // If the expression already has a matching type, we're golden.
7136 if (Converter.match(T))
7137 return Converted;
7138
7139 // FIXME: Check for missing '()' if T is a function type?
7140
7141 // We can only perform contextual implicit conversions on objects of class
7142 // type.
7143 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7144 if (!RecordTy || !getLangOpts().CPlusPlus) {
7145 if (!Converter.Suppress)
7146 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7147 return From;
7148 }
7149
7150 // We must have a complete class type.
7151 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7152 ContextualImplicitConverter &Converter;
7153 Expr *From;
7154
7155 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7156 : Converter(Converter), From(From) {}
7157
7158 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7159 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7160 }
7161 } IncompleteDiagnoser(Converter, From);
7162
7163 if (Converter.Suppress ? !isCompleteType(Loc, T)
7164 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7165 return From;
7166
7167 // Look for a conversion to an integral or enumeration type.
7169 ViableConversions; // These are *potentially* viable in C++1y.
7170 UnresolvedSet<4> ExplicitConversions;
7171 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7172 ->getDefinitionOrSelf()
7173 ->getVisibleConversionFunctions();
7174
7175 bool HadMultipleCandidates =
7176 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7177
7178 // To check that there is only one target type, in C++1y:
7179 QualType ToType;
7180 bool HasUniqueTargetType = true;
7181
7182 // Collect explicit or viable (potentially in C++1y) conversions.
7183 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7184 NamedDecl *D = (*I)->getUnderlyingDecl();
7185 CXXConversionDecl *Conversion;
7186 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7187 if (ConvTemplate) {
7189 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7190 else
7191 continue; // C++11 does not consider conversion operator templates(?).
7192 } else
7193 Conversion = cast<CXXConversionDecl>(D);
7194
7195 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7196 "Conversion operator templates are considered potentially "
7197 "viable in C++1y");
7198
7199 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7200 if (Converter.match(CurToType) || ConvTemplate) {
7201
7202 if (Conversion->isExplicit()) {
7203 // FIXME: For C++1y, do we need this restriction?
7204 // cf. diagnoseNoViableConversion()
7205 if (!ConvTemplate)
7206 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7207 } else {
7208 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7209 if (ToType.isNull())
7210 ToType = CurToType.getUnqualifiedType();
7211 else if (HasUniqueTargetType &&
7212 (CurToType.getUnqualifiedType() != ToType))
7213 HasUniqueTargetType = false;
7214 }
7215 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7216 }
7217 }
7218 }
7219
7220 if (getLangOpts().CPlusPlus14) {
7221 // C++1y [conv]p6:
7222 // ... An expression e of class type E appearing in such a context
7223 // is said to be contextually implicitly converted to a specified
7224 // type T and is well-formed if and only if e can be implicitly
7225 // converted to a type T that is determined as follows: E is searched
7226 // for conversion functions whose return type is cv T or reference to
7227 // cv T such that T is allowed by the context. There shall be
7228 // exactly one such T.
7229
7230 // If no unique T is found:
7231 if (ToType.isNull()) {
7232 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7233 HadMultipleCandidates,
7234 ExplicitConversions))
7235 return ExprError();
7236 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7237 }
7238
7239 // If more than one unique Ts are found:
7240 if (!HasUniqueTargetType)
7241 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7242 ViableConversions);
7243
7244 // If one unique T is found:
7245 // First, build a candidate set from the previously recorded
7246 // potentially viable conversions.
7248 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7249 CandidateSet);
7250
7251 // Then, perform overload resolution over the candidate set.
7253 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7254 case OR_Success: {
7255 // Apply this conversion.
7257 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7258 if (recordConversion(*this, Loc, From, Converter, T,
7259 HadMultipleCandidates, Found))
7260 return ExprError();
7261 break;
7262 }
7263 case OR_Ambiguous:
7264 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7265 ViableConversions);
7267 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7268 HadMultipleCandidates,
7269 ExplicitConversions))
7270 return ExprError();
7271 [[fallthrough]];
7272 case OR_Deleted:
7273 // We'll complain below about a non-integral condition type.
7274 break;
7275 }
7276 } else {
7277 switch (ViableConversions.size()) {
7278 case 0: {
7279 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7280 HadMultipleCandidates,
7281 ExplicitConversions))
7282 return ExprError();
7283
7284 // We'll complain below about a non-integral condition type.
7285 break;
7286 }
7287 case 1: {
7288 // Apply this conversion.
7289 DeclAccessPair Found = ViableConversions[0];
7290 if (recordConversion(*this, Loc, From, Converter, T,
7291 HadMultipleCandidates, Found))
7292 return ExprError();
7293 break;
7294 }
7295 default:
7296 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7297 ViableConversions);
7298 }
7299 }
7300
7301 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7302}
7303
7304/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7305/// an acceptable non-member overloaded operator for a call whose
7306/// arguments have types T1 (and, if non-empty, T2). This routine
7307/// implements the check in C++ [over.match.oper]p3b2 concerning
7308/// enumeration types.
7310 FunctionDecl *Fn,
7311 ArrayRef<Expr *> Args) {
7312 QualType T1 = Args[0]->getType();
7313 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7314
7315 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7316 return true;
7317
7318 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7319 return true;
7320
7321 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7322 if (Proto->getNumParams() < 1)
7323 return false;
7324
7325 if (T1->isEnumeralType()) {
7326 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7327 if (Context.hasSameUnqualifiedType(T1, ArgType))
7328 return true;
7329 }
7330
7331 if (Proto->getNumParams() < 2)
7332 return false;
7333
7334 if (!T2.isNull() && T2->isEnumeralType()) {
7335 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7336 if (Context.hasSameUnqualifiedType(T2, ArgType))
7337 return true;
7338 }
7339
7340 return false;
7341}
7342
7345 return false;
7346
7347 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7348 return FD->isTargetMultiVersion();
7349
7350 if (!FD->isMultiVersion())
7351 return false;
7352
7353 // Among multiple target versions consider either the default,
7354 // or the first non-default in the absence of default version.
7355 unsigned SeenAt = 0;
7356 unsigned I = 0;
7357 bool HasDefault = false;
7359 FD, [&](const FunctionDecl *CurFD) {
7360 if (FD == CurFD)
7361 SeenAt = I;
7362 else if (CurFD->isTargetMultiVersionDefault())
7363 HasDefault = true;
7364 ++I;
7365 });
7366 return HasDefault || SeenAt != 0;
7367}
7368
7371 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7372 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7373 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7374 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7375 bool StrictPackMatch) {
7376 const FunctionProtoType *Proto
7377 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7378 assert(Proto && "Functions without a prototype cannot be overloaded");
7379 assert(!Function->getDescribedFunctionTemplate() &&
7380 "Use AddTemplateOverloadCandidate for function templates");
7381
7382 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7384 // If we get here, it's because we're calling a member function
7385 // that is named without a member access expression (e.g.,
7386 // "this->f") that was either written explicitly or created
7387 // implicitly. This can happen with a qualified call to a member
7388 // function, e.g., X::f(). We use an empty type for the implied
7389 // object argument (C++ [over.call.func]p3), and the acting context
7390 // is irrelevant.
7391 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7393 CandidateSet, SuppressUserConversions,
7394 PartialOverloading, EarlyConversions, PO,
7395 StrictPackMatch);
7396 return;
7397 }
7398 // We treat a constructor like a non-member function, since its object
7399 // argument doesn't participate in overload resolution.
7400 }
7401
7402 if (!CandidateSet.isNewCandidate(Function, PO))
7403 return;
7404
7405 // C++11 [class.copy]p11: [DR1402]
7406 // A defaulted move constructor that is defined as deleted is ignored by
7407 // overload resolution.
7408 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7409 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7410 Constructor->isMoveConstructor())
7411 return;
7412
7413 // Overload resolution is always an unevaluated context.
7416
7417 // C++ [over.match.oper]p3:
7418 // if no operand has a class type, only those non-member functions in the
7419 // lookup set that have a first parameter of type T1 or "reference to
7420 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7421 // is a right operand) a second parameter of type T2 or "reference to
7422 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7423 // candidate functions.
7424 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7426 return;
7427
7428 // Add this candidate
7429 OverloadCandidate &Candidate =
7430 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7431 Candidate.FoundDecl = FoundDecl;
7432 Candidate.Function = Function;
7433 Candidate.Viable = true;
7434 Candidate.RewriteKind =
7435 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7436 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7437 Candidate.ExplicitCallArguments = Args.size();
7438 Candidate.StrictPackMatch = StrictPackMatch;
7439
7440 // Explicit functions are not actually candidates at all if we're not
7441 // allowing them in this context, but keep them around so we can point
7442 // to them in diagnostics.
7443 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7444 Candidate.Viable = false;
7445 Candidate.FailureKind = ovl_fail_explicit;
7446 return;
7447 }
7448
7449 // Functions with internal linkage are only viable in the same module unit.
7450 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7451 /// FIXME: Currently, the semantics of linkage in clang is slightly
7452 /// different from the semantics in C++ spec. In C++ spec, only names
7453 /// have linkage. So that all entities of the same should share one
7454 /// linkage. But in clang, different entities of the same could have
7455 /// different linkage.
7456 const NamedDecl *ND = Function;
7457 bool IsImplicitlyInstantiated = false;
7458 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7459 ND = SpecInfo->getTemplate();
7460 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7462 }
7463
7464 /// Don't remove inline functions with internal linkage from the overload
7465 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7466 /// However:
7467 /// - Inline functions with internal linkage are a common pattern in
7468 /// headers to avoid ODR issues.
7469 /// - The global module is meant to be a transition mechanism for C and C++
7470 /// headers, and the current rules as written work against that goal.
7471 const bool IsInlineFunctionInGMF =
7472 Function->isFromGlobalModule() &&
7473 (IsImplicitlyInstantiated || Function->isInlined());
7474
7475 // Don't exclude internal-linkage entities from the current TU's global
7476 // module fragment.
7477 const Module *CurrentModule = getCurrentModule();
7478 const bool IsCurrentUnitGMFDecl =
7479 Function->isFromGlobalModule() && CurrentModule &&
7480 Function->getOwningModule()->getTopLevelModule() ==
7481 CurrentModule->getTopLevelModule();
7482
7483 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7484 !IsCurrentUnitGMFDecl) {
7485 Candidate.Viable = false;
7487 return;
7488 }
7489 }
7490
7492 Candidate.Viable = false;
7494 return;
7495 }
7496
7497 if (Constructor) {
7498 // C++ [class.copy]p3:
7499 // A member function template is never instantiated to perform the copy
7500 // of a class object to an object of its class type.
7501 CanQualType ClassType =
7502 Context.getCanonicalTagType(Constructor->getParent());
7503 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7504 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7505 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7506 ClassType))) {
7507 Candidate.Viable = false;
7509 return;
7510 }
7511
7512 // C++ [over.match.funcs]p8: (proposed DR resolution)
7513 // A constructor inherited from class type C that has a first parameter
7514 // of type "reference to P" (including such a constructor instantiated
7515 // from a template) is excluded from the set of candidate functions when
7516 // constructing an object of type cv D if the argument list has exactly
7517 // one argument and D is reference-related to P and P is reference-related
7518 // to C.
7519 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7520 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7521 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7522 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7523 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7524 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7525 SourceLocation Loc = Args.front()->getExprLoc();
7526 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7527 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7528 Candidate.Viable = false;
7530 return;
7531 }
7532 }
7533
7534 // Check that the constructor is capable of constructing an object in the
7535 // destination address space.
7537 Constructor->getMethodQualifiers().getAddressSpace(),
7538 CandidateSet.getDestAS(), getASTContext())) {
7539 Candidate.Viable = false;
7541 }
7542 }
7543
7544 unsigned NumParams = Proto->getNumParams();
7545
7546 // (C++ 13.3.2p2): A candidate function having fewer than m
7547 // parameters is viable only if it has an ellipsis in its parameter
7548 // list (8.3.5).
7549 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7550 !Proto->isVariadic() &&
7551 shouldEnforceArgLimit(PartialOverloading, Function)) {
7552 Candidate.Viable = false;
7554 return;
7555 }
7556
7557 // (C++ 13.3.2p2): A candidate function having more than m parameters
7558 // is viable only if the (m+1)st parameter has a default argument
7559 // (8.3.6). For the purposes of overload resolution, the
7560 // parameter list is truncated on the right, so that there are
7561 // exactly m parameters.
7562 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7563 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7564 !PartialOverloading) {
7565 // Not enough arguments.
7566 Candidate.Viable = false;
7568 return;
7569 }
7570
7571 // (CUDA B.1): Check for invalid calls between targets.
7572 if (getLangOpts().CUDA) {
7573 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7574 // Skip the check for callers that are implicit members, because in this
7575 // case we may not yet know what the member's target is; the target is
7576 // inferred for the member automatically, based on the bases and fields of
7577 // the class.
7578 if (!(Caller && Caller->isImplicit()) &&
7579 !CUDA().IsAllowedCall(Caller, Function)) {
7580 Candidate.Viable = false;
7581 Candidate.FailureKind = ovl_fail_bad_target;
7582 return;
7583 }
7584 }
7585
7586 if (Function->getTrailingRequiresClause()) {
7587 ConstraintSatisfaction Satisfaction;
7588 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7589 /*ForOverloadResolution*/ true) ||
7590 !Satisfaction.IsSatisfied) {
7591 Candidate.Viable = false;
7593 return;
7594 }
7595 }
7596
7597 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7598 // Determine the implicit conversion sequences for each of the
7599 // arguments.
7600 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7601 unsigned ConvIdx =
7602 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7603 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7604 // We already formed a conversion sequence for this parameter during
7605 // template argument deduction.
7606 } else if (ArgIdx < NumParams) {
7607 // (C++ 13.3.2p3): for F to be a viable function, there shall
7608 // exist for each argument an implicit conversion sequence
7609 // (13.3.3.1) that converts that argument to the corresponding
7610 // parameter of F.
7611 QualType ParamType = Proto->getParamType(ArgIdx);
7612 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7613 if (ParamABI == ParameterABI::HLSLOut ||
7614 ParamABI == ParameterABI::HLSLInOut) {
7615 ParamType = ParamType.getNonReferenceType();
7616 if (ParamABI == ParameterABI::HLSLInOut &&
7617 Args[ArgIdx]->getType().getAddressSpace() ==
7619 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7620 }
7621 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7622 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7623 /*InOverloadResolution=*/true,
7624 /*AllowObjCWritebackConversion=*/
7625 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7626 if (Candidate.Conversions[ConvIdx].isBad()) {
7627 Candidate.Viable = false;
7629 return;
7630 }
7631 } else {
7632 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7633 // argument for which there is no corresponding parameter is
7634 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7635 Candidate.Conversions[ConvIdx].setEllipsis();
7636 }
7637 }
7638
7639 if (EnableIfAttr *FailedAttr =
7640 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7641 Candidate.Viable = false;
7642 Candidate.FailureKind = ovl_fail_enable_if;
7643 Candidate.DeductionFailure.Data = FailedAttr;
7644 return;
7645 }
7646}
7647
7651 if (Methods.size() <= 1)
7652 return nullptr;
7653
7654 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7655 bool Match = true;
7656 ObjCMethodDecl *Method = Methods[b];
7657 unsigned NumNamedArgs = Sel.getNumArgs();
7658 // Method might have more arguments than selector indicates. This is due
7659 // to addition of c-style arguments in method.
7660 if (Method->param_size() > NumNamedArgs)
7661 NumNamedArgs = Method->param_size();
7662 if (Args.size() < NumNamedArgs)
7663 continue;
7664
7665 for (unsigned i = 0; i < NumNamedArgs; i++) {
7666 // We can't do any type-checking on a type-dependent argument.
7667 if (Args[i]->isTypeDependent()) {
7668 Match = false;
7669 break;
7670 }
7671
7672 ParmVarDecl *param = Method->parameters()[i];
7673 Expr *argExpr = Args[i];
7674 assert(argExpr && "SelectBestMethod(): missing expression");
7675
7676 // Strip the unbridged-cast placeholder expression off unless it's
7677 // a consumed argument.
7678 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7679 !param->hasAttr<CFConsumedAttr>())
7680 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7681
7682 // If the parameter is __unknown_anytype, move on to the next method.
7683 if (param->getType() == Context.UnknownAnyTy) {
7684 Match = false;
7685 break;
7686 }
7687
7688 ImplicitConversionSequence ConversionState
7689 = TryCopyInitialization(*this, argExpr, param->getType(),
7690 /*SuppressUserConversions*/false,
7691 /*InOverloadResolution=*/true,
7692 /*AllowObjCWritebackConversion=*/
7693 getLangOpts().ObjCAutoRefCount,
7694 /*AllowExplicit*/false);
7695 // This function looks for a reasonably-exact match, so we consider
7696 // incompatible pointer conversions to be a failure here.
7697 if (ConversionState.isBad() ||
7698 (ConversionState.isStandard() &&
7699 ConversionState.Standard.Second ==
7701 Match = false;
7702 break;
7703 }
7704 }
7705 // Promote additional arguments to variadic methods.
7706 if (Match && Method->isVariadic()) {
7707 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7708 if (Args[i]->isTypeDependent()) {
7709 Match = false;
7710 break;
7711 }
7713 Args[i], VariadicCallType::Method, nullptr);
7714 if (Arg.isInvalid()) {
7715 Match = false;
7716 break;
7717 }
7718 }
7719 } else {
7720 // Check for extra arguments to non-variadic methods.
7721 if (Args.size() != NumNamedArgs)
7722 Match = false;
7723 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7724 // Special case when selectors have no argument. In this case, select
7725 // one with the most general result type of 'id'.
7726 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7727 QualType ReturnT = Methods[b]->getReturnType();
7728 if (ReturnT->isObjCIdType())
7729 return Methods[b];
7730 }
7731 }
7732 }
7733
7734 if (Match)
7735 return Method;
7736 }
7737 return nullptr;
7738}
7739
7741 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7742 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7743 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7744 if (ThisArg) {
7745 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7746 assert(!isa<CXXConstructorDecl>(Method) &&
7747 "Shouldn't have `this` for ctors!");
7748 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7750 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7751 if (R.isInvalid())
7752 return false;
7753 ConvertedThis = R.get();
7754 } else {
7755 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7756 (void)MD;
7757 assert((MissingImplicitThis || MD->isStatic() ||
7759 "Expected `this` for non-ctor instance methods");
7760 }
7761 ConvertedThis = nullptr;
7762 }
7763
7764 // Ignore any variadic arguments. Converting them is pointless, since the
7765 // user can't refer to them in the function condition.
7766 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7767
7768 // Convert the arguments.
7769 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7770 ExprResult R;
7772 S.Context, Function->getParamDecl(I)),
7773 SourceLocation(), Args[I]);
7774
7775 if (R.isInvalid())
7776 return false;
7777
7778 ConvertedArgs.push_back(R.get());
7779 }
7780
7781 if (Trap.hasErrorOccurred())
7782 return false;
7783
7784 // Push default arguments if needed.
7785 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7786 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7787 ParmVarDecl *P = Function->getParamDecl(i);
7788 if (!P->hasDefaultArg())
7789 return false;
7790 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7791 if (R.isInvalid())
7792 return false;
7793 ConvertedArgs.push_back(R.get());
7794 }
7795
7796 if (Trap.hasErrorOccurred())
7797 return false;
7798 }
7799 return true;
7800}
7801
7803 SourceLocation CallLoc,
7804 ArrayRef<Expr *> Args,
7805 bool MissingImplicitThis) {
7806 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7807 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7808 return nullptr;
7809
7810 SFINAETrap Trap(*this);
7811 // Perform the access checking immediately so any access diagnostics are
7812 // caught by the SFINAE trap.
7813 llvm::scope_exit UndelayDiags(
7814 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7815 DelayedDiagnostics.popUndelayed(CurrentState);
7816 });
7817 SmallVector<Expr *, 16> ConvertedArgs;
7818 // FIXME: We should look into making enable_if late-parsed.
7819 Expr *DiscardedThis;
7821 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7822 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7823 return *EnableIfAttrs.begin();
7824
7825 for (auto *EIA : EnableIfAttrs) {
7827 // FIXME: This doesn't consider value-dependent cases, because doing so is
7828 // very difficult. Ideally, we should handle them more gracefully.
7829 if (EIA->getCond()->isValueDependent() ||
7830 !EIA->getCond()->EvaluateWithSubstitution(
7831 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7832 return EIA;
7833
7834 if (!Result.isInt() || !Result.getInt().getBoolValue())
7835 return EIA;
7836 }
7837 return nullptr;
7838}
7839
7840template <typename CheckFn>
7842 bool ArgDependent, SourceLocation Loc,
7843 CheckFn &&IsSuccessful) {
7845 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7846 if (ArgDependent == DIA->getArgDependent())
7847 Attrs.push_back(DIA);
7848 }
7849
7850 // Common case: No diagnose_if attributes, so we can quit early.
7851 if (Attrs.empty())
7852 return false;
7853
7854 auto WarningBegin = std::stable_partition(
7855 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7856 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7857 DIA->getWarningGroup().empty();
7858 });
7859
7860 // Note that diagnose_if attributes are late-parsed, so they appear in the
7861 // correct order (unlike enable_if attributes).
7862 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7863 IsSuccessful);
7864 if (ErrAttr != WarningBegin) {
7865 const DiagnoseIfAttr *DIA = *ErrAttr;
7866 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7867 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7868 << DIA->getParent() << DIA->getCond()->getSourceRange();
7869 return true;
7870 }
7871
7872 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7873 switch (Sev) {
7874 case DiagnoseIfAttr::DS_warning:
7876 case DiagnoseIfAttr::DS_error:
7877 return diag::Severity::Error;
7878 }
7879 llvm_unreachable("Fully covered switch above!");
7880 };
7881
7882 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7883 if (IsSuccessful(DIA)) {
7884 if (DIA->getWarningGroup().empty() &&
7885 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7886 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7887 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7888 << DIA->getParent() << DIA->getCond()->getSourceRange();
7889 } else {
7890 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7891 DIA->getWarningGroup());
7892 assert(DiagGroup);
7893 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7894 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7895 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7896 S.Diag(Loc, DiagID) << DIA->getMessage();
7897 }
7898 }
7899
7900 return false;
7901}
7902
7904 const Expr *ThisArg,
7906 SourceLocation Loc) {
7908 *this, Function, /*ArgDependent=*/true, Loc,
7909 [&](const DiagnoseIfAttr *DIA) {
7911 // It's sane to use the same Args for any redecl of this function, since
7912 // EvaluateWithSubstitution only cares about the position of each
7913 // argument in the arg list, not the ParmVarDecl* it maps to.
7914 if (!DIA->getCond()->EvaluateWithSubstitution(
7915 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7916 return false;
7917 return Result.isInt() && Result.getInt().getBoolValue();
7918 });
7919}
7920
7922 SourceLocation Loc) {
7924 *this, ND, /*ArgDependent=*/false, Loc,
7925 [&](const DiagnoseIfAttr *DIA) {
7926 bool Result;
7927 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7928 Result;
7929 });
7930}
7931
7933 ArrayRef<Expr *> Args,
7934 OverloadCandidateSet &CandidateSet,
7935 TemplateArgumentListInfo *ExplicitTemplateArgs,
7936 bool SuppressUserConversions,
7937 bool PartialOverloading,
7938 bool FirstArgumentIsBase) {
7939 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7940 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7941 ArrayRef<Expr *> FunctionArgs = Args;
7942
7943 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7944 FunctionDecl *FD =
7945 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7946
7947 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7948 QualType ObjectType;
7949 Expr::Classification ObjectClassification;
7950 if (Args.size() > 0) {
7951 if (Expr *E = Args[0]) {
7952 // Use the explicit base to restrict the lookup:
7953 ObjectType = E->getType();
7954 // Pointers in the object arguments are implicitly dereferenced, so we
7955 // always classify them as l-values.
7956 if (!ObjectType.isNull() && ObjectType->isPointerType())
7957 ObjectClassification = Expr::Classification::makeSimpleLValue();
7958 else
7959 ObjectClassification = E->Classify(Context);
7960 } // .. else there is an implicit base.
7961 FunctionArgs = Args.slice(1);
7962 }
7963 if (FunTmpl) {
7965 FunTmpl, F.getPair(),
7967 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7968 FunctionArgs, CandidateSet, SuppressUserConversions,
7969 PartialOverloading);
7970 } else {
7971 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7972 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7973 ObjectClassification, FunctionArgs, CandidateSet,
7974 SuppressUserConversions, PartialOverloading);
7975 }
7976 } else {
7977 // This branch handles both standalone functions and static methods.
7978
7979 // Slice the first argument (which is the base) when we access
7980 // static method as non-static.
7981 if (Args.size() > 0 &&
7982 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7983 !isa<CXXConstructorDecl>(FD)))) {
7984 assert(cast<CXXMethodDecl>(FD)->isStatic());
7985 FunctionArgs = Args.slice(1);
7986 }
7987 if (FunTmpl) {
7988 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7989 ExplicitTemplateArgs, FunctionArgs,
7990 CandidateSet, SuppressUserConversions,
7991 PartialOverloading);
7992 } else {
7993 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7994 SuppressUserConversions, PartialOverloading);
7995 }
7996 }
7997 }
7998}
7999
8001 Expr::Classification ObjectClassification,
8002 ArrayRef<Expr *> Args,
8003 OverloadCandidateSet &CandidateSet,
8004 bool SuppressUserConversions,
8006 NamedDecl *Decl = FoundDecl.getDecl();
8008
8010 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
8011
8012 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
8013 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
8014 "Expected a member function template");
8015 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
8016 /*ExplicitArgs*/ nullptr, ObjectType,
8017 ObjectClassification, Args, CandidateSet,
8018 SuppressUserConversions, false, PO);
8019 } else {
8020 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
8021 ObjectType, ObjectClassification, Args, CandidateSet,
8022 SuppressUserConversions, false, {}, PO);
8023 }
8024}
8025
8028 CXXRecordDecl *ActingContext, QualType ObjectType,
8029 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8030 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8031 bool PartialOverloading, ConversionSequenceList EarlyConversions,
8032 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
8033 const FunctionProtoType *Proto
8034 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
8035 assert(Proto && "Methods without a prototype cannot be overloaded");
8037 "Use AddOverloadCandidate for constructors");
8038
8039 if (!CandidateSet.isNewCandidate(Method, PO))
8040 return;
8041
8042 // C++11 [class.copy]p23: [DR1402]
8043 // A defaulted move assignment operator that is defined as deleted is
8044 // ignored by overload resolution.
8045 if (Method->isDefaulted() && Method->isDeleted() &&
8046 Method->isMoveAssignmentOperator())
8047 return;
8048
8049 // Overload resolution is always an unevaluated context.
8052
8053 bool IgnoreExplicitObject =
8054 (Method->isExplicitObjectMemberFunction() &&
8055 CandidateSet.getKind() ==
8057 bool ImplicitObjectMethodTreatedAsStatic =
8058 CandidateSet.getKind() ==
8060 Method->isImplicitObjectMemberFunction();
8061
8062 unsigned ExplicitOffset =
8063 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8064
8065 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8066 int(ImplicitObjectMethodTreatedAsStatic);
8067
8068 unsigned ExtraArgs =
8070 ? 0
8071 : 1;
8072
8073 // Add this candidate
8074 OverloadCandidate &Candidate =
8075 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
8076 Candidate.FoundDecl = FoundDecl;
8077 Candidate.Function = Method;
8078 Candidate.RewriteKind =
8079 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
8080 Candidate.TookAddressOfOverload =
8082 Candidate.ExplicitCallArguments = Args.size();
8083 Candidate.StrictPackMatch = StrictPackMatch;
8084
8085 // (C++ 13.3.2p2): A candidate function having fewer than m
8086 // parameters is viable only if it has an ellipsis in its parameter
8087 // list (8.3.5).
8088 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8089 !Proto->isVariadic() &&
8090 shouldEnforceArgLimit(PartialOverloading, Method)) {
8091 Candidate.Viable = false;
8093 return;
8094 }
8095
8096 // (C++ 13.3.2p2): A candidate function having more than m parameters
8097 // is viable only if the (m+1)st parameter has a default argument
8098 // (8.3.6). For the purposes of overload resolution, the
8099 // parameter list is truncated on the right, so that there are
8100 // exactly m parameters.
8101 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8102 ExplicitOffset +
8103 int(ImplicitObjectMethodTreatedAsStatic);
8104
8105 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8106 // Not enough arguments.
8107 Candidate.Viable = false;
8109 return;
8110 }
8111
8112 Candidate.Viable = true;
8113
8114 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8115 if (!IgnoreExplicitObject) {
8116 if (ObjectType.isNull())
8117 Candidate.IgnoreObjectArgument = true;
8118 else if (Method->isStatic()) {
8119 // [over.best.ics.general]p8
8120 // When the parameter is the implicit object parameter of a static member
8121 // function, the implicit conversion sequence is a standard conversion
8122 // sequence that is neither better nor worse than any other standard
8123 // conversion sequence.
8124 //
8125 // This is a rule that was introduced in C++23 to support static lambdas.
8126 // We apply it retroactively because we want to support static lambdas as
8127 // an extension and it doesn't hurt previous code.
8128 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8129 } else {
8130 // Determine the implicit conversion sequence for the object
8131 // parameter.
8132 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8133 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8134 Method, ActingContext, /*InOverloadResolution=*/true);
8135 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8136 Candidate.Viable = false;
8138 return;
8139 }
8140 }
8141 }
8142
8143 // (CUDA B.1): Check for invalid calls between targets.
8144 if (getLangOpts().CUDA)
8145 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8146 Method)) {
8147 Candidate.Viable = false;
8148 Candidate.FailureKind = ovl_fail_bad_target;
8149 return;
8150 }
8151
8152 if (Method->getTrailingRequiresClause()) {
8153 ConstraintSatisfaction Satisfaction;
8154 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8155 /*ForOverloadResolution*/ true) ||
8156 !Satisfaction.IsSatisfied) {
8157 Candidate.Viable = false;
8159 return;
8160 }
8161 }
8162
8163 // Determine the implicit conversion sequences for each of the
8164 // arguments.
8165 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8166 unsigned ConvIdx =
8167 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8168 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8169 // We already formed a conversion sequence for this parameter during
8170 // template argument deduction.
8171 } else if (ArgIdx < NumParams) {
8172 // (C++ 13.3.2p3): for F to be a viable function, there shall
8173 // exist for each argument an implicit conversion sequence
8174 // (13.3.3.1) that converts that argument to the corresponding
8175 // parameter of F.
8176 QualType ParamType;
8177 if (ImplicitObjectMethodTreatedAsStatic) {
8178 ParamType = ArgIdx == 0
8179 ? Method->getFunctionObjectParameterReferenceType()
8180 : Proto->getParamType(ArgIdx - 1);
8181 } else {
8182 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8183 }
8184 Candidate.Conversions[ConvIdx]
8185 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8186 SuppressUserConversions,
8187 /*InOverloadResolution=*/true,
8188 /*AllowObjCWritebackConversion=*/
8189 getLangOpts().ObjCAutoRefCount);
8190 if (Candidate.Conversions[ConvIdx].isBad()) {
8191 Candidate.Viable = false;
8193 return;
8194 }
8195 } else {
8196 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8197 // argument for which there is no corresponding parameter is
8198 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8199 Candidate.Conversions[ConvIdx].setEllipsis();
8200 }
8201 }
8202
8203 if (EnableIfAttr *FailedAttr =
8204 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8205 Candidate.Viable = false;
8206 Candidate.FailureKind = ovl_fail_enable_if;
8207 Candidate.DeductionFailure.Data = FailedAttr;
8208 return;
8209 }
8210
8212 Candidate.Viable = false;
8214 }
8215}
8216
8218 Sema &S, OverloadCandidateSet &CandidateSet,
8219 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8220 CXXRecordDecl *ActingContext,
8221 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8222 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8223 bool SuppressUserConversions, bool PartialOverloading,
8225
8226 // C++ [over.match.funcs]p7:
8227 // In each case where a candidate is a function template, candidate
8228 // function template specializations are generated using template argument
8229 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8230 // candidate functions in the usual way.113) A given name can refer to one
8231 // or more function templates and also to a set of overloaded non-template
8232 // functions. In such a case, the candidate functions generated from each
8233 // function template are combined with the set of non-template candidate
8234 // functions.
8235 TemplateDeductionInfo Info(CandidateSet.getLocation());
8236 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8237 FunctionDecl *Specialization = nullptr;
8238 ConversionSequenceList Conversions;
8240 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8241 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8242 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8243 CandidateSet.getKind() ==
8245 [&](ArrayRef<QualType> ParamTypes,
8246 bool OnlyInitializeNonUserDefinedConversions) {
8247 return S.CheckNonDependentConversions(
8248 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8249 Sema::CheckNonDependentConversionsFlag(
8250 SuppressUserConversions,
8251 OnlyInitializeNonUserDefinedConversions),
8252 ActingContext, ObjectType, ObjectClassification, PO);
8253 });
8255 OverloadCandidate &Candidate =
8256 CandidateSet.addCandidate(Conversions.size(), Conversions);
8257 Candidate.FoundDecl = FoundDecl;
8258 Candidate.Function = Method;
8259 Candidate.Viable = false;
8260 Candidate.RewriteKind =
8261 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8262 Candidate.IsSurrogate = false;
8263 Candidate.TookAddressOfOverload =
8264 CandidateSet.getKind() ==
8266
8267 Candidate.IgnoreObjectArgument =
8268 Method->isStatic() ||
8269 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8270 Candidate.ExplicitCallArguments = Args.size();
8273 else {
8275 Candidate.DeductionFailure =
8277 }
8278 return;
8279 }
8280
8281 // Add the function template specialization produced by template argument
8282 // deduction as a candidate.
8283 assert(Specialization && "Missing member function template specialization?");
8285 "Specialization is not a member function?");
8287 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8288 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8289 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8290}
8291
8293 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8294 CXXRecordDecl *ActingContext,
8295 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8296 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8297 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8298 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8299 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8300 return;
8301
8302 if (ExplicitTemplateArgs ||
8303 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8305 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8306 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8307 SuppressUserConversions, PartialOverloading, PO);
8308 return;
8309 }
8310
8312 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8313 Args, SuppressUserConversions, PartialOverloading, PO);
8314}
8315
8316/// Determine whether a given function template has a simple explicit specifier
8317/// or a non-value-dependent explicit-specification that evaluates to true.
8321
8326
8328 Sema &S, OverloadCandidateSet &CandidateSet,
8330 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8331 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8333 bool AggregateCandidateDeduction) {
8334
8335 // If the function template has a non-dependent explicit specification,
8336 // exclude it now if appropriate; we are not permitted to perform deduction
8337 // and substitution in this case.
8338 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8339 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8340 Candidate.FoundDecl = FoundDecl;
8341 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8342 Candidate.Viable = false;
8343 Candidate.FailureKind = ovl_fail_explicit;
8344 return;
8345 }
8346
8347 // C++ [over.match.funcs]p7:
8348 // In each case where a candidate is a function template, candidate
8349 // function template specializations are generated using template argument
8350 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8351 // candidate functions in the usual way.113) A given name can refer to one
8352 // or more function templates and also to a set of overloaded non-template
8353 // functions. In such a case, the candidate functions generated from each
8354 // function template are combined with the set of non-template candidate
8355 // functions.
8356 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8357 FunctionTemplate->getTemplateDepth());
8358 FunctionDecl *Specialization = nullptr;
8359 ConversionSequenceList Conversions;
8361 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8362 PartialOverloading, AggregateCandidateDeduction,
8363 /*PartialOrdering=*/false,
8364 /*ObjectType=*/QualType(),
8365 /*ObjectClassification=*/Expr::Classification(),
8366 CandidateSet.getKind() ==
8368 [&](ArrayRef<QualType> ParamTypes,
8369 bool OnlyInitializeNonUserDefinedConversions) {
8370 return S.CheckNonDependentConversions(
8371 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8372 Sema::CheckNonDependentConversionsFlag(
8373 SuppressUserConversions,
8374 OnlyInitializeNonUserDefinedConversions),
8375 nullptr, QualType(), {}, PO);
8376 });
8378 OverloadCandidate &Candidate =
8379 CandidateSet.addCandidate(Conversions.size(), Conversions);
8380 Candidate.FoundDecl = FoundDecl;
8381 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8382 Candidate.Viable = false;
8383 Candidate.RewriteKind =
8384 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8385 Candidate.IsSurrogate = false;
8386 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8387 // Ignore the object argument if there is one, since we don't have an object
8388 // type.
8389 Candidate.TookAddressOfOverload =
8390 CandidateSet.getKind() ==
8392
8393 Candidate.IgnoreObjectArgument =
8394 isa<CXXMethodDecl>(Candidate.Function) &&
8395 !cast<CXXMethodDecl>(Candidate.Function)
8396 ->isExplicitObjectMemberFunction() &&
8398
8399 Candidate.ExplicitCallArguments = Args.size();
8402 else {
8404 Candidate.DeductionFailure =
8406 }
8407 return;
8408 }
8409
8410 // Add the function template specialization produced by template argument
8411 // deduction as a candidate.
8412 assert(Specialization && "Missing function template specialization?");
8414 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8415 PartialOverloading, AllowExplicit,
8416 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8417 Info.AggregateDeductionCandidateHasMismatchedArity,
8418 Info.hasStrictPackMatch());
8419}
8420
8423 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8424 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8425 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8426 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8427 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8428 return;
8429
8430 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8431
8432 if (ExplicitTemplateArgs ||
8433 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8434 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8435 DependentExplicitSpecifier)) {
8436
8438 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8439 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8440 IsADLCandidate, PO, AggregateCandidateDeduction);
8441
8442 if (DependentExplicitSpecifier)
8444 return;
8445 }
8446
8447 CandidateSet.AddDeferredTemplateCandidate(
8448 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8449 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8450 AggregateCandidateDeduction);
8451}
8452
8455 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8457 CheckNonDependentConversionsFlag UserConversionFlag,
8458 CXXRecordDecl *ActingContext, QualType ObjectType,
8459 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8460 // FIXME: The cases in which we allow explicit conversions for constructor
8461 // arguments never consider calling a constructor template. It's not clear
8462 // that is correct.
8463 const bool AllowExplicit = false;
8464
8465 bool ForOverloadSetAddressResolution =
8467 auto *FD = FunctionTemplate->getTemplatedDecl();
8468 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8469 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8471 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8472
8473 if (Conversions.empty())
8474 Conversions =
8475 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8476
8477 // Overload resolution is always an unevaluated context.
8480
8481 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8482 // require that, but this check should never result in a hard error, and
8483 // overload resolution is permitted to sidestep instantiations.
8484 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8485 !ObjectType.isNull()) {
8486 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8487 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8488 !ParamTypes[0]->isDependentType()) {
8490 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8491 Method, ActingContext, /*InOverloadResolution=*/true,
8492 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8493 : QualType());
8494 if (Conversions[ConvIdx].isBad())
8495 return true;
8496 }
8497 }
8498
8499 // A speculative workaround for self-dependent constraint bugs that manifest
8500 // after CWG2369.
8501 // FIXME: Add references to the standard once P3606 is adopted.
8502 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8503 QualType ArgType) {
8504 ParamType = ParamType.getNonReferenceType();
8505 ArgType = ArgType.getNonReferenceType();
8506 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8507 if (PointerConv) {
8508 ParamType = ParamType->getPointeeType();
8509 ArgType = ArgType->getPointeeType();
8510 }
8511
8512 if (auto *RD = ParamType->getAsCXXRecordDecl();
8513 RD && RD->hasDefinition() &&
8514 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8515 auto Info = getConstructorInfo(ND);
8516 if (!Info)
8517 return false;
8518 CXXConstructorDecl *Ctor = Info.Constructor;
8519 /// isConvertingConstructor takes copy/move constructors into
8520 /// account!
8521 return !Ctor->isCopyOrMoveConstructor() &&
8523 /*AllowExplicit=*/true);
8524 }))
8525 return true;
8526 if (auto *RD = ArgType->getAsCXXRecordDecl();
8527 RD && RD->hasDefinition() &&
8528 !RD->getVisibleConversionFunctions().empty())
8529 return true;
8530
8531 return false;
8532 };
8533
8534 unsigned Offset =
8535 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8536 : 0;
8537
8538 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8539 I != N; ++I) {
8540 QualType ParamType = ParamTypes[I + Offset];
8541 if (!ParamType->isDependentType()) {
8542 unsigned ConvIdx;
8544 ConvIdx = Args.size() - 1 - I;
8545 assert(Args.size() + ThisConversions == 2 &&
8546 "number of args (including 'this') must be exactly 2 for "
8547 "reversed order");
8548 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8549 // would also be 0. 'this' got ConvIdx = 1 previously.
8550 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8551 } else {
8552 // For members, 'this' got ConvIdx = 0 previously.
8553 ConvIdx = ThisConversions + I;
8554 }
8555 if (Conversions[ConvIdx].isInitialized())
8556 continue;
8557 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8558 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8559 continue;
8561 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8562 /*InOverloadResolution=*/true,
8563 /*AllowObjCWritebackConversion=*/
8564 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8565 if (Conversions[ConvIdx].isBad())
8566 return true;
8567 }
8568 }
8569
8570 return false;
8571}
8572
8573/// Determine whether this is an allowable conversion from the result
8574/// of an explicit conversion operator to the expected type, per C++
8575/// [over.match.conv]p1 and [over.match.ref]p1.
8576///
8577/// \param ConvType The return type of the conversion function.
8578///
8579/// \param ToType The type we are converting to.
8580///
8581/// \param AllowObjCPointerConversion Allow a conversion from one
8582/// Objective-C pointer to another.
8583///
8584/// \returns true if the conversion is allowable, false otherwise.
8586 QualType ConvType, QualType ToType,
8587 bool AllowObjCPointerConversion) {
8588 QualType ToNonRefType = ToType.getNonReferenceType();
8589
8590 // Easy case: the types are the same.
8591 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8592 return true;
8593
8594 // Allow qualification conversions.
8595 bool ObjCLifetimeConversion;
8596 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8597 ObjCLifetimeConversion))
8598 return true;
8599
8600 // If we're not allowed to consider Objective-C pointer conversions,
8601 // we're done.
8602 if (!AllowObjCPointerConversion)
8603 return false;
8604
8605 // Is this an Objective-C pointer conversion?
8606 bool IncompatibleObjC = false;
8607 QualType ConvertedType;
8608 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8609 IncompatibleObjC);
8610}
8611
8613 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8614 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8615 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8616 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8617 assert(!Conversion->getDescribedFunctionTemplate() &&
8618 "Conversion function templates use AddTemplateConversionCandidate");
8619 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8620 if (!CandidateSet.isNewCandidate(Conversion))
8621 return;
8622
8623 // If the conversion function has an undeduced return type, trigger its
8624 // deduction now.
8625 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8626 if (DeduceReturnType(Conversion, From->getExprLoc()))
8627 return;
8628 ConvType = Conversion->getConversionType().getNonReferenceType();
8629 }
8630
8631 // If we don't allow any conversion of the result type, ignore conversion
8632 // functions that don't convert to exactly (possibly cv-qualified) T.
8633 if (!AllowResultConversion &&
8634 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8635 return;
8636
8637 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8638 // operator is only a candidate if its return type is the target type or
8639 // can be converted to the target type with a qualification conversion.
8640 //
8641 // FIXME: Include such functions in the candidate list and explain why we
8642 // can't select them.
8643 if (Conversion->isExplicit() &&
8644 !isAllowableExplicitConversion(*this, ConvType, ToType,
8645 AllowObjCConversionOnExplicit))
8646 return;
8647
8648 // Overload resolution is always an unevaluated context.
8651
8652 // Add this candidate
8653 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8654 Candidate.FoundDecl = FoundDecl;
8655 Candidate.Function = Conversion;
8657 Candidate.FinalConversion.setFromType(ConvType);
8658 Candidate.FinalConversion.setAllToTypes(ToType);
8659 Candidate.HasFinalConversion = true;
8660 Candidate.Viable = true;
8661 Candidate.ExplicitCallArguments = 1;
8662 Candidate.StrictPackMatch = StrictPackMatch;
8663
8664 // Explicit functions are not actually candidates at all if we're not
8665 // allowing them in this context, but keep them around so we can point
8666 // to them in diagnostics.
8667 if (!AllowExplicit && Conversion->isExplicit()) {
8668 Candidate.Viable = false;
8669 Candidate.FailureKind = ovl_fail_explicit;
8670 return;
8671 }
8672
8673 // C++ [over.match.funcs]p4:
8674 // For conversion functions, the function is considered to be a member of
8675 // the class of the implicit implied object argument for the purpose of
8676 // defining the type of the implicit object parameter.
8677 //
8678 // Determine the implicit conversion sequence for the implicit
8679 // object parameter.
8680 QualType ObjectType = From->getType();
8681 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8682 ObjectType = FromPtrType->getPointeeType();
8683 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8684 // C++23 [over.best.ics.general]
8685 // However, if the target is [...]
8686 // - the object parameter of a user-defined conversion function
8687 // [...] user-defined conversion sequences are not considered.
8689 *this, CandidateSet.getLocation(), From->getType(),
8690 From->Classify(Context), Conversion, ConversionContext,
8691 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8692 /*SuppressUserConversion*/ true);
8693
8694 if (Candidate.Conversions[0].isBad()) {
8695 Candidate.Viable = false;
8697 return;
8698 }
8699
8700 if (Conversion->getTrailingRequiresClause()) {
8701 ConstraintSatisfaction Satisfaction;
8702 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8703 !Satisfaction.IsSatisfied) {
8704 Candidate.Viable = false;
8706 return;
8707 }
8708 }
8709
8710 // We won't go through a user-defined type conversion function to convert a
8711 // derived to base as such conversions are given Conversion Rank. They only
8712 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8713 QualType FromCanon
8714 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8715 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8716 if (FromCanon == ToCanon ||
8717 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8718 Candidate.Viable = false;
8720 return;
8721 }
8722
8723 // To determine what the conversion from the result of calling the
8724 // conversion function to the type we're eventually trying to
8725 // convert to (ToType), we need to synthesize a call to the
8726 // conversion function and attempt copy initialization from it. This
8727 // makes sure that we get the right semantics with respect to
8728 // lvalues/rvalues and the type. Fortunately, we can allocate this
8729 // call on the stack and we don't need its arguments to be
8730 // well-formed.
8731 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8732 VK_LValue, From->getBeginLoc());
8734 Context.getPointerType(Conversion->getType()),
8735 CK_FunctionToPointerDecay, &ConversionRef,
8737
8738 QualType ConversionType = Conversion->getConversionType();
8739 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8740 Candidate.Viable = false;
8742 return;
8743 }
8744
8745 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8746
8747 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8748
8749 // Introduce a temporary expression with the right type and value category
8750 // that we can use for deduction purposes.
8751 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8752
8754 TryCopyInitialization(*this, &FakeCall, ToType,
8755 /*SuppressUserConversions=*/true,
8756 /*InOverloadResolution=*/false,
8757 /*AllowObjCWritebackConversion=*/false);
8758
8759 switch (ICS.getKind()) {
8761 Candidate.FinalConversion = ICS.Standard;
8762 Candidate.HasFinalConversion = true;
8763
8764 // C++ [over.ics.user]p3:
8765 // If the user-defined conversion is specified by a specialization of a
8766 // conversion function template, the second standard conversion sequence
8767 // shall have exact match rank.
8768 if (Conversion->getPrimaryTemplate() &&
8770 Candidate.Viable = false;
8772 return;
8773 }
8774
8775 // C++0x [dcl.init.ref]p5:
8776 // In the second case, if the reference is an rvalue reference and
8777 // the second standard conversion sequence of the user-defined
8778 // conversion sequence includes an lvalue-to-rvalue conversion, the
8779 // program is ill-formed.
8780 if (ToType->isRValueReferenceType() &&
8782 Candidate.Viable = false;
8784 return;
8785 }
8786 break;
8787
8789 Candidate.Viable = false;
8791 return;
8792
8793 default:
8794 llvm_unreachable(
8795 "Can only end up with a standard conversion sequence or failure");
8796 }
8797
8798 if (EnableIfAttr *FailedAttr =
8799 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8800 Candidate.Viable = false;
8801 Candidate.FailureKind = ovl_fail_enable_if;
8802 Candidate.DeductionFailure.Data = FailedAttr;
8803 return;
8804 }
8805
8806 if (isNonViableMultiVersionOverload(Conversion)) {
8807 Candidate.Viable = false;
8809 }
8810}
8811
8813 Sema &S, OverloadCandidateSet &CandidateSet,
8815 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8816 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8817 bool AllowResultConversion) {
8818
8819 // If the function template has a non-dependent explicit specification,
8820 // exclude it now if appropriate; we are not permitted to perform deduction
8821 // and substitution in this case.
8822 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8823 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8824 Candidate.FoundDecl = FoundDecl;
8825 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8826 Candidate.Viable = false;
8827 Candidate.FailureKind = ovl_fail_explicit;
8828 return;
8829 }
8830
8831 QualType ObjectType = From->getType();
8832 Expr::Classification ObjectClassification = From->Classify(S.Context);
8833
8834 TemplateDeductionInfo Info(CandidateSet.getLocation());
8837 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8838 Specialization, Info);
8840 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8841 Candidate.FoundDecl = FoundDecl;
8842 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8843 Candidate.Viable = false;
8845 Candidate.ExplicitCallArguments = 1;
8846 Candidate.DeductionFailure =
8848 return;
8849 }
8850
8851 // Add the conversion function template specialization produced by
8852 // template argument deduction as a candidate.
8853 assert(Specialization && "Missing function template specialization?");
8854 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8855 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8856 AllowExplicit, AllowResultConversion,
8857 Info.hasStrictPackMatch());
8858}
8859
8862 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8863 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8864 bool AllowExplicit, bool AllowResultConversion) {
8865 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8866 "Only conversion function templates permitted here");
8867
8868 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8869 return;
8870
8871 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8872 CandidateSet.getKind() ==
8876 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8877 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8878 AllowResultConversion);
8879
8881 return;
8882 }
8883
8885 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8886 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8887}
8888
8890 DeclAccessPair FoundDecl,
8891 CXXRecordDecl *ActingContext,
8892 const FunctionProtoType *Proto,
8893 Expr *Object,
8894 ArrayRef<Expr *> Args,
8895 OverloadCandidateSet& CandidateSet) {
8896 if (!CandidateSet.isNewCandidate(Conversion))
8897 return;
8898
8899 // Overload resolution is always an unevaluated context.
8902
8903 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8904 Candidate.FoundDecl = FoundDecl;
8905 Candidate.Function = nullptr;
8906 Candidate.Surrogate = Conversion;
8907 Candidate.IsSurrogate = true;
8908 Candidate.Viable = true;
8909 Candidate.ExplicitCallArguments = Args.size();
8910
8911 // Determine the implicit conversion sequence for the implicit
8912 // object parameter.
8913 ImplicitConversionSequence ObjectInit;
8914 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8915 ObjectInit = TryCopyInitialization(*this, Object,
8916 Conversion->getParamDecl(0)->getType(),
8917 /*SuppressUserConversions=*/false,
8918 /*InOverloadResolution=*/true, false);
8919 } else {
8921 *this, CandidateSet.getLocation(), Object->getType(),
8922 Object->Classify(Context), Conversion, ActingContext);
8923 }
8924
8925 if (ObjectInit.isBad()) {
8926 Candidate.Viable = false;
8928 Candidate.Conversions[0] = ObjectInit;
8929 return;
8930 }
8931
8932 // The first conversion is actually a user-defined conversion whose
8933 // first conversion is ObjectInit's standard conversion (which is
8934 // effectively a reference binding). Record it as such.
8935 Candidate.Conversions[0].setUserDefined();
8936 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8937 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8938 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8939 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8940 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8941 Candidate.Conversions[0].UserDefined.After
8942 = Candidate.Conversions[0].UserDefined.Before;
8943 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8944
8945 // Find the
8946 unsigned NumParams = Proto->getNumParams();
8947
8948 // (C++ 13.3.2p2): A candidate function having fewer than m
8949 // parameters is viable only if it has an ellipsis in its parameter
8950 // list (8.3.5).
8951 if (Args.size() > NumParams && !Proto->isVariadic()) {
8952 Candidate.Viable = false;
8954 return;
8955 }
8956
8957 // Function types don't have any default arguments, so just check if
8958 // we have enough arguments.
8959 if (Args.size() < NumParams) {
8960 // Not enough arguments.
8961 Candidate.Viable = false;
8963 return;
8964 }
8965
8966 // Determine the implicit conversion sequences for each of the
8967 // arguments.
8968 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8969 if (ArgIdx < NumParams) {
8970 // (C++ 13.3.2p3): for F to be a viable function, there shall
8971 // exist for each argument an implicit conversion sequence
8972 // (13.3.3.1) that converts that argument to the corresponding
8973 // parameter of F.
8974 QualType ParamType = Proto->getParamType(ArgIdx);
8975 Candidate.Conversions[ArgIdx + 1]
8976 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8977 /*SuppressUserConversions=*/false,
8978 /*InOverloadResolution=*/false,
8979 /*AllowObjCWritebackConversion=*/
8980 getLangOpts().ObjCAutoRefCount);
8981 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8982 Candidate.Viable = false;
8984 return;
8985 }
8986 } else {
8987 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8988 // argument for which there is no corresponding parameter is
8989 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8990 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8991 }
8992 }
8993
8994 if (Conversion->getTrailingRequiresClause()) {
8995 ConstraintSatisfaction Satisfaction;
8996 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8997 /*ForOverloadResolution*/ true) ||
8998 !Satisfaction.IsSatisfied) {
8999 Candidate.Viable = false;
9001 return;
9002 }
9003 }
9004
9005 if (EnableIfAttr *FailedAttr =
9006 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
9007 Candidate.Viable = false;
9008 Candidate.FailureKind = ovl_fail_enable_if;
9009 Candidate.DeductionFailure.Data = FailedAttr;
9010 return;
9011 }
9012}
9013
9015 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
9016 OverloadCandidateSet &CandidateSet,
9017 TemplateArgumentListInfo *ExplicitTemplateArgs) {
9018 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
9019 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
9020 ArrayRef<Expr *> FunctionArgs = Args;
9021
9022 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
9023 FunctionDecl *FD =
9024 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
9025
9026 // Don't consider rewritten functions if we're not rewriting.
9027 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
9028 continue;
9029
9030 assert(!isa<CXXMethodDecl>(FD) &&
9031 "unqualified operator lookup found a member function");
9032
9033 if (FunTmpl) {
9034 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
9035 FunctionArgs, CandidateSet);
9036 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9037
9038 // As template candidates are not deduced immediately,
9039 // persist the array in the overload set.
9041 FunctionArgs[1], FunctionArgs[0]);
9042 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
9043 Reversed, CandidateSet, false, false, true,
9044 ADLCallKind::NotADL,
9046 }
9047 } else {
9048 if (ExplicitTemplateArgs)
9049 continue;
9050 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
9051 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
9052 AddOverloadCandidate(FD, F.getPair(),
9053 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9054 false, false, true, false, ADLCallKind::NotADL, {},
9056 }
9057 }
9058}
9059
9061 SourceLocation OpLoc,
9062 ArrayRef<Expr *> Args,
9063 OverloadCandidateSet &CandidateSet,
9065 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9066
9067 // C++ [over.match.oper]p3:
9068 // For a unary operator @ with an operand of a type whose
9069 // cv-unqualified version is T1, and for a binary operator @ with
9070 // a left operand of a type whose cv-unqualified version is T1 and
9071 // a right operand of a type whose cv-unqualified version is T2,
9072 // three sets of candidate functions, designated member
9073 // candidates, non-member candidates and built-in candidates, are
9074 // constructed as follows:
9075 QualType T1 = Args[0]->getType();
9076
9077 // -- If T1 is a complete class type or a class currently being
9078 // defined, the set of member candidates is the result of the
9079 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9080 // the set of member candidates is empty.
9081 if (T1->isRecordType()) {
9082 bool IsComplete = isCompleteType(OpLoc, T1);
9083 auto *T1RD = T1->getAsCXXRecordDecl();
9084 // Complete the type if it can be completed.
9085 // If the type is neither complete nor being defined, bail out now.
9086 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9087 return;
9088
9089 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9090 LookupQualifiedName(Operators, T1RD);
9091 Operators.suppressAccessDiagnostics();
9092
9093 for (LookupResult::iterator Oper = Operators.begin(),
9094 OperEnd = Operators.end();
9095 Oper != OperEnd; ++Oper) {
9096 if (Oper->getAsFunction() &&
9098 !CandidateSet.getRewriteInfo().shouldAddReversed(
9099 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9100 continue;
9101 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9102 Args[0]->Classify(Context), Args.slice(1),
9103 CandidateSet, /*SuppressUserConversion=*/false, PO);
9104 }
9105 }
9106}
9107
9109 OverloadCandidateSet& CandidateSet,
9110 bool IsAssignmentOperator,
9111 unsigned NumContextualBoolArguments) {
9112 // Overload resolution is always an unevaluated context.
9115
9116 // Add this candidate
9117 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9118 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9119 Candidate.Function = nullptr;
9120 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9121
9122 // Determine the implicit conversion sequences for each of the
9123 // arguments.
9124 Candidate.Viable = true;
9125 Candidate.ExplicitCallArguments = Args.size();
9126 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9127 // C++ [over.match.oper]p4:
9128 // For the built-in assignment operators, conversions of the
9129 // left operand are restricted as follows:
9130 // -- no temporaries are introduced to hold the left operand, and
9131 // -- no user-defined conversions are applied to the left
9132 // operand to achieve a type match with the left-most
9133 // parameter of a built-in candidate.
9134 //
9135 // We block these conversions by turning off user-defined
9136 // conversions, since that is the only way that initialization of
9137 // a reference to a non-class type can occur from something that
9138 // is not of the same type.
9139 if (ArgIdx < NumContextualBoolArguments) {
9140 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9141 "Contextual conversion to bool requires bool type");
9142 Candidate.Conversions[ArgIdx]
9143 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9144 } else {
9145 Candidate.Conversions[ArgIdx]
9146 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9147 ArgIdx == 0 && IsAssignmentOperator,
9148 /*InOverloadResolution=*/false,
9149 /*AllowObjCWritebackConversion=*/
9150 getLangOpts().ObjCAutoRefCount);
9151 }
9152 if (Candidate.Conversions[ArgIdx].isBad()) {
9153 Candidate.Viable = false;
9155 break;
9156 }
9157 }
9158}
9159
9160namespace {
9161
9162/// BuiltinCandidateTypeSet - A set of types that will be used for the
9163/// candidate operator functions for built-in operators (C++
9164/// [over.built]). The types are separated into pointer types and
9165/// enumeration types.
9166class BuiltinCandidateTypeSet {
9167 /// TypeSet - A set of types.
9168 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9169
9170 /// PointerTypes - The set of pointer types that will be used in the
9171 /// built-in candidates.
9172 TypeSet PointerTypes;
9173
9174 /// MemberPointerTypes - The set of member pointer types that will be
9175 /// used in the built-in candidates.
9176 TypeSet MemberPointerTypes;
9177
9178 /// EnumerationTypes - The set of enumeration types that will be
9179 /// used in the built-in candidates.
9180 TypeSet EnumerationTypes;
9181
9182 /// The set of vector types that will be used in the built-in
9183 /// candidates.
9184 TypeSet VectorTypes;
9185
9186 /// The set of matrix types that will be used in the built-in
9187 /// candidates.
9188 TypeSet MatrixTypes;
9189
9190 /// The set of _BitInt types that will be used in the built-in candidates.
9191 TypeSet BitIntTypes;
9192
9193 /// A flag indicating non-record types are viable candidates
9194 bool HasNonRecordTypes;
9195
9196 /// A flag indicating whether either arithmetic or enumeration types
9197 /// were present in the candidate set.
9198 bool HasArithmeticOrEnumeralTypes;
9199
9200 /// A flag indicating whether the candidate set has a type that might
9201 /// convert to a promoted arithmetic type or to a vector type. This is
9202 /// conservative: only scoped enumerations, pointers, member pointers,
9203 /// nullptr_t, and classes that convert to nothing else are known not to.
9204 bool MayConvertToArithmetic;
9205
9206 /// A flag indicating whether the nullptr type was present in the
9207 /// candidate set.
9208 bool HasNullPtrType;
9209
9210 /// A flag indicating whether the reflection type was present in the
9211 /// candidate set.
9212 bool HasReflectionType;
9213
9214 /// Sema - The semantic analysis instance where we are building the
9215 /// candidate type set.
9216 Sema &SemaRef;
9217
9218 /// Context - The AST context in which we will build the type sets.
9219 ASTContext &Context;
9220
9221 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9222 const Qualifiers &VisibleQuals);
9223 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9224
9225public:
9226 /// iterator - Iterates through the types that are part of the set.
9227 typedef TypeSet::iterator iterator;
9228
9229 BuiltinCandidateTypeSet(Sema &SemaRef)
9230 : HasNonRecordTypes(false), HasArithmeticOrEnumeralTypes(false),
9231 MayConvertToArithmetic(false), HasNullPtrType(false),
9232 HasReflectionType(false), SemaRef(SemaRef), Context(SemaRef.Context) {}
9233
9234 void AddTypesConvertedFrom(QualType Ty,
9235 SourceLocation Loc,
9236 bool AllowUserConversions,
9237 bool AllowExplicitConversions,
9238 const Qualifiers &VisibleTypeConversionsQuals);
9239
9240 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9241 llvm::iterator_range<iterator> member_pointer_types() {
9242 return MemberPointerTypes;
9243 }
9244 llvm::iterator_range<iterator> enumeration_types() {
9245 return EnumerationTypes;
9246 }
9247 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9248 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9249 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9250
9251 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9252 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9253 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9254 bool mayConvertToArithmetic() const { return MayConvertToArithmetic; }
9255 bool hasNullPtrType() const { return HasNullPtrType; }
9256 bool hasReflectionType() const { return HasReflectionType; }
9257};
9258
9259} // end anonymous namespace
9260
9261/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9262/// the set of pointer types along with any more-qualified variants of
9263/// that type. For example, if @p Ty is "int const *", this routine
9264/// will add "int const *", "int const volatile *", "int const
9265/// restrict *", and "int const volatile restrict *" to the set of
9266/// pointer types. Returns true if the add of @p Ty itself succeeded,
9267/// false otherwise.
9268///
9269/// FIXME: what to do about extended qualifiers?
9270bool
9271BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9272 const Qualifiers &VisibleQuals) {
9273
9274 // Insert this type.
9275 if (!PointerTypes.insert(Ty))
9276 return false;
9277
9278 QualType PointeeTy;
9279 const PointerType *PointerTy = Ty->getAs<PointerType>();
9280 bool buildObjCPtr = false;
9281 if (!PointerTy) {
9282 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9283 PointeeTy = PTy->getPointeeType();
9284 buildObjCPtr = true;
9285 } else {
9286 PointeeTy = PointerTy->getPointeeType();
9287 }
9288
9289 // Don't add qualified variants of arrays. For one, they're not allowed
9290 // (the qualifier would sink to the element type), and for another, the
9291 // only overload situation where it matters is subscript or pointer +- int,
9292 // and those shouldn't have qualifier variants anyway.
9293 if (PointeeTy->isArrayType())
9294 return true;
9295
9296 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9297 bool hasVolatile = VisibleQuals.hasVolatile();
9298 bool hasRestrict = VisibleQuals.hasRestrict();
9299
9300 // Iterate through all strict supersets of BaseCVR.
9301 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9302 if ((CVR | BaseCVR) != CVR) continue;
9303 // Skip over volatile if no volatile found anywhere in the types.
9304 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9305
9306 // Skip over restrict if no restrict found anywhere in the types, or if
9307 // the type cannot be restrict-qualified.
9308 if ((CVR & Qualifiers::Restrict) &&
9309 (!hasRestrict ||
9310 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9311 continue;
9312
9313 // Build qualified pointee type.
9314 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9315
9316 // Build qualified pointer type.
9317 QualType QPointerTy;
9318 if (!buildObjCPtr)
9319 QPointerTy = Context.getPointerType(QPointeeTy);
9320 else
9321 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9322
9323 // Insert qualified pointer type.
9324 PointerTypes.insert(QPointerTy);
9325 }
9326
9327 return true;
9328}
9329
9330/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9331/// to the set of pointer types along with any more-qualified variants of
9332/// that type. For example, if @p Ty is "int const *", this routine
9333/// will add "int const *", "int const volatile *", "int const
9334/// restrict *", and "int const volatile restrict *" to the set of
9335/// pointer types. Returns true if the add of @p Ty itself succeeded,
9336/// false otherwise.
9337///
9338/// FIXME: what to do about extended qualifiers?
9339bool
9340BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9341 QualType Ty) {
9342 // Insert this type.
9343 if (!MemberPointerTypes.insert(Ty))
9344 return false;
9345
9346 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9347 assert(PointerTy && "type was not a member pointer type!");
9348
9349 QualType PointeeTy = PointerTy->getPointeeType();
9350 // Don't add qualified variants of arrays. For one, they're not allowed
9351 // (the qualifier would sink to the element type), and for another, the
9352 // only overload situation where it matters is subscript or pointer +- int,
9353 // and those shouldn't have qualifier variants anyway.
9354 if (PointeeTy->isArrayType())
9355 return true;
9356 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9357
9358 // Iterate through all strict supersets of the pointee type's CVR
9359 // qualifiers.
9360 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9361 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9362 if ((CVR | BaseCVR) != CVR) continue;
9363
9364 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9365 MemberPointerTypes.insert(Context.getMemberPointerType(
9366 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9367 }
9368
9369 return true;
9370}
9371
9372/// AddTypesConvertedFrom - Add each of the types to which the type @p
9373/// Ty can be implicit converted to the given set of @p Types. We're
9374/// primarily interested in pointer types and enumeration types. We also
9375/// take member pointer types, for the conditional operator.
9376/// AllowUserConversions is true if we should look at the conversion
9377/// functions of a class type, and AllowExplicitConversions if we
9378/// should also include the explicit conversion functions of a class
9379/// type.
9380void
9381BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9382 SourceLocation Loc,
9383 bool AllowUserConversions,
9384 bool AllowExplicitConversions,
9385 const Qualifiers &VisibleQuals) {
9386 // Only deal with canonical types.
9387 Ty = Context.getCanonicalType(Ty);
9388
9389 // Look through reference types; they aren't part of the type of an
9390 // expression for the purposes of conversions.
9391 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9392 Ty = RefTy->getPointeeType();
9393
9394 // If we're dealing with an array type, decay to the pointer.
9395 if (Ty->isArrayType())
9396 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9397
9398 // Otherwise, we don't care about qualifiers on the type.
9399 Ty = Ty.getLocalUnqualifiedType();
9400
9401 // Flag if we ever add a non-record type.
9402 bool TyIsRec = Ty->isRecordType();
9403 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9404
9405 // Flag if we encounter an arithmetic type.
9406 HasArithmeticOrEnumeralTypes =
9407 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9408
9409 // Flag if the type might convert to a promoted arithmetic or vector type.
9410 // For records, this is set below when visiting their conversion functions.
9411 MayConvertToArithmetic =
9412 MayConvertToArithmetic ||
9413 !(TyIsRec || Ty->isScopedEnumeralType() || Ty->isAnyPointerType() ||
9414 Ty->isMemberPointerType() || Ty->isNullPtrType());
9415
9416 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9417 PointerTypes.insert(Ty);
9418 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9419 // Insert our type, and its more-qualified variants, into the set
9420 // of types.
9421 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9422 return;
9423 } else if (Ty->isMemberPointerType()) {
9424 // Member pointers are far easier, since the pointee can't be converted.
9425 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9426 return;
9427 } else if (Ty->isEnumeralType()) {
9428 HasArithmeticOrEnumeralTypes = true;
9429 EnumerationTypes.insert(Ty);
9430 } else if (Ty->isBitIntType()) {
9431 HasArithmeticOrEnumeralTypes = true;
9432 BitIntTypes.insert(Ty);
9433 } else if (Ty->isVectorType()) {
9434 // We treat vector types as arithmetic types in many contexts as an
9435 // extension.
9436 HasArithmeticOrEnumeralTypes = true;
9437 VectorTypes.insert(Ty);
9438 } else if (Ty->isMatrixType()) {
9439 // Similar to vector types, we treat vector types as arithmetic types in
9440 // many contexts as an extension.
9441 HasArithmeticOrEnumeralTypes = true;
9442 MatrixTypes.insert(Ty);
9443 } else if (Ty->isNullPtrType()) {
9444 HasNullPtrType = true;
9445 } else if (Ty->isMetaInfoType()) {
9446 HasReflectionType = true;
9447 } else if (AllowUserConversions && TyIsRec) {
9448 // No conversion functions in incomplete types.
9449 if (!SemaRef.isCompleteType(Loc, Ty))
9450 return;
9451
9452 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9453 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9454 if (isa<UsingShadowDecl>(D))
9455 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9456
9457 // Skip conversion function templates; they don't tell us anything
9458 // about which builtin types we can convert to.
9460 MayConvertToArithmetic = true;
9461 continue;
9462 }
9463
9464 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9465 if (AllowExplicitConversions || !Conv->isExplicit()) {
9466 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9467 VisibleQuals);
9468 }
9469 }
9470 }
9471}
9472/// Helper function for adjusting address spaces for the pointer or reference
9473/// operands of builtin operators depending on the argument.
9478
9479/// Helper function for AddBuiltinOperatorCandidates() that adds
9480/// the volatile- and non-volatile-qualified assignment operators for the
9481/// given type to the candidate set.
9483 QualType T,
9484 ArrayRef<Expr *> Args,
9485 OverloadCandidateSet &CandidateSet) {
9486 QualType ParamTypes[2];
9487
9488 // T& operator=(T&, T)
9489 ParamTypes[0] = S.Context.getLValueReferenceType(
9491 ParamTypes[1] = T;
9492 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9493 /*IsAssignmentOperator=*/true);
9494
9496 // volatile T& operator=(volatile T&, T)
9497 ParamTypes[0] = S.Context.getLValueReferenceType(
9499 Args[0]));
9500 ParamTypes[1] = T;
9501 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9502 /*IsAssignmentOperator=*/true);
9503 }
9504}
9505
9506/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9507/// if any, found in visible type conversion functions found in ArgExpr's type.
9508static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9509 Qualifiers VRQuals;
9510 CXXRecordDecl *ClassDecl;
9511 if (const MemberPointerType *RHSMPType =
9512 ArgExpr->getType()->getAs<MemberPointerType>())
9513 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9514 else
9515 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9516 if (!ClassDecl) {
9517 // Just to be safe, assume the worst case.
9518 VRQuals.addVolatile();
9519 VRQuals.addRestrict();
9520 return VRQuals;
9521 }
9522 if (!ClassDecl->hasDefinition())
9523 return VRQuals;
9524
9525 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9526 if (isa<UsingShadowDecl>(D))
9527 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9528 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9529 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9530 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9531 CanTy = ResTypeRef->getPointeeType();
9532 // Need to go down the pointer/mempointer chain and add qualifiers
9533 // as see them.
9534 bool done = false;
9535 while (!done) {
9536 if (CanTy.isRestrictQualified())
9537 VRQuals.addRestrict();
9538 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9539 CanTy = ResTypePtr->getPointeeType();
9540 else if (const MemberPointerType *ResTypeMPtr =
9541 CanTy->getAs<MemberPointerType>())
9542 CanTy = ResTypeMPtr->getPointeeType();
9543 else
9544 done = true;
9545 if (CanTy.isVolatileQualified())
9546 VRQuals.addVolatile();
9547 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9548 return VRQuals;
9549 }
9550 }
9551 }
9552 return VRQuals;
9553}
9554
9555// Note: We're currently only handling qualifiers that are meaningful for the
9556// LHS of compound assignment overloading.
9558 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9559 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9560 // _Atomic
9561 if (Available.hasAtomic()) {
9562 Available.removeAtomic();
9563 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9564 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9565 return;
9566 }
9567
9568 // volatile
9569 if (Available.hasVolatile()) {
9570 Available.removeVolatile();
9571 assert(!Applied.hasVolatile());
9572 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9573 Callback);
9574 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9575 return;
9576 }
9577
9578 Callback(Applied);
9579}
9580
9582 QualifiersAndAtomic Quals,
9583 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9585 Callback);
9586}
9587
9589 QualifiersAndAtomic Quals,
9590 Sema &S) {
9591 if (Quals.hasAtomic())
9593 if (Quals.hasVolatile())
9596}
9597
9598namespace {
9599
9600/// Helper class to manage the addition of builtin operator overload
9601/// candidates. It provides shared state and utility methods used throughout
9602/// the process, as well as a helper method to add each group of builtin
9603/// operator overloads from the standard to a candidate set.
9604class BuiltinOperatorOverloadBuilder {
9605 // Common instance state available to all overload candidate addition methods.
9606 Sema &S;
9607 ArrayRef<Expr *> Args;
9608 QualifiersAndAtomic VisibleTypeConversionsQuals;
9609 // Whether a candidate whose parameters are all arithmetic, vector or matrix
9610 // types can be viable. It is viable if there is an arithmetic or enumeral
9611 // candidate type, and every argument might convert to such a type.
9612 bool ArithmeticCandidatesMayBeViable;
9613 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9614 OverloadCandidateSet &CandidateSet;
9615
9616 static constexpr int ArithmeticTypesCap = 26;
9617 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9618
9619 // Define some indices used to iterate over the arithmetic types in
9620 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9621 // types are that preserved by promotion (C++ [over.built]p2).
9622 unsigned FirstIntegralType,
9623 LastIntegralType;
9624 unsigned FirstPromotedIntegralType,
9625 LastPromotedIntegralType;
9626 unsigned FirstPromotedArithmeticType,
9627 LastPromotedArithmeticType;
9628 unsigned NumArithmeticTypes;
9629
9630 void InitArithmeticTypes() {
9631 // Start of promoted types.
9632 FirstPromotedArithmeticType = 0;
9633 ArithmeticTypes.push_back(S.Context.FloatTy);
9634 ArithmeticTypes.push_back(S.Context.DoubleTy);
9635 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9637 ArithmeticTypes.push_back(S.Context.Float128Ty);
9639 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9640
9641 // Start of integral types.
9642 FirstIntegralType = ArithmeticTypes.size();
9643 FirstPromotedIntegralType = ArithmeticTypes.size();
9644 ArithmeticTypes.push_back(S.Context.IntTy);
9645 ArithmeticTypes.push_back(S.Context.LongTy);
9646 ArithmeticTypes.push_back(S.Context.LongLongTy);
9650 ArithmeticTypes.push_back(S.Context.Int128Ty);
9651 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9652 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9653 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9657 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9658
9659 /// We add candidates for the unique, unqualified _BitInt types present in
9660 /// the candidate type set. The candidate set already handled ensuring the
9661 /// type is unqualified and canonical, but because we're adding from N
9662 /// different sets, we need to do some extra work to unique things. Insert
9663 /// the candidates into a unique set, then move from that set into the list
9664 /// of arithmetic types.
9665 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9666 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9667 for (QualType BitTy : Candidate.bitint_types())
9668 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9669 }
9670 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9671 LastPromotedIntegralType = ArithmeticTypes.size();
9672 LastPromotedArithmeticType = ArithmeticTypes.size();
9673 // End of promoted types.
9674
9675 ArithmeticTypes.push_back(S.Context.BoolTy);
9676 ArithmeticTypes.push_back(S.Context.CharTy);
9677 ArithmeticTypes.push_back(S.Context.WCharTy);
9678 if (S.Context.getLangOpts().Char8)
9679 ArithmeticTypes.push_back(S.Context.Char8Ty);
9680 ArithmeticTypes.push_back(S.Context.Char16Ty);
9681 ArithmeticTypes.push_back(S.Context.Char32Ty);
9682 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9683 ArithmeticTypes.push_back(S.Context.ShortTy);
9684 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9685 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9686 LastIntegralType = ArithmeticTypes.size();
9687 NumArithmeticTypes = ArithmeticTypes.size();
9688 // End of integral types.
9689 // FIXME: What about complex? What about half?
9690
9691 // We don't know for sure how many bit-precise candidates were involved, so
9692 // we subtract those from the total when testing whether we're under the
9693 // cap or not.
9694 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9695 ArithmeticTypesCap &&
9696 "Enough inline storage for all arithmetic types.");
9697 }
9698
9699 /// Helper method to factor out the common pattern of adding overloads
9700 /// for '++' and '--' builtin operators.
9701 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9702 bool HasVolatile,
9703 bool HasRestrict) {
9704 QualType ParamTypes[2] = {
9705 S.Context.getLValueReferenceType(CandidateTy),
9706 S.Context.IntTy
9707 };
9708
9709 // Non-volatile version.
9710 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9711
9712 // Use a heuristic to reduce number of builtin candidates in the set:
9713 // add volatile version only if there are conversions to a volatile type.
9714 if (HasVolatile) {
9715 ParamTypes[0] =
9717 S.Context.getVolatileType(CandidateTy));
9718 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9719 }
9720
9721 // Add restrict version only if there are conversions to a restrict type
9722 // and our candidate type is a non-restrict-qualified pointer.
9723 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9724 !CandidateTy.isRestrictQualified()) {
9725 ParamTypes[0]
9728 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9729
9730 if (HasVolatile) {
9731 ParamTypes[0]
9733 S.Context.getCVRQualifiedType(CandidateTy,
9736 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9737 }
9738 }
9739
9740 }
9741
9742 /// Helper to add an overload candidate for a binary builtin with types \p L
9743 /// and \p R.
9744 void AddCandidate(QualType L, QualType R) {
9745 QualType LandR[2] = {L, R};
9746 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9747 }
9748
9749public:
9750 BuiltinOperatorOverloadBuilder(
9751 Sema &S, ArrayRef<Expr *> Args,
9752 QualifiersAndAtomic VisibleTypeConversionsQuals,
9753 bool HasArithmeticOrEnumeralCandidateType,
9754 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9755 OverloadCandidateSet &CandidateSet)
9756 : S(S), Args(Args),
9757 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9758 ArithmeticCandidatesMayBeViable(
9759 HasArithmeticOrEnumeralCandidateType &&
9760 llvm::all_of(CandidateTypes,
9761 [](const BuiltinCandidateTypeSet &Types) {
9762 return Types.mayConvertToArithmetic();
9763 })),
9764 CandidateTypes(CandidateTypes), CandidateSet(CandidateSet) {
9765 InitArithmeticTypes();
9766 }
9767
9768 // Increment is deprecated for bool since C++17.
9769 //
9770 // C++ [over.built]p3:
9771 //
9772 // For every pair (T, VQ), where T is an arithmetic type other
9773 // than bool, and VQ is either volatile or empty, there exist
9774 // candidate operator functions of the form
9775 //
9776 // VQ T& operator++(VQ T&);
9777 // T operator++(VQ T&, int);
9778 //
9779 // C++ [over.built]p4:
9780 //
9781 // For every pair (T, VQ), where T is an arithmetic type other
9782 // than bool, and VQ is either volatile or empty, there exist
9783 // candidate operator functions of the form
9784 //
9785 // VQ T& operator--(VQ T&);
9786 // T operator--(VQ T&, int);
9787 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9788 if (!ArithmeticCandidatesMayBeViable)
9789 return;
9790
9791 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9792 const auto TypeOfT = ArithmeticTypes[Arith];
9793 if (TypeOfT == S.Context.BoolTy) {
9794 if (Op == OO_MinusMinus)
9795 continue;
9796 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9797 continue;
9798 }
9799 addPlusPlusMinusMinusStyleOverloads(
9800 TypeOfT,
9801 VisibleTypeConversionsQuals.hasVolatile(),
9802 VisibleTypeConversionsQuals.hasRestrict());
9803 }
9804 }
9805
9806 // C++ [over.built]p5:
9807 //
9808 // For every pair (T, VQ), where T is a cv-qualified or
9809 // cv-unqualified object type, and VQ is either volatile or
9810 // empty, there exist candidate operator functions of the form
9811 //
9812 // T*VQ& operator++(T*VQ&);
9813 // T*VQ& operator--(T*VQ&);
9814 // T* operator++(T*VQ&, int);
9815 // T* operator--(T*VQ&, int);
9816 void addPlusPlusMinusMinusPointerOverloads() {
9817 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9818 // Skip pointer types that aren't pointers to object types.
9819 if (!PtrTy->getPointeeType()->isObjectType())
9820 continue;
9821
9822 addPlusPlusMinusMinusStyleOverloads(
9823 PtrTy,
9824 (!PtrTy.isVolatileQualified() &&
9825 VisibleTypeConversionsQuals.hasVolatile()),
9826 (!PtrTy.isRestrictQualified() &&
9827 VisibleTypeConversionsQuals.hasRestrict()));
9828 }
9829 }
9830
9831 // C++ [over.built]p6:
9832 // For every cv-qualified or cv-unqualified object type T, there
9833 // exist candidate operator functions of the form
9834 //
9835 // T& operator*(T*);
9836 //
9837 // C++ [over.built]p7:
9838 // For every function type T that does not have cv-qualifiers or a
9839 // ref-qualifier, there exist candidate operator functions of the form
9840 // T& operator*(T*);
9841 void addUnaryStarPointerOverloads() {
9842 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9843 QualType PointeeTy = ParamTy->getPointeeType();
9844 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9845 continue;
9846
9847 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9848 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9849 continue;
9850
9851 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9852 }
9853 }
9854
9855 // C++ [over.built]p9:
9856 // For every promoted arithmetic type T, there exist candidate
9857 // operator functions of the form
9858 //
9859 // T operator+(T);
9860 // T operator-(T);
9861 void addUnaryPlusOrMinusArithmeticOverloads() {
9862 if (!ArithmeticCandidatesMayBeViable)
9863 return;
9864
9865 for (unsigned Arith = FirstPromotedArithmeticType;
9866 Arith < LastPromotedArithmeticType; ++Arith) {
9867 QualType ArithTy = ArithmeticTypes[Arith];
9868 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9869 }
9870
9871 // Extension: We also add these operators for vector types.
9872 for (QualType VecTy : CandidateTypes[0].vector_types())
9873 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9874 }
9875
9876 // C++ [over.built]p8:
9877 // For every type T, there exist candidate operator functions of
9878 // the form
9879 //
9880 // T* operator+(T*);
9881 void addUnaryPlusPointerOverloads() {
9882 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9883 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9884 }
9885
9886 // C++ [over.built]p10:
9887 // For every promoted integral type T, there exist candidate
9888 // operator functions of the form
9889 //
9890 // T operator~(T);
9891 void addUnaryTildePromotedIntegralOverloads() {
9892 if (!ArithmeticCandidatesMayBeViable)
9893 return;
9894
9895 for (unsigned Int = FirstPromotedIntegralType;
9896 Int < LastPromotedIntegralType; ++Int) {
9897 QualType IntTy = ArithmeticTypes[Int];
9898 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9899 }
9900
9901 // Extension: We also add this operator for vector types.
9902 for (QualType VecTy : CandidateTypes[0].vector_types())
9903 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9904 }
9905
9906 // C++ [over.match.oper]p16:
9907 // For every pointer to member type T or type std::nullptr_t, there
9908 // exist candidate operator functions of the form
9909 //
9910 // bool operator==(T,T);
9911 // bool operator!=(T,T);
9912 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9913 /// Set of (canonical) types that we've already handled.
9914 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9915
9916 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9917 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9918 // Don't add the same builtin candidate twice.
9919 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9920 continue;
9921
9922 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9923 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9924 }
9925
9926 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9928 if (AddedTypes.insert(NullPtrTy).second) {
9929 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9930 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9931 }
9932 }
9933
9934 if (CandidateTypes[ArgIdx].hasReflectionType()) {
9935 CanQualType MetaInfoTy = S.Context.MetaInfoTy;
9936 if (AddedTypes.insert(MetaInfoTy).second) {
9937 QualType ParamTypes[2] = {MetaInfoTy, MetaInfoTy};
9938 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9939 }
9940 }
9941 }
9942 }
9943
9944 // C++ [over.built]p15:
9945 //
9946 // For every T, where T is an enumeration type or a pointer type,
9947 // there exist candidate operator functions of the form
9948 //
9949 // bool operator<(T, T);
9950 // bool operator>(T, T);
9951 // bool operator<=(T, T);
9952 // bool operator>=(T, T);
9953 // bool operator==(T, T);
9954 // bool operator!=(T, T);
9955 // R operator<=>(T, T)
9956 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9957 // C++ [over.match.oper]p3:
9958 // [...]the built-in candidates include all of the candidate operator
9959 // functions defined in 13.6 that, compared to the given operator, [...]
9960 // do not have the same parameter-type-list as any non-template non-member
9961 // candidate.
9962 //
9963 // Note that in practice, this only affects enumeration types because there
9964 // aren't any built-in candidates of record type, and a user-defined operator
9965 // must have an operand of record or enumeration type. Also, the only other
9966 // overloaded operator with enumeration arguments, operator=,
9967 // cannot be overloaded for enumeration types, so this is the only place
9968 // where we must suppress candidates like this.
9969 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9970 UserDefinedBinaryOperators;
9971
9972 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9973 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9974 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9975 CEnd = CandidateSet.end();
9976 C != CEnd; ++C) {
9977 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9978 continue;
9979
9980 if (C->Function->isFunctionTemplateSpecialization())
9981 continue;
9982
9983 // We interpret "same parameter-type-list" as applying to the
9984 // "synthesized candidate, with the order of the two parameters
9985 // reversed", not to the original function.
9986 bool Reversed = C->isReversed();
9987 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9988 ->getType()
9989 .getUnqualifiedType();
9990 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9991 ->getType()
9992 .getUnqualifiedType();
9993
9994 // Skip if either parameter isn't of enumeral type.
9995 if (!FirstParamType->isEnumeralType() ||
9996 !SecondParamType->isEnumeralType())
9997 continue;
9998
9999 // Add this operator to the set of known user-defined operators.
10000 UserDefinedBinaryOperators.insert(
10001 std::make_pair(S.Context.getCanonicalType(FirstParamType),
10002 S.Context.getCanonicalType(SecondParamType)));
10003 }
10004 }
10005 }
10006
10007 /// Set of (canonical) types that we've already handled.
10008 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10009
10010 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10011 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10012 // Don't add the same builtin candidate twice.
10013 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10014 continue;
10015 if (IsSpaceship && PtrTy->isFunctionPointerType())
10016 continue;
10017
10018 QualType ParamTypes[2] = {PtrTy, PtrTy};
10019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10020 }
10021 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10022 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
10023
10024 // Don't add the same builtin candidate twice, or if a user defined
10025 // candidate exists.
10026 if (!AddedTypes.insert(CanonType).second ||
10027 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
10028 CanonType)))
10029 continue;
10030 QualType ParamTypes[2] = {EnumTy, EnumTy};
10031 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10032 }
10033 }
10034 }
10035
10036 // C++ [over.built]p13:
10037 //
10038 // For every cv-qualified or cv-unqualified object type T
10039 // there exist candidate operator functions of the form
10040 //
10041 // T* operator+(T*, ptrdiff_t);
10042 // T& operator[](T*, ptrdiff_t); [BELOW]
10043 // T* operator-(T*, ptrdiff_t);
10044 // T* operator+(ptrdiff_t, T*);
10045 // T& operator[](ptrdiff_t, T*); [BELOW]
10046 //
10047 // C++ [over.built]p14:
10048 //
10049 // For every T, where T is a pointer to object type, there
10050 // exist candidate operator functions of the form
10051 //
10052 // ptrdiff_t operator-(T, T);
10053 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
10054 /// Set of (canonical) types that we've already handled.
10055 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10056
10057 for (int Arg = 0; Arg < 2; ++Arg) {
10058 QualType AsymmetricParamTypes[2] = {
10061 };
10062 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
10063 QualType PointeeTy = PtrTy->getPointeeType();
10064 if (!PointeeTy->isObjectType())
10065 continue;
10066
10067 AsymmetricParamTypes[Arg] = PtrTy;
10068 if (Arg == 0 || Op == OO_Plus) {
10069 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
10070 // T* operator+(ptrdiff_t, T*);
10071 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
10072 }
10073 if (Op == OO_Minus) {
10074 // ptrdiff_t operator-(T, T);
10075 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10076 continue;
10077
10078 QualType ParamTypes[2] = {PtrTy, PtrTy};
10079 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10080 }
10081 }
10082 }
10083 }
10084
10085 // C++ [over.built]p12:
10086 //
10087 // For every pair of promoted arithmetic types L and R, there
10088 // exist candidate operator functions of the form
10089 //
10090 // LR operator*(L, R);
10091 // LR operator/(L, R);
10092 // LR operator+(L, R);
10093 // LR operator-(L, R);
10094 // bool operator<(L, R);
10095 // bool operator>(L, R);
10096 // bool operator<=(L, R);
10097 // bool operator>=(L, R);
10098 // bool operator==(L, R);
10099 // bool operator!=(L, R);
10100 //
10101 // where LR is the result of the usual arithmetic conversions
10102 // between types L and R.
10103 //
10104 // C++ [over.built]p24:
10105 //
10106 // For every pair of promoted arithmetic types L and R, there exist
10107 // candidate operator functions of the form
10108 //
10109 // LR operator?(bool, L, R);
10110 //
10111 // where LR is the result of the usual arithmetic conversions
10112 // between types L and R.
10113 // Our candidates ignore the first parameter.
10114 void addGenericBinaryArithmeticOverloads() {
10115 if (!ArithmeticCandidatesMayBeViable)
10116 return;
10117
10118 for (unsigned Left = FirstPromotedArithmeticType;
10119 Left < LastPromotedArithmeticType; ++Left) {
10120 for (unsigned Right = FirstPromotedArithmeticType;
10121 Right < LastPromotedArithmeticType; ++Right) {
10122 QualType LandR[2] = { ArithmeticTypes[Left],
10123 ArithmeticTypes[Right] };
10124 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10125 }
10126 }
10127
10128 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10129 // conditional operator for vector types.
10130 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10131 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10132 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10133 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10134 }
10135 }
10136
10137 /// Add binary operator overloads for each candidate matrix type M1, M2:
10138 /// * (M1, M1) -> M1
10139 /// * (M1, M1.getElementType()) -> M1
10140 /// * (M2.getElementType(), M2) -> M2
10141 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10142 void addMatrixBinaryArithmeticOverloads() {
10143 if (!ArithmeticCandidatesMayBeViable)
10144 return;
10145
10146 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10147 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10148 AddCandidate(M1, M1);
10149 }
10150
10151 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10152 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10153 if (!CandidateTypes[0].containsMatrixType(M2))
10154 AddCandidate(M2, M2);
10155 }
10156 }
10157
10158 // C++2a [over.built]p14:
10159 //
10160 // For every integral type T there exists a candidate operator function
10161 // of the form
10162 //
10163 // std::strong_ordering operator<=>(T, T)
10164 //
10165 // C++2a [over.built]p15:
10166 //
10167 // For every pair of floating-point types L and R, there exists a candidate
10168 // operator function of the form
10169 //
10170 // std::partial_ordering operator<=>(L, R);
10171 //
10172 // FIXME: The current specification for integral types doesn't play nice with
10173 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10174 // comparisons. Under the current spec this can lead to ambiguity during
10175 // overload resolution. For example:
10176 //
10177 // enum A : int {a};
10178 // auto x = (a <=> (long)42);
10179 //
10180 // error: call is ambiguous for arguments 'A' and 'long'.
10181 // note: candidate operator<=>(int, int)
10182 // note: candidate operator<=>(long, long)
10183 //
10184 // To avoid this error, this function deviates from the specification and adds
10185 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10186 // arithmetic types (the same as the generic relational overloads).
10187 //
10188 // For now this function acts as a placeholder.
10189 void addThreeWayArithmeticOverloads() {
10190 addGenericBinaryArithmeticOverloads();
10191 }
10192
10193 // C++ [over.built]p17:
10194 //
10195 // For every pair of promoted integral types L and R, there
10196 // exist candidate operator functions of the form
10197 //
10198 // LR operator%(L, R);
10199 // LR operator&(L, R);
10200 // LR operator^(L, R);
10201 // LR operator|(L, R);
10202 // L operator<<(L, R);
10203 // L operator>>(L, R);
10204 //
10205 // where LR is the result of the usual arithmetic conversions
10206 // between types L and R.
10207 void addBinaryBitwiseArithmeticOverloads() {
10208 if (!ArithmeticCandidatesMayBeViable)
10209 return;
10210
10211 for (unsigned Left = FirstPromotedIntegralType;
10212 Left < LastPromotedIntegralType; ++Left) {
10213 for (unsigned Right = FirstPromotedIntegralType;
10214 Right < LastPromotedIntegralType; ++Right) {
10215 QualType LandR[2] = { ArithmeticTypes[Left],
10216 ArithmeticTypes[Right] };
10217 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10218 }
10219 }
10220 }
10221
10222 // C++ [over.built]p20:
10223 //
10224 // For every pair (T, VQ), where T is an enumeration or
10225 // pointer to member type and VQ is either volatile or
10226 // empty, there exist candidate operator functions of the form
10227 //
10228 // VQ T& operator=(VQ T&, T);
10229 void addAssignmentMemberPointerOrEnumeralOverloads() {
10230 /// Set of (canonical) types that we've already handled.
10231 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10232
10233 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10234 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10235 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10236 continue;
10237
10238 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10239 }
10240
10241 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10242 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10243 continue;
10244
10245 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10246 }
10247 }
10248 }
10249
10250 // C++ [over.built]p19:
10251 //
10252 // For every pair (T, VQ), where T is any type and VQ is either
10253 // volatile or empty, there exist candidate operator functions
10254 // of the form
10255 //
10256 // T*VQ& operator=(T*VQ&, T*);
10257 //
10258 // C++ [over.built]p21:
10259 //
10260 // For every pair (T, VQ), where T is a cv-qualified or
10261 // cv-unqualified object type and VQ is either volatile or
10262 // empty, there exist candidate operator functions of the form
10263 //
10264 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10265 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10266 void addAssignmentPointerOverloads(bool isEqualOp) {
10267 /// Set of (canonical) types that we've already handled.
10268 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10269
10270 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10271 // If this is operator=, keep track of the builtin candidates we added.
10272 if (isEqualOp)
10273 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10274 else if (!PtrTy->getPointeeType()->isObjectType())
10275 continue;
10276
10277 // non-volatile version
10278 QualType ParamTypes[2] = {
10280 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10281 };
10282 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10283 /*IsAssignmentOperator=*/ isEqualOp);
10284
10285 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10286 VisibleTypeConversionsQuals.hasVolatile();
10287 if (NeedVolatile) {
10288 // volatile version
10289 ParamTypes[0] =
10291 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10292 /*IsAssignmentOperator=*/isEqualOp);
10293 }
10294
10295 if (!PtrTy.isRestrictQualified() &&
10296 VisibleTypeConversionsQuals.hasRestrict()) {
10297 // restrict version
10298 ParamTypes[0] =
10300 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10301 /*IsAssignmentOperator=*/isEqualOp);
10302
10303 if (NeedVolatile) {
10304 // volatile restrict version
10305 ParamTypes[0] =
10308 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10309 /*IsAssignmentOperator=*/isEqualOp);
10310 }
10311 }
10312 }
10313
10314 if (isEqualOp) {
10315 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10316 // Make sure we don't add the same candidate twice.
10317 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10318 continue;
10319
10320 QualType ParamTypes[2] = {
10322 PtrTy,
10323 };
10324
10325 // non-volatile version
10326 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10327 /*IsAssignmentOperator=*/true);
10328
10329 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10330 VisibleTypeConversionsQuals.hasVolatile();
10331 if (NeedVolatile) {
10332 // volatile version
10333 ParamTypes[0] = S.Context.getLValueReferenceType(
10334 S.Context.getVolatileType(PtrTy));
10335 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10336 /*IsAssignmentOperator=*/true);
10337 }
10338
10339 if (!PtrTy.isRestrictQualified() &&
10340 VisibleTypeConversionsQuals.hasRestrict()) {
10341 // restrict version
10342 ParamTypes[0] = S.Context.getLValueReferenceType(
10343 S.Context.getRestrictType(PtrTy));
10344 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10345 /*IsAssignmentOperator=*/true);
10346
10347 if (NeedVolatile) {
10348 // volatile restrict version
10349 ParamTypes[0] =
10352 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10353 /*IsAssignmentOperator=*/true);
10354 }
10355 }
10356 }
10357 }
10358 }
10359
10360 // C++ [over.built]p18:
10361 //
10362 // For every triple (L, VQ, R), where L is an arithmetic type,
10363 // VQ is either volatile or empty, and R is a promoted
10364 // arithmetic type, there exist candidate operator functions of
10365 // the form
10366 //
10367 // VQ L& operator=(VQ L&, R);
10368 // VQ L& operator*=(VQ L&, R);
10369 // VQ L& operator/=(VQ L&, R);
10370 // VQ L& operator+=(VQ L&, R);
10371 // VQ L& operator-=(VQ L&, R);
10372 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10373 if (!ArithmeticCandidatesMayBeViable)
10374 return;
10375
10376 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10377 for (unsigned Right = FirstPromotedArithmeticType;
10378 Right < LastPromotedArithmeticType; ++Right) {
10379 QualType ParamTypes[2];
10380 ParamTypes[1] = ArithmeticTypes[Right];
10382 S, ArithmeticTypes[Left], Args[0]);
10383
10385 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10386 ParamTypes[0] =
10387 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10388 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10389 /*IsAssignmentOperator=*/isEqualOp);
10390 });
10391 }
10392 }
10393
10394 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10395 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10396 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10397 QualType ParamTypes[2];
10398 ParamTypes[1] = Vec2Ty;
10399 // Add this built-in operator as a candidate (VQ is empty).
10400 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10401 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10402 /*IsAssignmentOperator=*/isEqualOp);
10403
10404 // Add this built-in operator as a candidate (VQ is 'volatile').
10405 if (VisibleTypeConversionsQuals.hasVolatile()) {
10406 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10407 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10408 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10409 /*IsAssignmentOperator=*/isEqualOp);
10410 }
10411 }
10412 }
10413
10414 // C++ [over.built]p22:
10415 //
10416 // For every triple (L, VQ, R), where L is an integral type, VQ
10417 // is either volatile or empty, and R is a promoted integral
10418 // type, there exist candidate operator functions of the form
10419 //
10420 // VQ L& operator%=(VQ L&, R);
10421 // VQ L& operator<<=(VQ L&, R);
10422 // VQ L& operator>>=(VQ L&, R);
10423 // VQ L& operator&=(VQ L&, R);
10424 // VQ L& operator^=(VQ L&, R);
10425 // VQ L& operator|=(VQ L&, R);
10426 void addAssignmentIntegralOverloads() {
10427 if (!ArithmeticCandidatesMayBeViable)
10428 return;
10429
10430 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10431 for (unsigned Right = FirstPromotedIntegralType;
10432 Right < LastPromotedIntegralType; ++Right) {
10433 QualType ParamTypes[2];
10434 ParamTypes[1] = ArithmeticTypes[Right];
10436 S, ArithmeticTypes[Left], Args[0]);
10437
10439 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10440 ParamTypes[0] =
10441 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10442 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10443 });
10444 }
10445 }
10446 }
10447
10448 // C++ [over.operator]p23:
10449 //
10450 // There also exist candidate operator functions of the form
10451 //
10452 // bool operator!(bool);
10453 // bool operator&&(bool, bool);
10454 // bool operator||(bool, bool);
10455 void addExclaimOverload() {
10456 QualType ParamTy = S.Context.BoolTy;
10457 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10458 /*IsAssignmentOperator=*/false,
10459 /*NumContextualBoolArguments=*/1);
10460 }
10461 void addAmpAmpOrPipePipeOverload() {
10462 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10463 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10464 /*IsAssignmentOperator=*/false,
10465 /*NumContextualBoolArguments=*/2);
10466 }
10467
10468 // C++ [over.built]p13:
10469 //
10470 // For every cv-qualified or cv-unqualified object type T there
10471 // exist candidate operator functions of the form
10472 //
10473 // T* operator+(T*, ptrdiff_t); [ABOVE]
10474 // T& operator[](T*, ptrdiff_t);
10475 // T* operator-(T*, ptrdiff_t); [ABOVE]
10476 // T* operator+(ptrdiff_t, T*); [ABOVE]
10477 // T& operator[](ptrdiff_t, T*);
10478 void addSubscriptOverloads() {
10479 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10480 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10481 QualType PointeeType = PtrTy->getPointeeType();
10482 if (!PointeeType->isObjectType())
10483 continue;
10484
10485 // T& operator[](T*, ptrdiff_t)
10486 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10487 }
10488
10489 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10490 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10491 QualType PointeeType = PtrTy->getPointeeType();
10492 if (!PointeeType->isObjectType())
10493 continue;
10494
10495 // T& operator[](ptrdiff_t, T*)
10496 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10497 }
10498 }
10499
10500 // C++ [over.built]p11:
10501 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10502 // C1 is the same type as C2 or is a derived class of C2, T is an object
10503 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10504 // there exist candidate operator functions of the form
10505 //
10506 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10507 //
10508 // where CV12 is the union of CV1 and CV2.
10509 void addArrowStarOverloads() {
10510 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10511 QualType C1Ty = PtrTy;
10512 QualType C1;
10513 QualifierCollector Q1;
10514 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10515 if (!isa<RecordType>(C1))
10516 continue;
10517 // heuristic to reduce number of builtin candidates in the set.
10518 // Add volatile/restrict version only if there are conversions to a
10519 // volatile/restrict type.
10520 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10521 continue;
10522 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10523 continue;
10524 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10525 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10526 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10527 *D2 = mptr->getMostRecentCXXRecordDecl();
10528 if (!declaresSameEntity(D1, D2) &&
10529 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10530 break;
10531 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10532 // build CV12 T&
10533 QualType T = mptr->getPointeeType();
10534 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10535 T.isVolatileQualified())
10536 continue;
10537 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10538 T.isRestrictQualified())
10539 continue;
10540 T = Q1.apply(S.Context, T);
10541 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10542 }
10543 }
10544 }
10545
10546 // Note that we don't consider the first argument, since it has been
10547 // contextually converted to bool long ago. The candidates below are
10548 // therefore added as binary.
10549 //
10550 // C++ [over.built]p25:
10551 // For every type T, where T is a pointer, pointer-to-member, or scoped
10552 // enumeration type, there exist candidate operator functions of the form
10553 //
10554 // T operator?(bool, T, T);
10555 //
10556 void addConditionalOperatorOverloads() {
10557 /// Set of (canonical) types that we've already handled.
10558 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10559
10560 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10561 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10562 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10563 continue;
10564
10565 QualType ParamTypes[2] = {PtrTy, PtrTy};
10566 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10567 }
10568
10569 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10570 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10571 continue;
10572
10573 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10574 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10575 }
10576
10577 if (S.getLangOpts().CPlusPlus11) {
10578 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10579 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10580 continue;
10581
10582 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10583 continue;
10584
10585 QualType ParamTypes[2] = {EnumTy, EnumTy};
10586 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10587 }
10588 }
10589 }
10590 }
10591};
10592
10593} // end anonymous namespace
10594
10596 SourceLocation OpLoc,
10597 ArrayRef<Expr *> Args,
10598 OverloadCandidateSet &CandidateSet) {
10599 // Find all of the types that the arguments can convert to, but only
10600 // if the operator we're looking at has built-in operator candidates
10601 // that make use of these types. Also record whether we encounter non-record
10602 // candidate types or either arithmetic or enumeral candidate types.
10603 QualifiersAndAtomic VisibleTypeConversionsQuals;
10604 VisibleTypeConversionsQuals.addConst();
10605 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10606 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10607 if (Args[ArgIdx]->getType()->isAtomicType())
10608 VisibleTypeConversionsQuals.addAtomic();
10609 }
10610
10611 bool HasNonRecordCandidateType = false;
10612 bool HasArithmeticOrEnumeralCandidateType = false;
10614 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10615 CandidateTypes.emplace_back(*this);
10616 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10617 OpLoc,
10618 true,
10619 (Op == OO_Exclaim ||
10620 Op == OO_AmpAmp ||
10621 Op == OO_PipePipe),
10622 VisibleTypeConversionsQuals);
10623 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10624 CandidateTypes[ArgIdx].hasNonRecordTypes();
10625 HasArithmeticOrEnumeralCandidateType =
10626 HasArithmeticOrEnumeralCandidateType ||
10627 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10628 }
10629
10630 // Exit early when no non-record types have been added to the candidate set
10631 // for any of the arguments to the operator.
10632 //
10633 // We can't exit early for !, ||, or &&, since there we have always have
10634 // 'bool' overloads.
10635 if (!HasNonRecordCandidateType &&
10636 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10637 return;
10638
10639 // Setup an object to manage the common state for building overloads.
10640 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10641 VisibleTypeConversionsQuals,
10642 HasArithmeticOrEnumeralCandidateType,
10643 CandidateTypes, CandidateSet);
10644
10645 // Dispatch over the operation to add in only those overloads which apply.
10646 switch (Op) {
10647 case OO_None:
10649 llvm_unreachable("Expected an overloaded operator");
10650
10651 case OO_New:
10652 case OO_Delete:
10653 case OO_Array_New:
10654 case OO_Array_Delete:
10655 case OO_Call:
10656 llvm_unreachable(
10657 "Special operators don't use AddBuiltinOperatorCandidates");
10658
10659 case OO_Comma:
10660 case OO_Arrow:
10661 case OO_Coawait:
10662 // C++ [over.match.oper]p3:
10663 // -- For the operator ',', the unary operator '&', the
10664 // operator '->', or the operator 'co_await', the
10665 // built-in candidates set is empty.
10666 break;
10667
10668 case OO_Plus: // '+' is either unary or binary
10669 if (Args.size() == 1)
10670 OpBuilder.addUnaryPlusPointerOverloads();
10671 [[fallthrough]];
10672
10673 case OO_Minus: // '-' is either unary or binary
10674 if (Args.size() == 1) {
10675 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10676 } else {
10677 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10678 OpBuilder.addGenericBinaryArithmeticOverloads();
10679 OpBuilder.addMatrixBinaryArithmeticOverloads();
10680 }
10681 break;
10682
10683 case OO_Star: // '*' is either unary or binary
10684 if (Args.size() == 1)
10685 OpBuilder.addUnaryStarPointerOverloads();
10686 else {
10687 OpBuilder.addGenericBinaryArithmeticOverloads();
10688 OpBuilder.addMatrixBinaryArithmeticOverloads();
10689 }
10690 break;
10691
10692 case OO_Slash:
10693 OpBuilder.addGenericBinaryArithmeticOverloads();
10694 break;
10695
10696 case OO_PlusPlus:
10697 case OO_MinusMinus:
10698 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10699 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10700 break;
10701
10702 case OO_EqualEqual:
10703 case OO_ExclaimEqual:
10704 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10705 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10706 OpBuilder.addGenericBinaryArithmeticOverloads();
10707 break;
10708
10709 case OO_Less:
10710 case OO_Greater:
10711 case OO_LessEqual:
10712 case OO_GreaterEqual:
10713 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10714 OpBuilder.addGenericBinaryArithmeticOverloads();
10715 break;
10716
10717 case OO_Spaceship:
10718 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10719 OpBuilder.addThreeWayArithmeticOverloads();
10720 break;
10721
10722 case OO_Percent:
10723 case OO_Caret:
10724 case OO_Pipe:
10725 case OO_LessLess:
10726 case OO_GreaterGreater:
10727 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10728 break;
10729
10730 case OO_Amp: // '&' is either unary or binary
10731 if (Args.size() == 1)
10732 // C++ [over.match.oper]p3:
10733 // -- For the operator ',', the unary operator '&', or the
10734 // operator '->', the built-in candidates set is empty.
10735 break;
10736
10737 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10738 break;
10739
10740 case OO_Tilde:
10741 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10742 break;
10743
10744 case OO_Equal:
10745 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10746 [[fallthrough]];
10747
10748 case OO_PlusEqual:
10749 case OO_MinusEqual:
10750 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10751 [[fallthrough]];
10752
10753 case OO_StarEqual:
10754 case OO_SlashEqual:
10755 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10756 break;
10757
10758 case OO_PercentEqual:
10759 case OO_LessLessEqual:
10760 case OO_GreaterGreaterEqual:
10761 case OO_AmpEqual:
10762 case OO_CaretEqual:
10763 case OO_PipeEqual:
10764 OpBuilder.addAssignmentIntegralOverloads();
10765 break;
10766
10767 case OO_Exclaim:
10768 OpBuilder.addExclaimOverload();
10769 break;
10770
10771 case OO_AmpAmp:
10772 case OO_PipePipe:
10773 OpBuilder.addAmpAmpOrPipePipeOverload();
10774 break;
10775
10776 case OO_Subscript:
10777 if (Args.size() == 2)
10778 OpBuilder.addSubscriptOverloads();
10779 break;
10780
10781 case OO_ArrowStar:
10782 OpBuilder.addArrowStarOverloads();
10783 break;
10784
10785 case OO_Conditional:
10786 OpBuilder.addConditionalOperatorOverloads();
10787 OpBuilder.addGenericBinaryArithmeticOverloads();
10788 break;
10789 }
10790}
10791
10792void
10794 SourceLocation Loc,
10795 ArrayRef<Expr *> Args,
10796 TemplateArgumentListInfo *ExplicitTemplateArgs,
10797 OverloadCandidateSet& CandidateSet,
10798 bool PartialOverloading) {
10799 ADLResult Fns;
10800
10801 // FIXME: This approach for uniquing ADL results (and removing
10802 // redundant candidates from the set) relies on pointer-equality,
10803 // which means we need to key off the canonical decl. However,
10804 // always going back to the canonical decl might not get us the
10805 // right set of default arguments. What default arguments are
10806 // we supposed to consider on ADL candidates, anyway?
10807
10808 // FIXME: Pass in the explicit template arguments?
10809 ArgumentDependentLookup(Name, Loc, Args, Fns);
10810
10811 ArrayRef<Expr *> ReversedArgs;
10812
10813 // Erase all of the candidates we already knew about.
10814 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10815 CandEnd = CandidateSet.end();
10816 Cand != CandEnd; ++Cand)
10817 if (Cand->Function) {
10818 FunctionDecl *Fn = Cand->Function;
10819 Fns.erase(Fn);
10820 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10821 Fns.erase(FunTmpl);
10822 }
10823
10824 // For each of the ADL candidates we found, add it to the overload
10825 // set.
10826 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10828
10829 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10830 if (ExplicitTemplateArgs)
10831 continue;
10832
10834 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10835 PartialOverloading, /*AllowExplicit=*/true,
10836 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10837 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10839 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10840 /*SuppressUserConversions=*/false, PartialOverloading,
10841 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10842 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10843 }
10844 } else {
10845 auto *FTD = cast<FunctionTemplateDecl>(*I);
10847 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10848 /*SuppressUserConversions=*/false, PartialOverloading,
10849 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10850 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10851 *this, Args, FTD->getTemplatedDecl())) {
10852
10853 // As template candidates are not deduced immediately,
10854 // persist the array in the overload set.
10855 if (ReversedArgs.empty())
10856 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10857
10859 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10860 /*SuppressUserConversions=*/false, PartialOverloading,
10861 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10863 }
10864 }
10865 }
10866}
10867
10868namespace {
10869enum class Comparison { Equal, Better, Worse };
10870}
10871
10872/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10873/// overload resolution.
10874///
10875/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10876/// Cand1's first N enable_if attributes have precisely the same conditions as
10877/// Cand2's first N enable_if attributes (where N = the number of enable_if
10878/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10879///
10880/// Note that you can have a pair of candidates such that Cand1's enable_if
10881/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10882/// worse than Cand1's.
10883static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10884 const FunctionDecl *Cand2) {
10885 // Common case: One (or both) decls don't have enable_if attrs.
10886 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10887 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10888 if (!Cand1Attr || !Cand2Attr) {
10889 if (Cand1Attr == Cand2Attr)
10890 return Comparison::Equal;
10891 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10892 }
10893
10894 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10895 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10896
10897 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10898 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10899 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10900 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10901
10902 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10903 // has fewer enable_if attributes than Cand2, and vice versa.
10904 if (!Cand1A)
10905 return Comparison::Worse;
10906 if (!Cand2A)
10907 return Comparison::Better;
10908
10909 Cand1ID.clear();
10910 Cand2ID.clear();
10911
10912 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10913 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10914 if (Cand1ID != Cand2ID)
10915 return Comparison::Worse;
10916 }
10917
10918 return Comparison::Equal;
10919}
10920
10921static Comparison
10923 const OverloadCandidate &Cand2) {
10924 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10925 !Cand2.Function->isMultiVersion())
10926 return Comparison::Equal;
10927
10928 // If both are invalid, they are equal. If one of them is invalid, the other
10929 // is better.
10930 if (Cand1.Function->isInvalidDecl()) {
10931 if (Cand2.Function->isInvalidDecl())
10932 return Comparison::Equal;
10933 return Comparison::Worse;
10934 }
10935 if (Cand2.Function->isInvalidDecl())
10936 return Comparison::Better;
10937
10938 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10939 // cpu_dispatch, else arbitrarily based on the identifiers.
10940 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10941 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10942 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10943 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10944
10945 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10946 return Comparison::Equal;
10947
10948 if (Cand1CPUDisp && !Cand2CPUDisp)
10949 return Comparison::Better;
10950 if (Cand2CPUDisp && !Cand1CPUDisp)
10951 return Comparison::Worse;
10952
10953 if (Cand1CPUSpec && Cand2CPUSpec) {
10954 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10955 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10956 ? Comparison::Better
10957 : Comparison::Worse;
10958
10959 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10960 FirstDiff = std::mismatch(
10961 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10962 Cand2CPUSpec->cpus_begin(),
10963 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10964 return LHS->getName() == RHS->getName();
10965 });
10966
10967 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10968 "Two different cpu-specific versions should not have the same "
10969 "identifier list, otherwise they'd be the same decl!");
10970 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10971 ? Comparison::Better
10972 : Comparison::Worse;
10973 }
10974 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10975}
10976
10977/// Compute the type of the implicit object parameter for the given function,
10978/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10979/// null QualType if there is a 'matches anything' implicit object parameter.
10980static std::optional<QualType>
10983 return std::nullopt;
10984
10985 auto *M = cast<CXXMethodDecl>(F);
10986 // Static member functions' object parameters match all types.
10987 if (M->isStatic())
10988 return QualType();
10989 return M->getFunctionObjectParameterReferenceType();
10990}
10991
10992// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10993// represent the same entity.
10994static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10995 const FunctionDecl *F2) {
10996 if (declaresSameEntity(F1, F2))
10997 return true;
10998 auto PT1 = F1->getPrimaryTemplate();
10999 auto PT2 = F2->getPrimaryTemplate();
11000 if (PT1 && PT2) {
11001 if (declaresSameEntity(PT1, PT2) ||
11002 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
11003 PT2->getInstantiatedFromMemberTemplate()))
11004 return true;
11005 }
11006 // TODO: It is not clear whether comparing parameters is necessary (i.e.
11007 // different functions with same params). Consider removing this (as no test
11008 // fail w/o it).
11009 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
11010 if (First) {
11011 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
11012 return *T;
11013 }
11014 assert(I < F->getNumParams());
11015 return F->getParamDecl(I++)->getType();
11016 };
11017
11018 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
11019 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
11020
11021 if (F1NumParams != F2NumParams)
11022 return false;
11023
11024 unsigned I1 = 0, I2 = 0;
11025 for (unsigned I = 0; I != F1NumParams; ++I) {
11026 QualType T1 = NextParam(F1, I1, I == 0);
11027 QualType T2 = NextParam(F2, I2, I == 0);
11028 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
11029 if (!Context.hasSameUnqualifiedType(T1, T2))
11030 return false;
11031 }
11032 return true;
11033}
11034
11035/// We're allowed to use constraints partial ordering only if the candidates
11036/// have the same parameter types:
11037/// [over.match.best.general]p2.6
11038/// F1 and F2 are non-template functions with the same
11039/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
11041 FunctionDecl *Fn2,
11042 bool IsFn1Reversed,
11043 bool IsFn2Reversed) {
11044 assert(Fn1 && Fn2);
11045 if (Fn1->isVariadic() != Fn2->isVariadic())
11046 return false;
11047
11048 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
11049 IsFn1Reversed ^ IsFn2Reversed))
11050 return false;
11051
11052 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
11053 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
11054 if (Mem1 && Mem2) {
11055 // if they are member functions, both are direct members of the same class,
11056 // and
11057 if (Mem1->getParent() != Mem2->getParent())
11058 return false;
11059 // if both are non-static member functions, they have the same types for
11060 // their object parameters
11061 if (Mem1->isInstance() && Mem2->isInstance() &&
11063 Mem1->getFunctionObjectParameterReferenceType(),
11064 Mem2->getFunctionObjectParameterReferenceType()))
11065 return false;
11066 }
11067 return true;
11068}
11069
11070static FunctionDecl *
11072 bool IsFn1Reversed, bool IsFn2Reversed) {
11073 if (!Fn1 || !Fn2)
11074 return nullptr;
11075
11076 // C++ [temp.constr.order]:
11077 // A non-template function F1 is more partial-ordering-constrained than a
11078 // non-template function F2 if:
11079 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
11080 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11081
11082 if (Cand1IsSpecialization || Cand2IsSpecialization)
11083 return nullptr;
11084
11085 // - they have the same non-object-parameter-type-lists, and [...]
11086 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11087 IsFn2Reversed))
11088 return nullptr;
11089
11090 // - the declaration of F1 is more constrained than the declaration of F2.
11091 return S.getMoreConstrainedFunction(Fn1, Fn2);
11092}
11093
11094/// isBetterOverloadCandidate - Determines whether the first overload
11095/// candidate is a better candidate than the second (C++ 13.3.3p1).
11097 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11099 bool PartialOverloading) {
11100 // Define viable functions to be better candidates than non-viable
11101 // functions.
11102 if (!Cand2.Viable)
11103 return Cand1.Viable;
11104 else if (!Cand1.Viable)
11105 return false;
11106
11107 // [CUDA] A function with 'never' preference is marked not viable, therefore
11108 // is never shown up here. The worst preference shown up here is 'wrong side',
11109 // e.g. an H function called by a HD function in device compilation. This is
11110 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11111 // function which is called only by an H function. A deferred diagnostic will
11112 // be triggered if it is emitted. However a wrong-sided function is still
11113 // a viable candidate here.
11114 //
11115 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11116 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11117 // can be emitted, Cand1 is not better than Cand2. This rule should have
11118 // precedence over other rules.
11119 //
11120 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11121 // other rules should be used to determine which is better. This is because
11122 // host/device based overloading resolution is mostly for determining
11123 // viability of a function. If two functions are both viable, other factors
11124 // should take precedence in preference, e.g. the standard-defined preferences
11125 // like argument conversion ranks or enable_if partial-ordering. The
11126 // preference for pass-object-size parameters is probably most similar to a
11127 // type-based-overloading decision and so should take priority.
11128 //
11129 // If other rules cannot determine which is better, CUDA preference will be
11130 // used again to determine which is better.
11131 //
11132 // TODO: Currently IdentifyPreference does not return correct values
11133 // for functions called in global variable initializers due to missing
11134 // correct context about device/host. Therefore we can only enforce this
11135 // rule when there is a caller. We should enforce this rule for functions
11136 // in global variable initializers once proper context is added.
11137 //
11138 // TODO: We can only enable the hostness based overloading resolution when
11139 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11140 // overloading resolution diagnostics.
11141 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11142 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11143 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11144 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11145 bool IsCand1ImplicitHD =
11147 bool IsCand2ImplicitHD =
11149 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11150 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11151 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11152 // The implicit HD function may be a function in a system header which
11153 // is forced by pragma. In device compilation, if we prefer HD candidates
11154 // over wrong-sided candidates, overloading resolution may change, which
11155 // may result in non-deferrable diagnostics. As a workaround, we let
11156 // implicit HD candidates take equal preference as wrong-sided candidates.
11157 // This will preserve the overloading resolution.
11158 // TODO: We still need special handling of implicit HD functions since
11159 // they may incur other diagnostics to be deferred. We should make all
11160 // host/device related diagnostics deferrable and remove special handling
11161 // of implicit HD functions.
11162 auto EmitThreshold =
11163 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11164 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11167 auto Cand1Emittable = P1 > EmitThreshold;
11168 auto Cand2Emittable = P2 > EmitThreshold;
11169 if (Cand1Emittable && !Cand2Emittable)
11170 return true;
11171 if (!Cand1Emittable && Cand2Emittable)
11172 return false;
11173 }
11174 }
11175
11176 // C++ [over.match.best]p1: (Changed in C++23)
11177 //
11178 // -- if F is a static member function, ICS1(F) is defined such
11179 // that ICS1(F) is neither better nor worse than ICS1(G) for
11180 // any function G, and, symmetrically, ICS1(G) is neither
11181 // better nor worse than ICS1(F).
11182 unsigned StartArg = 0;
11183 if (!Cand1.TookAddressOfOverload &&
11185 StartArg = 1;
11186
11187 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11188 // We don't allow incompatible pointer conversions in C++.
11189 if (!S.getLangOpts().CPlusPlus)
11190 return ICS.isStandard() &&
11191 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11192
11193 // The only ill-formed conversion we allow in C++ is the string literal to
11194 // char* conversion, which is only considered ill-formed after C++11.
11195 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11197 };
11198
11199 // Define functions that don't require ill-formed conversions for a given
11200 // argument to be better candidates than functions that do.
11201 unsigned NumArgs = Cand1.Conversions.size();
11202 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11203 bool HasBetterConversion = false;
11204 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11205 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11206 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11207 if (Cand1Bad != Cand2Bad) {
11208 if (Cand1Bad)
11209 return false;
11210 HasBetterConversion = true;
11211 }
11212 }
11213
11214 if (HasBetterConversion)
11215 return true;
11216
11217 // C++ [over.match.best]p1:
11218 // A viable function F1 is defined to be a better function than another
11219 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11220 // conversion sequence than ICSi(F2), and then...
11221 bool HasWorseConversion = false;
11222 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11224 Cand1.Conversions[ArgIdx],
11225 Cand2.Conversions[ArgIdx])) {
11227 // Cand1 has a better conversion sequence.
11228 HasBetterConversion = true;
11229 break;
11230
11232 if (Cand1.Function && Cand2.Function &&
11233 Cand1.isReversed() != Cand2.isReversed() &&
11234 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11235 // Work around large-scale breakage caused by considering reversed
11236 // forms of operator== in C++20:
11237 //
11238 // When comparing a function against a reversed function, if we have a
11239 // better conversion for one argument and a worse conversion for the
11240 // other, the implicit conversion sequences are treated as being equally
11241 // good.
11242 //
11243 // This prevents a comparison function from being considered ambiguous
11244 // with a reversed form that is written in the same way.
11245 //
11246 // We diagnose this as an extension from CreateOverloadedBinOp.
11247 HasWorseConversion = true;
11248 break;
11249 }
11250
11251 // Cand1 can't be better than Cand2.
11252 return false;
11253
11255 // Do nothing.
11256 break;
11257 }
11258 }
11259
11260 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11261 // ICSj(F2), or, if not that,
11262 if (HasBetterConversion && !HasWorseConversion)
11263 return true;
11264
11265 // -- the context is an initialization by user-defined conversion
11266 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11267 // from the return type of F1 to the destination type (i.e.,
11268 // the type of the entity being initialized) is a better
11269 // conversion sequence than the standard conversion sequence
11270 // from the return type of F2 to the destination type.
11272 Cand1.Function && Cand2.Function &&
11275
11276 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11277 // First check whether we prefer one of the conversion functions over the
11278 // other. This only distinguishes the results in non-standard, extension
11279 // cases such as the conversion from a lambda closure type to a function
11280 // pointer or block.
11285 Cand1.FinalConversion,
11286 Cand2.FinalConversion);
11287
11290
11291 // FIXME: Compare kind of reference binding if conversion functions
11292 // convert to a reference type used in direct reference binding, per
11293 // C++14 [over.match.best]p1 section 2 bullet 3.
11294 }
11295
11296 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11297 // as combined with the resolution to CWG issue 243.
11298 //
11299 // When the context is initialization by constructor ([over.match.ctor] or
11300 // either phase of [over.match.list]), a constructor is preferred over
11301 // a conversion function.
11302 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11303 Cand1.Function && Cand2.Function &&
11306 return isa<CXXConstructorDecl>(Cand1.Function);
11307
11308 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11309 return Cand2.StrictPackMatch;
11310
11311 // -- F1 is a non-template function and F2 is a function template
11312 // specialization, or, if not that,
11313 bool Cand1IsSpecialization = Cand1.Function &&
11315 bool Cand2IsSpecialization = Cand2.Function &&
11317 if (Cand1IsSpecialization != Cand2IsSpecialization)
11318 return Cand2IsSpecialization;
11319
11320 // -- F1 and F2 are function template specializations, and the function
11321 // template for F1 is more specialized than the template for F2
11322 // according to the partial ordering rules described in 14.5.5.2, or,
11323 // if not that,
11324 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11325 const auto *Obj1Context =
11326 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11327 const auto *Obj2Context =
11328 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11329 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11331 Cand2.Function->getPrimaryTemplate(), Loc,
11333 : TPOC_Call,
11335 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11336 : QualType{},
11337 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11338 : QualType{},
11339 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11340 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11341 }
11342 }
11343
11344 // -— F1 and F2 are non-template functions and F1 is more
11345 // partial-ordering-constrained than F2 [...],
11347 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11348 Cand2.isReversed());
11349 F && F == Cand1.Function)
11350 return true;
11351
11352 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11353 // class B of D, and for all arguments the corresponding parameters of
11354 // F1 and F2 have the same type.
11355 // FIXME: Implement the "all parameters have the same type" check.
11356 bool Cand1IsInherited =
11357 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11358 bool Cand2IsInherited =
11359 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11360 if (Cand1IsInherited != Cand2IsInherited)
11361 return Cand2IsInherited;
11362 else if (Cand1IsInherited) {
11363 assert(Cand2IsInherited);
11364 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11365 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11366 if (Cand1Class->isDerivedFrom(Cand2Class))
11367 return true;
11368 if (Cand2Class->isDerivedFrom(Cand1Class))
11369 return false;
11370 // Inherited from sibling base classes: still ambiguous.
11371 }
11372
11373 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11374 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11375 // with reversed order of parameters and F1 is not
11376 //
11377 // We rank reversed + different operator as worse than just reversed, but
11378 // that comparison can never happen, because we only consider reversing for
11379 // the maximally-rewritten operator (== or <=>).
11380 if (Cand1.RewriteKind != Cand2.RewriteKind)
11381 return Cand1.RewriteKind < Cand2.RewriteKind;
11382
11383 // Check C++17 tie-breakers for deduction guides.
11384 {
11385 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11386 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11387 if (Guide1 && Guide2) {
11388 // -- F1 is generated from a deduction-guide and F2 is not
11389 if (Guide1->isImplicit() != Guide2->isImplicit())
11390 return Guide2->isImplicit();
11391
11392 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11393 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11394 return true;
11395 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11396 return false;
11397
11398 // --F1 is generated from a non-template constructor and F2 is generated
11399 // from a constructor template
11400 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11401 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11402 if (Constructor1 && Constructor2) {
11403 bool isC1Templated = Constructor1->getTemplatedKind() !=
11405 bool isC2Templated = Constructor2->getTemplatedKind() !=
11407 if (isC1Templated != isC2Templated)
11408 return isC2Templated;
11409 }
11410 }
11411 }
11412
11413 // Check for enable_if value-based overload resolution.
11414 if (Cand1.Function && Cand2.Function) {
11416 if (Cmp != Comparison::Equal)
11417 return Cmp == Comparison::Better;
11418 }
11419
11420 bool HasPS1 = Cand1.Function != nullptr &&
11422 bool HasPS2 = Cand2.Function != nullptr &&
11424 if (HasPS1 != HasPS2 && HasPS1)
11425 return true;
11426
11427 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11428 if (MV == Comparison::Better)
11429 return true;
11430 if (MV == Comparison::Worse)
11431 return false;
11432
11433 // If other rules cannot determine which is better, CUDA preference is used
11434 // to determine which is better.
11435 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11436 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11437 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11438 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11439 }
11440
11441 // General member function overloading is handled above, so this only handles
11442 // constructors with address spaces.
11443 // This only handles address spaces since C++ has no other
11444 // qualifier that can be used with constructors.
11445 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11446 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11447 if (CD1 && CD2) {
11448 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11449 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11450 if (AS1 != AS2) {
11452 return true;
11454 return false;
11455 }
11456 }
11457
11458 return false;
11459}
11460
11461/// Determine whether two declarations are "equivalent" for the purposes of
11462/// name lookup and overload resolution. This applies when the same internal/no
11463/// linkage entity is defined by two modules (probably by textually including
11464/// the same header). In such a case, we don't consider the declarations to
11465/// declare the same entity, but we also don't want lookups with both
11466/// declarations visible to be ambiguous in some cases (this happens when using
11467/// a modularized libstdc++).
11469 const NamedDecl *B) {
11470 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11471 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11472 if (!VA || !VB)
11473 return false;
11474
11475 // The declarations must be declaring the same name as an internal linkage
11476 // entity in different modules.
11477 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11478 VB->getDeclContext()->getRedeclContext()) ||
11479 getOwningModule(VA) == getOwningModule(VB) ||
11480 VA->isExternallyVisible() || VB->isExternallyVisible())
11481 return false;
11482
11483 // Check that the declarations appear to be equivalent.
11484 //
11485 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11486 // For constants and functions, we should check the initializer or body is
11487 // the same. For non-constant variables, we shouldn't allow it at all.
11488 if (Context.hasSameType(VA->getType(), VB->getType()))
11489 return true;
11490
11491 // Enum constants within unnamed enumerations will have different types, but
11492 // may still be similar enough to be interchangeable for our purposes.
11493 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11494 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11495 // Only handle anonymous enums. If the enumerations were named and
11496 // equivalent, they would have been merged to the same type.
11497 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11498 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11499 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11500 !Context.hasSameType(EnumA->getIntegerType(),
11501 EnumB->getIntegerType()))
11502 return false;
11503 // Allow this only if the value is the same for both enumerators.
11504 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11505 }
11506 }
11507
11508 // Nothing else is sufficiently similar.
11509 return false;
11510}
11511
11514 assert(D && "Unknown declaration");
11515 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11516
11517 Module *M = getOwningModule(D);
11518 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11519 << !M << (M ? M->getFullModuleName() : "");
11520
11521 for (auto *E : Equiv) {
11522 Module *M = getOwningModule(E);
11523 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11524 << !M << (M ? M->getFullModuleName() : "");
11525 }
11526}
11527
11530 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11532 static_cast<CNSInfo *>(DeductionFailure.Data)
11533 ->Satisfaction.ContainsErrors;
11534}
11535
11538 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11539 bool PartialOverloading, bool AllowExplicit,
11541 bool AggregateCandidateDeduction) {
11542
11543 auto *C =
11544 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11545
11548 /*AllowObjCConversionOnExplicit=*/false,
11549 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11550 PartialOverloading, AggregateCandidateDeduction},
11552 FoundDecl,
11553 Args,
11554 IsADLCandidate,
11555 PO};
11556
11557 HasDeferredTemplateConstructors |=
11558 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11559}
11560
11562 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11563 CXXRecordDecl *ActingContext, QualType ObjectType,
11564 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11565 bool SuppressUserConversions, bool PartialOverloading,
11567
11568 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11569
11570 auto *C =
11571 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11572
11575 /*AllowObjCConversionOnExplicit=*/false,
11576 /*AllowResultConversion=*/false,
11577 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11578 /*AggregateCandidateDeduction=*/false},
11579 MethodTmpl,
11580 FoundDecl,
11581 Args,
11582 ActingContext,
11583 ObjectClassification,
11584 ObjectType,
11585 PO};
11586}
11587
11590 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11591 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11592 bool AllowResultConversion) {
11593
11594 auto *C =
11595 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11596
11599 AllowObjCConversionOnExplicit, AllowResultConversion,
11600 /*AllowExplicit=*/false,
11601 /*SuppressUserConversions=*/false,
11602 /*PartialOverloading*/ false,
11603 /*AggregateCandidateDeduction=*/false},
11605 FoundDecl,
11606 ActingContext,
11607 From,
11608 ToType};
11609}
11610
11611static void
11614
11616 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11617 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11618 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11619}
11620
11621static void
11625 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11626 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11627 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11628 C.AggregateCandidateDeduction);
11629}
11630
11631static void
11635 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11636 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11637 C.AllowResultConversion);
11638}
11639
11641 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11642 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11643 while (Cand) {
11644 switch (Cand->Kind) {
11647 S, *this,
11648 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11649 break;
11652 S, *this,
11653 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11654 break;
11657 S, *this,
11658 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11659 break;
11660 }
11661 Cand = Cand->Next;
11662 }
11663 FirstDeferredCandidate = nullptr;
11664 DeferredCandidatesCount = 0;
11665}
11666
11668OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11669 Best->Best = true;
11670 if (Best->Function && Best->Function->isDeleted())
11671 return OR_Deleted;
11672 return OR_Success;
11673}
11674
11675void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11677 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11678 // are accepted by both clang and NVCC. However, during a particular
11679 // compilation mode only one call variant is viable. We need to
11680 // exclude non-viable overload candidates from consideration based
11681 // only on their host/device attributes. Specifically, if one
11682 // candidate call is WrongSide and the other is SameSide, we ignore
11683 // the WrongSide candidate.
11684 // We only need to remove wrong-sided candidates here if
11685 // -fgpu-exclude-wrong-side-overloads is off. When
11686 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11687 // uniformly in isBetterOverloadCandidate.
11688 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11689 return;
11690 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11691
11692 bool ContainsSameSideCandidate =
11693 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11694 // Check viable function only.
11695 return Cand->Viable && Cand->Function &&
11696 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11698 });
11699
11700 if (!ContainsSameSideCandidate)
11701 return;
11702
11703 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11704 // Check viable function only to avoid unnecessary data copying/moving.
11705 return Cand->Viable && Cand->Function &&
11706 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11708 };
11709 llvm::erase_if(Candidates, IsWrongSideCandidate);
11710}
11711
11712/// Computes the best viable function (C++ 13.3.3)
11713/// within an overload candidate set.
11714///
11715/// \param Loc The location of the function name (or operator symbol) for
11716/// which overload resolution occurs.
11717///
11718/// \param Best If overload resolution was successful or found a deleted
11719/// function, \p Best points to the candidate function found.
11720///
11721/// \returns The result of overload resolution.
11723 SourceLocation Loc,
11724 iterator &Best) {
11725
11727 DeferredCandidatesCount == 0) &&
11728 "Unexpected deferred template candidates");
11729
11730 bool TwoPhaseResolution =
11731 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11732
11733 if (TwoPhaseResolution) {
11734 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11735 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11736 if (!(HasDeferredTemplateConstructors &&
11737 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11738 return Res;
11739 }
11740 }
11741
11743 return BestViableFunctionImpl(S, Loc, Best);
11744}
11745
11746OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11748
11750 Candidates.reserve(this->Candidates.size());
11751 std::transform(this->Candidates.begin(), this->Candidates.end(),
11752 std::back_inserter(Candidates),
11753 [](OverloadCandidate &Cand) { return &Cand; });
11754
11755 if (S.getLangOpts().CUDA)
11756 CudaExcludeWrongSideCandidates(S, Candidates);
11757
11758 Best = end();
11759 for (auto *Cand : Candidates) {
11760 Cand->Best = false;
11761 if (Cand->Viable) {
11762 if (Best == end() ||
11763 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11764 Best = Cand;
11765 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11766 // This candidate has constraint that we were unable to evaluate because
11767 // it referenced an expression that contained an error. Rather than fall
11768 // back onto a potentially unintended candidate (made worse by
11769 // subsuming constraints), treat this as 'no viable candidate'.
11770 Best = end();
11771 return OR_No_Viable_Function;
11772 }
11773 }
11774
11775 // If we didn't find any viable functions, abort.
11776 if (Best == end())
11777 return OR_No_Viable_Function;
11778
11779 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11780 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11781 PendingBest.push_back(&*Best);
11782 Best->Best = true;
11783
11784 // Make sure that this function is better than every other viable
11785 // function. If not, we have an ambiguity.
11786 while (!PendingBest.empty()) {
11787 auto *Curr = PendingBest.pop_back_val();
11788 for (auto *Cand : Candidates) {
11789 if (Cand->Viable && !Cand->Best &&
11790 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11791 PendingBest.push_back(Cand);
11792 Cand->Best = true;
11793
11795 Curr->Function))
11796 EquivalentCands.push_back(Cand->Function);
11797 else
11798 Best = end();
11799 }
11800 }
11801 }
11802
11803 if (Best == end())
11804 return OR_Ambiguous;
11805
11806 OverloadingResult R = ResultForBestCandidate(Best);
11807
11808 if (!EquivalentCands.empty())
11810 EquivalentCands);
11811 return R;
11812}
11813
11814namespace {
11815
11816enum OverloadCandidateKind {
11817 oc_function,
11818 oc_method,
11819 oc_reversed_binary_operator,
11820 oc_constructor,
11821 oc_implicit_default_constructor,
11822 oc_implicit_copy_constructor,
11823 oc_implicit_move_constructor,
11824 oc_implicit_copy_assignment,
11825 oc_implicit_move_assignment,
11826 oc_implicit_equality_comparison,
11827 oc_inherited_constructor
11828};
11829
11830enum OverloadCandidateSelect {
11831 ocs_non_template,
11832 ocs_template,
11833 ocs_described_template,
11834};
11835
11836static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11837ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11838 const FunctionDecl *Fn,
11840 std::string &Description) {
11841
11842 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11843 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11844 isTemplate = true;
11845 Description = S.getTemplateArgumentBindingsText(
11846 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11847 }
11848
11849 OverloadCandidateSelect Select = [&]() {
11850 if (!Description.empty())
11851 return ocs_described_template;
11852 return isTemplate ? ocs_template : ocs_non_template;
11853 }();
11854
11855 OverloadCandidateKind Kind = [&]() {
11856 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11857 return oc_implicit_equality_comparison;
11858
11859 if (CRK & CRK_Reversed)
11860 return oc_reversed_binary_operator;
11861
11862 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11863 if (!Ctor->isImplicit()) {
11865 return oc_inherited_constructor;
11866 else
11867 return oc_constructor;
11868 }
11869
11870 if (Ctor->isDefaultConstructor())
11871 return oc_implicit_default_constructor;
11872
11873 if (Ctor->isMoveConstructor())
11874 return oc_implicit_move_constructor;
11875
11876 assert(Ctor->isCopyConstructor() &&
11877 "unexpected sort of implicit constructor");
11878 return oc_implicit_copy_constructor;
11879 }
11880
11881 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11882 // This actually gets spelled 'candidate function' for now, but
11883 // it doesn't hurt to split it out.
11884 if (!Meth->isImplicit())
11885 return oc_method;
11886
11887 if (Meth->isMoveAssignmentOperator())
11888 return oc_implicit_move_assignment;
11889
11890 if (Meth->isCopyAssignmentOperator())
11891 return oc_implicit_copy_assignment;
11892
11893 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11894 return oc_method;
11895 }
11896
11897 return oc_function;
11898 }();
11899
11900 return std::make_pair(Kind, Select);
11901}
11902
11903void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11904 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11905 // set.
11906 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11907 S.Diag(FoundDecl->getLocation(),
11908 diag::note_ovl_candidate_inherited_constructor)
11909 << Shadow->getNominatedBaseClass();
11910}
11911
11912} // end anonymous namespace
11913
11915 const FunctionDecl *FD) {
11916 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11917 bool AlwaysTrue;
11918 if (EnableIf->getCond()->isValueDependent() ||
11919 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11920 return false;
11921 if (!AlwaysTrue)
11922 return false;
11923 }
11924 return true;
11925}
11926
11927/// Returns true if we can take the address of the function.
11928///
11929/// \param Complain - If true, we'll emit a diagnostic
11930/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11931/// we in overload resolution?
11932/// \param Loc - The location of the statement we're complaining about. Ignored
11933/// if we're not complaining, or if we're in overload resolution.
11935 bool Complain,
11936 bool InOverloadResolution,
11937 SourceLocation Loc) {
11938 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11939 if (Complain) {
11940 if (InOverloadResolution)
11941 S.Diag(FD->getBeginLoc(),
11942 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11943 else
11944 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11945 }
11946 return false;
11947 }
11948
11949 if (FD->getTrailingRequiresClause()) {
11950 ConstraintSatisfaction Satisfaction;
11951 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11952 return false;
11953 if (!Satisfaction.IsSatisfied) {
11954 if (Complain) {
11955 if (InOverloadResolution) {
11956 SmallString<128> TemplateArgString;
11957 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11958 TemplateArgString += " ";
11959 TemplateArgString += S.getTemplateArgumentBindingsText(
11960 FunTmpl->getTemplateParameters(),
11962 }
11963
11964 S.Diag(FD->getBeginLoc(),
11965 diag::note_ovl_candidate_unsatisfied_constraints)
11966 << TemplateArgString;
11967 } else
11968 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11969 << FD;
11970 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11971 }
11972 return false;
11973 }
11974 }
11975
11976 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11977 return P->hasAttr<PassObjectSizeAttr>();
11978 });
11979 if (I == FD->param_end())
11980 return true;
11981
11982 if (Complain) {
11983 // Add one to ParamNo because it's user-facing
11984 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11985 if (InOverloadResolution)
11986 S.Diag(FD->getLocation(),
11987 diag::note_ovl_candidate_has_pass_object_size_params)
11988 << ParamNo;
11989 else
11990 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11991 << FD << ParamNo;
11992 }
11993 return false;
11994}
11995
11997 const FunctionDecl *FD) {
11998 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11999 /*InOverloadResolution=*/true,
12000 /*Loc=*/SourceLocation());
12001}
12002
12004 bool Complain,
12005 SourceLocation Loc) {
12006 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
12007 /*InOverloadResolution=*/false,
12008 Loc);
12009}
12010
12011// Don't print candidates other than the one that matches the calling
12012// convention of the call operator, since that is guaranteed to exist.
12014 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
12015
12016 if (!ConvD)
12017 return false;
12018 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
12019 if (!RD->isLambda())
12020 return false;
12021
12022 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
12023 CallingConv CallOpCC =
12024 CallOp->getType()->castAs<FunctionType>()->getCallConv();
12025 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
12026 CallingConv ConvToCC =
12027 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
12028
12029 return ConvToCC != CallOpCC;
12030}
12031
12032// Notes the location of an overload candidate.
12034 OverloadCandidateRewriteKind RewriteKind,
12035 QualType DestType, bool TakingAddress) {
12036 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
12037 return;
12038 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
12039 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
12040 return;
12041 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
12042 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
12043 return;
12045 return;
12046
12047 std::string FnDesc;
12048 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
12049 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
12050 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
12051 << (unsigned)KSPair.first << (unsigned)KSPair.second
12052 << Fn << FnDesc;
12053
12054 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
12055 Diag(Fn->getLocation(), PD);
12056 MaybeEmitInheritedConstructorNote(*this, Found);
12057}
12058
12059static void
12061 // Perhaps the ambiguity was caused by two atomic constraints that are
12062 // 'identical' but not equivalent:
12063 //
12064 // void foo() requires (sizeof(T) > 4) { } // #1
12065 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
12066 //
12067 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
12068 // #2 to subsume #1, but these constraint are not considered equivalent
12069 // according to the subsumption rules because they are not the same
12070 // source-level construct. This behavior is quite confusing and we should try
12071 // to help the user figure out what happened.
12072
12073 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
12074 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
12075 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12076 if (!I->Function)
12077 continue;
12079 if (auto *Template = I->Function->getPrimaryTemplate())
12080 Template->getAssociatedConstraints(AC);
12081 else
12082 I->Function->getAssociatedConstraints(AC);
12083 if (AC.empty())
12084 continue;
12085 if (FirstCand == nullptr) {
12086 FirstCand = I->Function;
12087 FirstAC = AC;
12088 } else if (SecondCand == nullptr) {
12089 SecondCand = I->Function;
12090 SecondAC = AC;
12091 } else {
12092 // We have more than one pair of constrained functions - this check is
12093 // expensive and we'd rather not try to diagnose it.
12094 return;
12095 }
12096 }
12097 if (!SecondCand)
12098 return;
12099 // The diagnostic can only happen if there are associated constraints on
12100 // both sides (there needs to be some identical atomic constraint).
12101 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
12102 SecondCand, SecondAC))
12103 // Just show the user one diagnostic, they'll probably figure it out
12104 // from here.
12105 return;
12106}
12107
12108// Notes the location of all overload candidates designated through
12109// OverloadedExpr
12110void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12111 bool TakingAddress) {
12112 assert(OverloadedExpr->getType() == Context.OverloadTy);
12113
12114 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
12115 OverloadExpr *OvlExpr = Ovl.Expression;
12116
12117 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12118 IEnd = OvlExpr->decls_end();
12119 I != IEnd; ++I) {
12120 if (FunctionTemplateDecl *FunTmpl =
12121 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12122 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12123 TakingAddress);
12124 } else if (FunctionDecl *Fun
12125 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12126 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12127 }
12128 }
12129}
12130
12131/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12132/// "lead" diagnostic; it will be given two arguments, the source and
12133/// target types of the conversion.
12135 Sema &S,
12136 SourceLocation CaretLoc,
12137 const PartialDiagnostic &PDiag) const {
12138 S.Diag(CaretLoc, PDiag)
12139 << Ambiguous.getFromType() << Ambiguous.getToType();
12140 unsigned CandsShown = 0;
12142 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12143 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12144 break;
12145 ++CandsShown;
12146 S.NoteOverloadCandidate(I->first, I->second);
12147 }
12148 S.Diags.overloadCandidatesShown(CandsShown);
12149 if (I != E)
12150 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12151}
12152
12154 unsigned I, bool TakingCandidateAddress) {
12155 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12156 assert(Conv.isBad());
12157 assert(Cand->Function && "for now, candidate must be a function");
12158 FunctionDecl *Fn = Cand->Function;
12159
12160 // There's a conversion slot for the object argument if this is a
12161 // non-constructor method. Note that 'I' corresponds the
12162 // conversion-slot index.
12163 bool isObjectArgument = false;
12164 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12166 if (I == 0)
12167 isObjectArgument = true;
12168 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12169 I--;
12170 }
12171
12172 std::string FnDesc;
12173 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12174 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12175 FnDesc);
12176
12177 Expr *FromExpr = Conv.Bad.FromExpr;
12178 QualType FromTy = Conv.Bad.getFromType();
12179 QualType ToTy = Conv.Bad.getToType();
12180 SourceRange ToParamRange;
12181
12182 // FIXME: In presence of parameter packs we can't determine parameter range
12183 // reliably, as we don't have access to instantiation.
12184 bool HasParamPack =
12185 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12186 return Parm->isParameterPack();
12187 });
12188 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12189 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12190
12191 if (FromTy == S.Context.OverloadTy) {
12192 assert(FromExpr && "overload set argument came from implicit argument?");
12193 Expr *E = FromExpr->IgnoreParens();
12194 if (isa<UnaryOperator>(E))
12195 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12196 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12197
12198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12200 << ToParamRange << ToTy << Name << I + 1;
12201 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12202 return;
12203 }
12204
12205 // Do some hand-waving analysis to see if the non-viability is due
12206 // to a qualifier mismatch.
12207 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12208 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12209 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12210 CToTy = RT->getPointeeType();
12211 else {
12212 // TODO: detect and diagnose the full richness of const mismatches.
12213 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12214 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12215 CFromTy = FromPT->getPointeeType();
12216 CToTy = ToPT->getPointeeType();
12217 }
12218 }
12219
12220 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12221 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12222 Qualifiers FromQs = CFromTy.getQualifiers();
12223 Qualifiers ToQs = CToTy.getQualifiers();
12224
12225 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12226 if (isObjectArgument)
12227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12228 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12229 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12230 else
12231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12232 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12233 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12234 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12235 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12236 return;
12237 }
12238
12239 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12241 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12242 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12243 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12244 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12245 return;
12246 }
12247
12248 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12249 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12250 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12251 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12252 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12253 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12254 return;
12255 }
12256
12257 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12258 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12259 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12260 << FromTy << !!FromQs.getPointerAuth()
12261 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12262 << ToQs.getPointerAuth().getAsString() << I + 1
12263 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12264 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12265 return;
12266 }
12267
12268 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12269 assert(CVR && "expected qualifiers mismatch");
12270
12271 if (isObjectArgument) {
12272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12274 << FromTy << (CVR - 1);
12275 } else {
12276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12277 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12278 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12279 }
12280 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12281 return;
12282 }
12283
12286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12287 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12288 << (unsigned)isObjectArgument << I + 1
12290 << ToParamRange;
12291 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12292 return;
12293 }
12294
12295 // Special diagnostic for failure to convert an initializer list, since
12296 // telling the user that it has type void is not useful.
12297 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12299 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12300 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12303 ? 2
12304 : 0);
12305 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12306 return;
12307 }
12308
12309 // Diagnose references or pointers to incomplete types differently,
12310 // since it's far from impossible that the incompleteness triggered
12311 // the failure.
12312 QualType TempFromTy = FromTy.getNonReferenceType();
12313 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12314 TempFromTy = PTy->getPointeeType();
12315 if (TempFromTy->isIncompleteType()) {
12316 // Emit the generic diagnostic and, optionally, add the hints to it.
12317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12318 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12319 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12320 << (unsigned)(Cand->Fix.Kind);
12321
12322 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12323 return;
12324 }
12325
12326 // Diagnose base -> derived pointer conversions.
12327 unsigned BaseToDerivedConversion = 0;
12328 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12329 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12330 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12331 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12332 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12333 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12334 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12335 FromPtrTy->getPointeeType()))
12336 BaseToDerivedConversion = 1;
12337 }
12338 } else if (const ObjCObjectPointerType *FromPtrTy
12339 = FromTy->getAs<ObjCObjectPointerType>()) {
12340 if (const ObjCObjectPointerType *ToPtrTy
12341 = ToTy->getAs<ObjCObjectPointerType>())
12342 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12343 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12344 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12345 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12346 FromIface->isSuperClassOf(ToIface))
12347 BaseToDerivedConversion = 2;
12348 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12349 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12350 S.getASTContext()) &&
12351 !FromTy->isIncompleteType() &&
12352 !ToRefTy->getPointeeType()->isIncompleteType() &&
12353 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12354 BaseToDerivedConversion = 3;
12355 }
12356 }
12357
12358 if (BaseToDerivedConversion) {
12359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12360 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12361 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12362 << I + 1;
12363 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12364 return;
12365 }
12366
12367 if (isa<ObjCObjectPointerType>(CFromTy) &&
12368 isa<PointerType>(CToTy)) {
12369 Qualifiers FromQs = CFromTy.getQualifiers();
12370 Qualifiers ToQs = CToTy.getQualifiers();
12371 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12372 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12373 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12374 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12375 << I + 1;
12376 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12377 return;
12378 }
12379 }
12380
12381 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12382 return;
12383
12384 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12385 // although this is almost always an error and we advise against it.
12386 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12387 ToTy == S.Context.getLogicalOperationType()) {
12388 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12389 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12390 << Conv.Bad.FromExpr << ToTy;
12391 return;
12392 }
12393
12394 // Emit the generic diagnostic and, optionally, add the hints to it.
12395 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12396 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12397 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12398 << (unsigned)(Cand->Fix.Kind);
12399
12400 // Check that location of Fn is not in system header.
12401 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12402 // If we can fix the conversion, suggest the FixIts.
12403 for (const FixItHint &HI : Cand->Fix.Hints)
12404 FDiag << HI;
12405 }
12406
12407 S.Diag(Fn->getLocation(), FDiag);
12408
12409 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12410}
12411
12412/// Additional arity mismatch diagnosis specific to a function overload
12413/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12414/// over a candidate in any candidate set.
12416 unsigned NumArgs, bool IsAddressOf = false) {
12417 assert(Cand->Function && "Candidate is required to be a function.");
12418 FunctionDecl *Fn = Cand->Function;
12419 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12420 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12421
12422 // With invalid overloaded operators, it's possible that we think we
12423 // have an arity mismatch when in fact it looks like we have the
12424 // right number of arguments, because only overloaded operators have
12425 // the weird behavior of overloading member and non-member functions.
12426 // Just don't report anything.
12427 if (Fn->isInvalidDecl() &&
12428 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12429 return true;
12430
12431 if (NumArgs < MinParams) {
12432 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12434 Cand->DeductionFailure.getResult() ==
12436 } else {
12437 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12439 Cand->DeductionFailure.getResult() ==
12441 }
12442
12443 return false;
12444}
12445
12446/// General arity mismatch diagnosis over a candidate in a candidate set.
12448 unsigned NumFormalArgs,
12449 bool IsAddressOf = false) {
12450 assert(isa<FunctionDecl>(D) &&
12451 "The templated declaration should at least be a function"
12452 " when diagnosing bad template argument deduction due to too many"
12453 " or too few arguments");
12454
12456
12457 // TODO: treat calls to a missing default constructor as a special case
12458 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12459 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12460 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12461
12462 // at least / at most / exactly
12463 bool HasExplicitObjectParam =
12464 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12465
12466 unsigned ParamCount =
12467 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12468 unsigned mode, modeCount;
12469
12470 if (NumFormalArgs < MinParams) {
12471 if (MinParams != ParamCount || FnTy->isVariadic() ||
12472 FnTy->isTemplateVariadic())
12473 mode = 0; // "at least"
12474 else
12475 mode = 2; // "exactly"
12476 modeCount = MinParams;
12477 } else {
12478 if (MinParams != ParamCount)
12479 mode = 1; // "at most"
12480 else
12481 mode = 2; // "exactly"
12482 modeCount = ParamCount;
12483 }
12484
12485 std::string Description;
12486 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12487 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12488
12489 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12490 if (modeCount == 1 && !IsAddressOf &&
12491 FirstNonObjectParamIdx < Fn->getNumParams() &&
12492 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12494 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12495 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12496 << NumFormalArgs << HasExplicitObjectParam
12497 << Fn->getParametersSourceRange();
12498 else
12499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12500 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12501 << Description << mode << modeCount << NumFormalArgs
12502 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12503
12504 MaybeEmitInheritedConstructorNote(S, Found);
12505}
12506
12507/// Arity mismatch diagnosis specific to a function overload candidate.
12509 unsigned NumFormalArgs) {
12510 assert(Cand->Function && "Candidate must be a function");
12511 FunctionDecl *Fn = Cand->Function;
12512 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12513 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12514 Cand->TookAddressOfOverload);
12515}
12516
12518 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12519 return TD;
12520 llvm_unreachable("Unsupported: Getting the described template declaration"
12521 " for bad deduction diagnosis");
12522}
12523
12524/// Diagnose a failed template-argument deduction.
12525static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12526 DeductionFailureInfo &DeductionFailure,
12527 unsigned NumArgs, bool TakingCandidateAddress,
12528 TemplateSpecCandidateSetKind CandidateSetKind =
12530 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12531 NamedDecl *ParamD = dyn_cast_if_present<TemplateTypeParmDecl *>(Param);
12532 if (!ParamD)
12533 ParamD = dyn_cast_if_present<NonTypeTemplateParmDecl *>(Param);
12534 if (!ParamD)
12535 ParamD = dyn_cast_if_present<TemplateTemplateParmDecl *>(Param);
12536 switch (DeductionFailure.getResult()) {
12538 llvm_unreachable(
12539 "TemplateDeductionResult::Success while diagnosing bad deduction");
12541 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12542 "while diagnosing bad deduction");
12545 return;
12546
12548 assert(ParamD && "no parameter found for incomplete deduction result");
12549 S.Diag(Templated->getLocation(),
12550 diag::note_ovl_candidate_incomplete_deduction)
12551 << ParamD->getDeclName();
12552 MaybeEmitInheritedConstructorNote(S, Found);
12553 return;
12554 }
12555
12557 assert(ParamD && "no parameter found for incomplete deduction result");
12558 S.Diag(Templated->getLocation(),
12559 diag::note_ovl_candidate_incomplete_deduction_pack)
12560 << ParamD->getDeclName()
12561 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12562 << *DeductionFailure.getFirstArg();
12563 MaybeEmitInheritedConstructorNote(S, Found);
12564 return;
12565 }
12566
12568 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12570
12571 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12572
12573 // Param will have been canonicalized, but it should just be a
12574 // qualified version of ParamD, so move the qualifiers to that.
12576 Qs.strip(Param);
12577 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12578 assert(S.Context.hasSameType(Param, NonCanonParam));
12579
12580 // Arg has also been canonicalized, but there's nothing we can do
12581 // about that. It also doesn't matter as much, because it won't
12582 // have any template parameters in it (because deduction isn't
12583 // done on dependent types).
12584 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12585
12586 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12587 << ParamD->getDeclName() << Arg << NonCanonParam;
12588 MaybeEmitInheritedConstructorNote(S, Found);
12589 return;
12590 }
12591
12593 assert(ParamD && "no parameter found for inconsistent deduction result");
12594 int which = 0;
12595 if (isa<TemplateTypeParmDecl>(ParamD))
12596 which = 0;
12597 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12598 // Deduction might have failed because we deduced arguments of two
12599 // different types for a non-type template parameter.
12600 // FIXME: Use a different TDK value for this.
12601 QualType T1 =
12602 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12603 QualType T2 =
12604 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12605 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12606 S.Diag(Templated->getLocation(),
12607 diag::note_ovl_candidate_inconsistent_deduction_types)
12608 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12609 << *DeductionFailure.getSecondArg() << T2;
12610 MaybeEmitInheritedConstructorNote(S, Found);
12611 return;
12612 }
12613
12614 which = 1;
12615 } else {
12616 which = 2;
12617 }
12618
12619 // Tweak the diagnostic if the problem is that we deduced packs of
12620 // different arities. We'll print the actual packs anyway in case that
12621 // includes additional useful information.
12622 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12623 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12624 DeductionFailure.getFirstArg()->pack_size() !=
12625 DeductionFailure.getSecondArg()->pack_size()) {
12626 which = 3;
12627 }
12628
12629 S.Diag(Templated->getLocation(),
12630 diag::note_ovl_candidate_inconsistent_deduction)
12631 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12632 << *DeductionFailure.getSecondArg();
12633 MaybeEmitInheritedConstructorNote(S, Found);
12634 return;
12635 }
12636
12638 assert(ParamD && "no parameter found for invalid explicit arguments");
12639
12640 auto Diag = S.Diag(Templated->getLocation(),
12641 diag::note_ovl_candidate_explicit_arg_mismatch);
12642 if (ParamD->getDeclName())
12643 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12644 else
12645 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12646 << (getDepthAndIndex(ParamD).second + 1);
12647 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12648 SmallString<128> DiagContent;
12649 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12650 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12651 } else {
12652 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12653 }
12654
12655 MaybeEmitInheritedConstructorNote(S, Found);
12656 return;
12657 }
12659 // Format the template argument list into the argument string.
12660 SmallString<128> TemplateArgString;
12661 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12662 TemplateArgString = " ";
12663 TemplateArgString += S.getTemplateArgumentBindingsText(
12664 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12665 if (TemplateArgString.size() == 1)
12666 TemplateArgString.clear();
12667 S.Diag(Templated->getLocation(),
12668 diag::note_ovl_candidate_unsatisfied_constraints)
12669 << TemplateArgString;
12670
12672 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12673 return;
12674 }
12677 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12678 return;
12679
12681 S.Diag(Templated->getLocation(),
12682 diag::note_ovl_candidate_instantiation_depth);
12683 MaybeEmitInheritedConstructorNote(S, Found);
12684 return;
12685
12687 // Format the template argument list into the argument string.
12688 SmallString<128> TemplateArgString;
12689 if (TemplateArgumentList *Args =
12690 DeductionFailure.getTemplateArgumentList()) {
12691 TemplateArgString = " ";
12692 TemplateArgString += S.getTemplateArgumentBindingsText(
12693 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12694 if (TemplateArgString.size() == 1)
12695 TemplateArgString.clear();
12696 }
12697
12698 // If this candidate was disabled by enable_if, say so.
12699 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12700 if (PDiag && PDiag->second.getDiagID() ==
12701 diag::err_typename_nested_not_found_enable_if) {
12702 // FIXME: Use the source range of the condition, and the fully-qualified
12703 // name of the enable_if template. These are both present in PDiag.
12704 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12705 << "'enable_if'" << TemplateArgString;
12706 return;
12707 }
12708
12709 // We found a specific requirement that disabled the enable_if.
12710 if (PDiag && PDiag->second.getDiagID() ==
12711 diag::err_typename_nested_not_found_requirement) {
12712 S.Diag(Templated->getLocation(),
12713 diag::note_ovl_candidate_disabled_by_requirement)
12714 << PDiag->second.getStringArg(0) << TemplateArgString;
12715 return;
12716 }
12717
12718 // Format the SFINAE diagnostic into the argument string.
12719 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12720 // formatted message in another diagnostic.
12721 SmallString<128> SFINAEArgString;
12722 SourceRange R;
12723 if (PDiag) {
12724 SFINAEArgString = ": ";
12725 R = SourceRange(PDiag->first, PDiag->first);
12726 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12727 }
12728
12729 S.Diag(Templated->getLocation(),
12730 diag::note_ovl_candidate_substitution_failure)
12731 << TemplateArgString << SFINAEArgString << R;
12732 MaybeEmitInheritedConstructorNote(S, Found);
12733 return;
12734 }
12735
12738 // Format the template argument list into the argument string.
12739 SmallString<128> TemplateArgString;
12740 if (TemplateArgumentList *Args =
12741 DeductionFailure.getTemplateArgumentList()) {
12742 TemplateArgString = " ";
12743 TemplateArgString += S.getTemplateArgumentBindingsText(
12744 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12745 if (TemplateArgString.size() == 1)
12746 TemplateArgString.clear();
12747 }
12748
12749 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12750 << (*DeductionFailure.getCallArgIndex() + 1)
12751 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12752 << TemplateArgString
12753 << (DeductionFailure.getResult() ==
12755 break;
12756 }
12757
12759 // FIXME: Provide a source location to indicate what we couldn't match.
12760 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12761 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12762 if (FirstTA.getKind() == TemplateArgument::Template &&
12763 SecondTA.getKind() == TemplateArgument::Template) {
12764 TemplateName FirstTN = FirstTA.getAsTemplate();
12765 TemplateName SecondTN = SecondTA.getAsTemplate();
12766 if (FirstTN.getKind() == TemplateName::Template &&
12767 SecondTN.getKind() == TemplateName::Template) {
12768 if (FirstTN.getAsTemplateDecl()->getName() ==
12769 SecondTN.getAsTemplateDecl()->getName()) {
12770 // FIXME: This fixes a bad diagnostic where both templates are named
12771 // the same. This particular case is a bit difficult since:
12772 // 1) It is passed as a string to the diagnostic printer.
12773 // 2) The diagnostic printer only attempts to find a better
12774 // name for types, not decls.
12775 // Ideally, this should folded into the diagnostic printer.
12776 S.Diag(Templated->getLocation(),
12777 CandidateSetKind ==
12779 ? diag::note_friend_template_non_deduced_mismatch_qualified
12780 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12781 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12782 return;
12783 }
12784 }
12785 }
12786
12787 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12789 return;
12790
12791 // FIXME: For generic lambda parameters, check if the function is a lambda
12792 // call operator, and if so, emit a prettier and more informative
12793 // diagnostic that mentions 'auto' and lambda in addition to
12794 // (or instead of?) the canonical template type parameters.
12795 S.Diag(Templated->getLocation(),
12797 ? diag::note_friend_template_non_deduced_mismatch
12798 : diag::note_ovl_candidate_non_deduced_mismatch)
12799 << FirstTA << SecondTA;
12800 return;
12801 }
12802 // TODO: diagnose these individually, then kill off
12803 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12805 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12806 MaybeEmitInheritedConstructorNote(S, Found);
12807 return;
12809 S.Diag(Templated->getLocation(),
12810 diag::note_cuda_ovl_candidate_target_mismatch);
12811 return;
12812 }
12813}
12814
12815/// Diagnose a failed template-argument deduction, for function calls.
12817 unsigned NumArgs,
12818 bool TakingCandidateAddress) {
12819 assert(Cand->Function && "Candidate must be a function");
12820 FunctionDecl *Fn = Cand->Function;
12824 if (CheckArityMismatch(S, Cand, NumArgs))
12825 return;
12826 }
12827 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12828 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12829}
12830
12831/// CUDA: diagnose an invalid call across targets.
12833 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12834 assert(Cand->Function && "Candidate must be a Function.");
12835 FunctionDecl *Callee = Cand->Function;
12836
12837 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12838 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12839
12840 std::string FnDesc;
12841 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12842 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12843 Cand->getRewriteKind(), FnDesc);
12844
12845 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12846 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12847 << FnDesc /* Ignored */
12848 << CalleeTarget << CallerTarget;
12849
12850 // This could be an implicit constructor for which we could not infer the
12851 // target due to a collsion. Diagnose that case.
12852 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12853 if (Meth != nullptr && Meth->isImplicit()) {
12854 CXXRecordDecl *ParentClass = Meth->getParent();
12856
12857 switch (FnKindPair.first) {
12858 default:
12859 return;
12860 case oc_implicit_default_constructor:
12862 break;
12863 case oc_implicit_copy_constructor:
12865 break;
12866 case oc_implicit_move_constructor:
12868 break;
12869 case oc_implicit_copy_assignment:
12871 break;
12872 case oc_implicit_move_assignment:
12874 break;
12875 };
12876
12877 bool ConstRHS = false;
12878 if (Meth->getNumParams()) {
12879 if (const ReferenceType *RT =
12880 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12881 ConstRHS = RT->getPointeeType().isConstQualified();
12882 }
12883 }
12884
12885 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12886 /* ConstRHS */ ConstRHS,
12887 /* Diagnose */ true);
12888 }
12889}
12890
12892 assert(Cand->Function && "Candidate must be a function");
12893 FunctionDecl *Callee = Cand->Function;
12894 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12895
12896 S.Diag(Callee->getLocation(),
12897 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12898 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12899}
12900
12902 assert(Cand->Function && "Candidate must be a function");
12903 FunctionDecl *Fn = Cand->Function;
12905 assert(ES.isExplicit() && "not an explicit candidate");
12906
12907 unsigned Kind;
12908 switch (Fn->getDeclKind()) {
12909 case Decl::Kind::CXXConstructor:
12910 Kind = 0;
12911 break;
12912 case Decl::Kind::CXXConversion:
12913 Kind = 1;
12914 break;
12915 case Decl::Kind::CXXDeductionGuide:
12916 Kind = Fn->isImplicit() ? 0 : 2;
12917 break;
12918 default:
12919 llvm_unreachable("invalid Decl");
12920 }
12921
12922 // Note the location of the first (in-class) declaration; a redeclaration
12923 // (particularly an out-of-class definition) will typically lack the
12924 // 'explicit' specifier.
12925 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12926 FunctionDecl *First = Fn->getFirstDecl();
12927 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12928 First = Pattern->getFirstDecl();
12929
12930 S.Diag(First->getLocation(),
12931 diag::note_ovl_candidate_explicit)
12932 << Kind << (ES.getExpr() ? 1 : 0)
12933 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12934}
12935
12937 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12938 if (!DG)
12939 return;
12940 TemplateDecl *OriginTemplate =
12942 // We want to always print synthesized deduction guides for type aliases.
12943 // They would retain the explicit bit of the corresponding constructor.
12944 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12945 return;
12946 std::string FunctionProto;
12947 llvm::raw_string_ostream OS(FunctionProto);
12948 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12949 if (!Template) {
12950 // This also could be an instantiation. Find out the primary template.
12951 FunctionDecl *Pattern =
12952 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12953 if (!Pattern) {
12954 // The implicit deduction guide is built on an explicit non-template
12955 // deduction guide. Currently, this might be the case only for type
12956 // aliases.
12957 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12958 // gets merged.
12959 assert(OriginTemplate->isTypeAlias() &&
12960 "Non-template implicit deduction guides are only possible for "
12961 "type aliases");
12962 DG->print(OS);
12963 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12964 << FunctionProto;
12965 return;
12966 }
12968 assert(Template && "Cannot find the associated function template of "
12969 "CXXDeductionGuideDecl?");
12970 }
12971 Template->print(OS);
12972 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12973 << FunctionProto;
12974}
12975
12976/// Generates a 'note' diagnostic for an overload candidate. We've
12977/// already generated a primary error at the call site.
12978///
12979/// It really does need to be a single diagnostic with its caret
12980/// pointed at the candidate declaration. Yes, this creates some
12981/// major challenges of technical writing. Yes, this makes pointing
12982/// out problems with specific arguments quite awkward. It's still
12983/// better than generating twenty screens of text for every failed
12984/// overload.
12985///
12986/// It would be great to be able to express per-candidate problems
12987/// more richly for those diagnostic clients that cared, but we'd
12988/// still have to be just as careful with the default diagnostics.
12989/// \param CtorDestAS Addr space of object being constructed (for ctor
12990/// candidates only).
12992 unsigned NumArgs,
12993 bool TakingCandidateAddress,
12994 LangAS CtorDestAS = LangAS::Default) {
12995 assert(Cand->Function && "Candidate must be a function");
12996 FunctionDecl *Fn = Cand->Function;
12998 return;
12999
13000 // There is no physical candidate declaration to point to for OpenCL builtins.
13001 // Except for failed conversions, the notes are identical for each candidate,
13002 // so do not generate such notes.
13003 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
13005 return;
13006
13007 // Skip implicit member functions when trying to resolve
13008 // the address of a an overload set for a function pointer.
13009 if (Cand->TookAddressOfOverload &&
13010 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
13011 return;
13012
13013 // Note deleted candidates, but only if they're viable.
13014 if (Cand->Viable) {
13015 if (Fn->isDeleted()) {
13016 std::string FnDesc;
13017 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13018 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13019 Cand->getRewriteKind(), FnDesc);
13020
13021 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
13022 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
13023 << (Fn->isDeleted()
13024 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
13025 : 0);
13026 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13027 return;
13028 }
13029
13030 // We don't really have anything else to say about viable candidates.
13031 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13032 return;
13033 }
13034
13035 // If this is a synthesized deduction guide we're deducing against, add a note
13036 // for it. These deduction guides are not explicitly spelled in the source
13037 // code, so simply printing a deduction failure note mentioning synthesized
13038 // template parameters or pointing to the header of the surrounding RecordDecl
13039 // would be confusing.
13040 //
13041 // We prefer adding such notes at the end of the deduction failure because
13042 // duplicate code snippets appearing in the diagnostic would likely become
13043 // noisy.
13044 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
13045
13046 switch (Cand->FailureKind) {
13049 return DiagnoseArityMismatch(S, Cand, NumArgs);
13050
13052 return DiagnoseBadDeduction(S, Cand, NumArgs,
13053 TakingCandidateAddress);
13054
13056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
13057 << (Fn->getPrimaryTemplate() ? 1 : 0);
13058 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13059 return;
13060 }
13061
13063 Qualifiers QualsForPrinting;
13064 QualsForPrinting.setAddressSpace(CtorDestAS);
13065 S.Diag(Fn->getLocation(),
13066 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
13067 << QualsForPrinting;
13068 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13069 return;
13070 }
13071
13075 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13076
13078 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
13079 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
13080 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
13081 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13082
13083 // FIXME: this currently happens when we're called from SemaInit
13084 // when user-conversion overload fails. Figure out how to handle
13085 // those conditions and diagnose them well.
13086 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13087 }
13088
13090 return DiagnoseBadTarget(S, Cand);
13091
13092 case ovl_fail_enable_if:
13093 return DiagnoseFailedEnableIfAttr(S, Cand);
13094
13095 case ovl_fail_explicit:
13096 return DiagnoseFailedExplicitSpec(S, Cand);
13097
13099 // It's generally not interesting to note copy/move constructors here.
13100 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
13101 return;
13102 S.Diag(Fn->getLocation(),
13103 diag::note_ovl_candidate_inherited_constructor_slice)
13104 << (Fn->getPrimaryTemplate() ? 1 : 0)
13105 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
13106 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13107 return;
13108
13110 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
13111 (void)Available;
13112 assert(!Available);
13113 break;
13114 }
13116 // Do nothing, these should simply be ignored.
13117 break;
13118
13120 std::string FnDesc;
13121 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13122 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13123 Cand->getRewriteKind(), FnDesc);
13124
13125 S.Diag(Fn->getLocation(),
13126 diag::note_ovl_candidate_constraints_not_satisfied)
13127 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13128 << FnDesc /* Ignored */;
13129 ConstraintSatisfaction Satisfaction;
13130 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13131 /*ForOverloadResolution=*/true))
13132 break;
13133 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13134 }
13135 }
13136}
13137
13140 return;
13141
13142 // Desugar the type of the surrogate down to a function type,
13143 // retaining as many typedefs as possible while still showing
13144 // the function type (and, therefore, its parameter types).
13145 QualType FnType = Cand->Surrogate->getConversionType();
13146 bool isLValueReference = false;
13147 bool isRValueReference = false;
13148 bool isPointer = false;
13149 if (const LValueReferenceType *FnTypeRef =
13150 FnType->getAs<LValueReferenceType>()) {
13151 FnType = FnTypeRef->getPointeeType();
13152 isLValueReference = true;
13153 } else if (const RValueReferenceType *FnTypeRef =
13154 FnType->getAs<RValueReferenceType>()) {
13155 FnType = FnTypeRef->getPointeeType();
13156 isRValueReference = true;
13157 }
13158 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13159 FnType = FnTypePtr->getPointeeType();
13160 isPointer = true;
13161 }
13162 // Desugar down to a function type.
13163 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13164 // Reconstruct the pointer/reference as appropriate.
13165 if (isPointer) FnType = S.Context.getPointerType(FnType);
13166 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13167 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13168
13169 if (!Cand->Viable &&
13171 S.Diag(Cand->Surrogate->getLocation(),
13172 diag::note_ovl_surrogate_constraints_not_satisfied)
13173 << Cand->Surrogate;
13174 ConstraintSatisfaction Satisfaction;
13175 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13176 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13177 } else {
13178 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13179 << FnType;
13180 }
13181}
13182
13183static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13184 SourceLocation OpLoc,
13185 OverloadCandidate *Cand) {
13186 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13187 std::string TypeStr("operator");
13188 TypeStr += Opc;
13189 TypeStr += "(";
13190 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13191 if (Cand->Conversions.size() == 1) {
13192 TypeStr += ")";
13193 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13194 } else {
13195 TypeStr += ", ";
13196 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13197 TypeStr += ")";
13198 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13199 }
13200}
13201
13203 OverloadCandidate *Cand) {
13204 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13205 if (ICS.isBad()) break; // all meaningless after first invalid
13206 if (!ICS.isAmbiguous()) continue;
13207
13209 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13210 }
13211}
13212
13214 if (Cand->Function)
13215 return Cand->Function->getLocation();
13216 if (Cand->IsSurrogate)
13217 return Cand->Surrogate->getLocation();
13218 return SourceLocation();
13219}
13220
13221static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13222 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13226 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13227
13231 return 1;
13232
13235 return 2;
13236
13244 return 3;
13245
13247 return 4;
13248
13250 return 5;
13251
13254 return 6;
13255 }
13256 llvm_unreachable("Unhandled deduction result");
13257}
13258
13259namespace {
13260
13261struct CompareOverloadCandidatesForDisplay {
13262 Sema &S;
13263 SourceLocation Loc;
13264 size_t NumArgs;
13266
13267 CompareOverloadCandidatesForDisplay(
13268 Sema &S, SourceLocation Loc, size_t NArgs,
13270 : S(S), NumArgs(NArgs), CSK(CSK) {}
13271
13272 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13273 // If there are too many or too few arguments, that's the high-order bit we
13274 // want to sort by, even if the immediate failure kind was something else.
13275 if (C->FailureKind == ovl_fail_too_many_arguments ||
13276 C->FailureKind == ovl_fail_too_few_arguments)
13277 return static_cast<OverloadFailureKind>(C->FailureKind);
13278
13279 if (C->Function) {
13280 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13282 if (NumArgs < C->Function->getMinRequiredArguments())
13284 }
13285
13286 return static_cast<OverloadFailureKind>(C->FailureKind);
13287 }
13288
13289 bool operator()(const OverloadCandidate *L,
13290 const OverloadCandidate *R) {
13291 // Fast-path this check.
13292 if (L == R) return false;
13293
13294 // Order first by viability.
13295 if (L->Viable) {
13296 if (!R->Viable) return true;
13297
13298 if (int Ord = CompareConversions(*L, *R))
13299 return Ord < 0;
13300 // Use other tie breakers.
13301 } else if (R->Viable)
13302 return false;
13303
13304 assert(L->Viable == R->Viable);
13305
13306 // Criteria by which we can sort non-viable candidates:
13307 if (!L->Viable) {
13308 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13309 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13310
13311 // 1. Arity mismatches come after other candidates.
13312 if (LFailureKind == ovl_fail_too_many_arguments ||
13313 LFailureKind == ovl_fail_too_few_arguments) {
13314 if (RFailureKind == ovl_fail_too_many_arguments ||
13315 RFailureKind == ovl_fail_too_few_arguments) {
13316 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13317 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13318 if (LDist == RDist) {
13319 if (LFailureKind == RFailureKind)
13320 // Sort non-surrogates before surrogates.
13321 return !L->IsSurrogate && R->IsSurrogate;
13322 // Sort candidates requiring fewer parameters than there were
13323 // arguments given after candidates requiring more parameters
13324 // than there were arguments given.
13325 return LFailureKind == ovl_fail_too_many_arguments;
13326 }
13327 return LDist < RDist;
13328 }
13329 return false;
13330 }
13331 if (RFailureKind == ovl_fail_too_many_arguments ||
13332 RFailureKind == ovl_fail_too_few_arguments)
13333 return true;
13334
13335 // 2. Bad conversions come first and are ordered by the number
13336 // of bad conversions and quality of good conversions.
13337 if (LFailureKind == ovl_fail_bad_conversion) {
13338 if (RFailureKind != ovl_fail_bad_conversion)
13339 return true;
13340
13341 // The conversion that can be fixed with a smaller number of changes,
13342 // comes first.
13343 unsigned numLFixes = L->Fix.NumConversionsFixed;
13344 unsigned numRFixes = R->Fix.NumConversionsFixed;
13345 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13346 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13347 if (numLFixes != numRFixes) {
13348 return numLFixes < numRFixes;
13349 }
13350
13351 // If there's any ordering between the defined conversions...
13352 if (int Ord = CompareConversions(*L, *R))
13353 return Ord < 0;
13354 } else if (RFailureKind == ovl_fail_bad_conversion)
13355 return false;
13356
13357 if (LFailureKind == ovl_fail_bad_deduction) {
13358 if (RFailureKind != ovl_fail_bad_deduction)
13359 return true;
13360
13361 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13362 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13363 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13364 if (LRank != RRank)
13365 return LRank < RRank;
13366 }
13367 } else if (RFailureKind == ovl_fail_bad_deduction)
13368 return false;
13369
13370 // TODO: others?
13371 }
13372
13373 // Sort everything else by location.
13374 SourceLocation LLoc = GetLocationForCandidate(L);
13375 SourceLocation RLoc = GetLocationForCandidate(R);
13376
13377 // Put candidates without locations (e.g. builtins) at the end.
13378 if (LLoc.isValid() && RLoc.isValid())
13379 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13380 if (LLoc.isValid() && !RLoc.isValid())
13381 return true;
13382 if (RLoc.isValid() && !LLoc.isValid())
13383 return false;
13384 assert(!LLoc.isValid() && !RLoc.isValid());
13385 // For builtins and other functions without locations, fallback to the order
13386 // in which they were added into the candidate set.
13387 return L < R;
13388 }
13389
13390private:
13391 struct ConversionSignals {
13392 unsigned KindRank = 0;
13394
13395 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13396 ConversionSignals Sig;
13397 Sig.KindRank = Seq.getKindRank();
13398 if (Seq.isStandard())
13399 Sig.Rank = Seq.Standard.getRank();
13400 else if (Seq.isUserDefined())
13401 Sig.Rank = Seq.UserDefined.After.getRank();
13402 // We intend StaticObjectArgumentConversion to compare the same as
13403 // StandardConversion with ICR_ExactMatch rank.
13404 return Sig;
13405 }
13406
13407 static ConversionSignals ForObjectArgument() {
13408 // We intend StaticObjectArgumentConversion to compare the same as
13409 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13410 return {};
13411 }
13412 };
13413
13414 // Returns -1 if conversions in L are considered better.
13415 // 0 if they are considered indistinguishable.
13416 // 1 if conversions in R are better.
13417 int CompareConversions(const OverloadCandidate &L,
13418 const OverloadCandidate &R) {
13419 // We cannot use `isBetterOverloadCandidate` because it is defined
13420 // according to the C++ standard and provides a partial order, but we need
13421 // a total order as this function is used in sort.
13422 assert(L.Conversions.size() == R.Conversions.size());
13423 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13424 auto LS = L.IgnoreObjectArgument && I == 0
13425 ? ConversionSignals::ForObjectArgument()
13426 : ConversionSignals::ForSequence(L.Conversions[I]);
13427 auto RS = R.IgnoreObjectArgument
13428 ? ConversionSignals::ForObjectArgument()
13429 : ConversionSignals::ForSequence(R.Conversions[I]);
13430 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13431 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13432 ? -1
13433 : 1;
13434 }
13435 // FIXME: find a way to compare templates for being more or less
13436 // specialized that provides a strict weak ordering.
13437 return 0;
13438 }
13439};
13440}
13441
13442/// CompleteNonViableCandidate - Normally, overload resolution only
13443/// computes up to the first bad conversion. Produces the FixIt set if
13444/// possible.
13445static void
13447 ArrayRef<Expr *> Args,
13449 assert(!Cand->Viable);
13450
13451 // Don't do anything on failures other than bad conversion.
13453 return;
13454
13455 // We only want the FixIts if all the arguments can be corrected.
13456 bool Unfixable = false;
13457 // Use a implicit copy initialization to check conversion fixes.
13459
13460 // Attempt to fix the bad conversion.
13461 unsigned ConvCount = Cand->Conversions.size();
13462 for (unsigned ConvIdx =
13463 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13464 : 0);
13465 /**/; ++ConvIdx) {
13466 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13467 if (Cand->Conversions[ConvIdx].isInitialized() &&
13468 Cand->Conversions[ConvIdx].isBad()) {
13469 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13470 break;
13471 }
13472 }
13473
13474 // FIXME: this should probably be preserved from the overload
13475 // operation somehow.
13476 bool SuppressUserConversions = false;
13477
13478 unsigned ConvIdx = 0;
13479 unsigned ArgIdx = 0;
13480 ArrayRef<QualType> ParamTypes;
13481 bool Reversed = Cand->isReversed();
13482
13483 if (Cand->IsSurrogate) {
13484 QualType ConvType
13486 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13487 ConvType = ConvPtrType->getPointeeType();
13488 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13489 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13490 ConvIdx = 1;
13491 } else if (Cand->Function) {
13492 ParamTypes =
13493 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13494 if (isa<CXXMethodDecl>(Cand->Function) &&
13497 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13498 ConvIdx = 1;
13500 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13502 OO_Subscript)
13503 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13504 ArgIdx = 1;
13505 }
13506 } else {
13507 // Builtin operator.
13508 assert(ConvCount <= 3);
13509 ParamTypes = Cand->BuiltinParamTypes;
13510 }
13511
13512 // Fill in the rest of the conversions.
13513 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13514 ConvIdx != ConvCount && ArgIdx < Args.size();
13515 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13516 if (Cand->Conversions[ConvIdx].isInitialized()) {
13517 // We've already checked this conversion.
13518 } else if (ParamIdx < ParamTypes.size()) {
13519 if (ParamTypes[ParamIdx]->isDependentType())
13520 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13521 Args[ArgIdx]->getType());
13522 else {
13523 Cand->Conversions[ConvIdx] =
13524 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13525 SuppressUserConversions,
13526 /*InOverloadResolution=*/true,
13527 /*AllowObjCWritebackConversion=*/
13528 S.getLangOpts().ObjCAutoRefCount);
13529 // Store the FixIt in the candidate if it exists.
13530 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13531 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13532 }
13533 } else
13534 Cand->Conversions[ConvIdx].setEllipsis();
13535 }
13536}
13537
13540 SourceLocation OpLoc,
13541 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13542
13544
13545 // Sort the candidates by viability and position. Sorting directly would
13546 // be prohibitive, so we make a set of pointers and sort those.
13548 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13549 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13550 Cand != LastCand; ++Cand) {
13551 if (!Filter(*Cand))
13552 continue;
13553 switch (OCD) {
13554 case OCD_AllCandidates:
13555 if (!Cand->Viable) {
13556 if (!Cand->Function && !Cand->IsSurrogate) {
13557 // This a non-viable builtin candidate. We do not, in general,
13558 // want to list every possible builtin candidate.
13559 continue;
13560 }
13561 CompleteNonViableCandidate(S, Cand, Args, Kind);
13562 }
13563 break;
13564
13566 if (!Cand->Viable)
13567 continue;
13568 break;
13569
13571 if (!Cand->Best)
13572 continue;
13573 break;
13574 }
13575
13576 Cands.push_back(Cand);
13577 }
13578
13579 llvm::stable_sort(
13580 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13581
13582 return Cands;
13583}
13584
13586 SourceLocation OpLoc) {
13587 bool DeferHint = false;
13588 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13589 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13590 // host device candidates.
13591 auto WrongSidedCands =
13592 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13593 return (Cand.Viable == false &&
13595 (Cand.Function &&
13596 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13597 Cand.Function->template hasAttr<CUDADeviceAttr>());
13598 });
13599 DeferHint = !WrongSidedCands.empty();
13600 }
13601 return DeferHint;
13602}
13603
13604/// When overload resolution fails, prints diagnostic messages containing the
13605/// candidates in the candidate set.
13608 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13609 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13610
13611 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13612
13613 {
13614 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13615 S.Diag(PD.first, PD.second);
13616 }
13617
13618 // In WebAssembly we don't want to emit further diagnostics if a table is
13619 // passed as an argument to a function.
13620 bool NoteCands = true;
13621 for (const Expr *Arg : Args) {
13622 if (Arg->getType()->isWebAssemblyTableType())
13623 NoteCands = false;
13624 }
13625
13626 if (NoteCands)
13627 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13628
13629 if (OCD == OCD_AmbiguousCandidates)
13631 {Candidates.begin(), Candidates.end()});
13632}
13633
13636 StringRef Opc, SourceLocation OpLoc) {
13637 bool ReportedAmbiguousConversions = false;
13638
13639 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13640 unsigned CandsShown = 0;
13641 auto I = Cands.begin(), E = Cands.end();
13642 for (; I != E; ++I) {
13643 OverloadCandidate *Cand = *I;
13644
13645 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13646 ShowOverloads == Ovl_Best) {
13647 break;
13648 }
13649 ++CandsShown;
13650
13651 if (Cand->Function)
13652 NoteFunctionCandidate(S, Cand, Args.size(),
13653 Kind == CSK_AddressOfOverloadSet, DestAS);
13654 else if (Cand->IsSurrogate)
13655 NoteSurrogateCandidate(S, Cand);
13656 else {
13657 assert(Cand->Viable &&
13658 "Non-viable built-in candidates are not added to Cands.");
13659 // Generally we only see ambiguities including viable builtin
13660 // operators if overload resolution got screwed up by an
13661 // ambiguous user-defined conversion.
13662 //
13663 // FIXME: It's quite possible for different conversions to see
13664 // different ambiguities, though.
13665 if (!ReportedAmbiguousConversions) {
13666 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13667 ReportedAmbiguousConversions = true;
13668 }
13669
13670 // If this is a viable builtin, print it.
13671 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13672 }
13673 }
13674
13675 // Inform S.Diags that we've shown an overload set with N elements. This may
13676 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13677 S.Diags.overloadCandidatesShown(CandsShown);
13678
13679 if (I != E) {
13680 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13681 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13682 }
13683}
13684
13686 const Sema &S) const {
13687 if (S.getLangOpts().CUDA) {
13688 auto *Caller = S.getCurFunctionDecl(true);
13689 // Overloading based on __host__ and __device__ attributes takes
13690 // higher priority, HD functions may favor template candidates even when a
13691 // non-template candidate would be a perfect match.
13692 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13693 Caller->hasAttr<CUDADeviceAttr>())
13694 return false;
13695 }
13696
13697 return
13698 // For user defined conversion we need to check against different
13699 // combination of CV qualifiers and look at any explicit specifier, so
13700 // always deduce template candidates.
13702 // When doing code completion, we want to see all the
13703 // viable candidates.
13704 && Kind != CSK_CodeCompletion;
13705}
13706
13707static SourceLocation
13709 return Cand->Specialization ? Cand->Specialization->getLocation()
13710 : SourceLocation();
13711}
13712
13713namespace {
13714struct CompareTemplateSpecCandidatesForDisplay {
13715 Sema &S;
13716 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13717
13718 bool operator()(const TemplateSpecCandidate *L,
13719 const TemplateSpecCandidate *R) {
13720 // Fast-path this check.
13721 if (L == R)
13722 return false;
13723
13724 // Assuming that both candidates are not matches...
13725
13726 // Sort by the ranking of deduction failures.
13727 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13729 RankDeductionFailure(R->DeductionFailure);
13730
13731 // Sort everything else by location.
13732 SourceLocation LLoc = GetLocationForCandidate(L);
13733 SourceLocation RLoc = GetLocationForCandidate(R);
13734
13735 // Put candidates without locations (e.g. builtins) at the end.
13736 if (LLoc.isInvalid())
13737 return false;
13738 if (RLoc.isInvalid())
13739 return true;
13740
13741 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13742 }
13743};
13744}
13745
13746/// Diagnose a template argument deduction failure.
13747/// We are treating these failures as overload failures due to bad
13748/// deductions.
13750 Sema &S, bool ForTakingAddress,
13751 TemplateSpecCandidateSetKind CandidateSetKind) {
13753 DeductionFailure, /*NumArgs=*/0, ForTakingAddress,
13754 CandidateSetKind);
13755}
13756
13757void TemplateSpecCandidateSet::destroyCandidates() {
13758 for (iterator i = begin(), e = end(); i != e; ++i) {
13759 i->DeductionFailure.Destroy();
13760 }
13761}
13762
13764 destroyCandidates();
13765 Candidates.clear();
13766}
13767
13768/// NoteCandidates - When no template specialization match is found, prints
13769/// diagnostic messages containing the non-matching specializations that form
13770/// the candidate set.
13771/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13772/// OCD == OCD_AllCandidates and Cand->Viable == false.
13774 // Sort the candidates by position (assuming no candidate is a match).
13775 // Sorting directly would be prohibitive, so we make a set of pointers
13776 // and sort those.
13778 Cands.reserve(size());
13779 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13780 if (Cand->Specialization)
13781 Cands.push_back(Cand);
13782 // Otherwise, this is a non-matching builtin candidate. We do not,
13783 // in general, want to list every possible builtin candidate.
13784 }
13785
13786 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13787
13788 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13789 // for generalization purposes (?).
13790 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13791
13793 unsigned CandsShown = 0;
13794 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13795 TemplateSpecCandidate *Cand = *I;
13796
13797 // Set an arbitrary limit on the number of candidates we'll spam
13798 // the user with. FIXME: This limit should depend on details of the
13799 // candidate list.
13800 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13801 break;
13802 ++CandsShown;
13803
13804 assert(Cand->Specialization &&
13805 "Non-matching built-in candidates are not added to Cands.");
13806 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13807 }
13808
13809 if (I != E)
13810 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13811}
13812
13813// [PossiblyAFunctionType] --> [Return]
13814// NonFunctionType --> NonFunctionType
13815// R (A) --> R(A)
13816// R (*)(A) --> R (A)
13817// R (&)(A) --> R (A)
13818// R (S::*)(A) --> R (A)
13820 QualType Ret = PossiblyAFunctionType;
13821 if (const PointerType *ToTypePtr =
13822 PossiblyAFunctionType->getAs<PointerType>())
13823 Ret = ToTypePtr->getPointeeType();
13824 else if (const ReferenceType *ToTypeRef =
13825 PossiblyAFunctionType->getAs<ReferenceType>())
13826 Ret = ToTypeRef->getPointeeType();
13827 else if (const MemberPointerType *MemTypePtr =
13828 PossiblyAFunctionType->getAs<MemberPointerType>())
13829 Ret = MemTypePtr->getPointeeType();
13830 Ret =
13831 Context.getCanonicalType(Ret).getUnqualifiedType();
13832 return Ret;
13833}
13834
13836 bool Complain = true) {
13837 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13838 S.DeduceReturnType(FD, Loc, Complain))
13839 return true;
13840
13841 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13842 if (S.getLangOpts().CPlusPlus17 &&
13843 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13844 !S.ResolveExceptionSpec(Loc, FPT))
13845 return true;
13846
13847 return false;
13848}
13849
13850namespace {
13851// A helper class to help with address of function resolution
13852// - allows us to avoid passing around all those ugly parameters
13853class AddressOfFunctionResolver {
13854 Sema& S;
13855 Expr* SourceExpr;
13856 const QualType& TargetType;
13857 QualType TargetFunctionType; // Extracted function type from target type
13858
13859 bool Complain;
13860 //DeclAccessPair& ResultFunctionAccessPair;
13861 ASTContext& Context;
13862
13863 bool TargetTypeIsNonStaticMemberFunction;
13864 bool FoundNonTemplateFunction;
13865 bool StaticMemberFunctionFromBoundPointer;
13866 bool HasComplained;
13867
13868 OverloadExpr::FindResult OvlExprInfo;
13869 OverloadExpr *OvlExpr;
13870 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13871 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13872 TemplateSpecCandidateSet FailedCandidates;
13873
13874public:
13875 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13876 const QualType &TargetType, bool Complain)
13877 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13878 Complain(Complain), Context(S.getASTContext()),
13879 TargetTypeIsNonStaticMemberFunction(
13880 !!TargetType->getAs<MemberPointerType>()),
13881 FoundNonTemplateFunction(false),
13882 StaticMemberFunctionFromBoundPointer(false),
13883 HasComplained(false),
13884 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13885 OvlExpr(OvlExprInfo.Expression),
13886 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13887 ExtractUnqualifiedFunctionTypeFromTargetType();
13888
13889 if (TargetFunctionType->isFunctionType()) {
13890 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13891 if (!UME->isImplicitAccess() &&
13893 StaticMemberFunctionFromBoundPointer = true;
13894 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13895 DeclAccessPair dap;
13896 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13897 OvlExpr, false, &dap)) {
13898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13899 if (!Method->isStatic()) {
13900 // If the target type is a non-function type and the function found
13901 // is a non-static member function, pretend as if that was the
13902 // target, it's the only possible type to end up with.
13903 TargetTypeIsNonStaticMemberFunction = true;
13904
13905 // And skip adding the function if its not in the proper form.
13906 // We'll diagnose this due to an empty set of functions.
13907 if (!OvlExprInfo.HasFormOfMemberPointer)
13908 return;
13909 }
13910
13911 Matches.push_back(std::make_pair(dap, Fn));
13912 }
13913 return;
13914 }
13915
13916 if (OvlExpr->hasExplicitTemplateArgs())
13917 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13918
13919 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13920 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13921 EliminateSuboptimalCudaMatches();
13922
13923 // C++ [over.over]p4:
13924 // If more than one function is selected, [...]
13925 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13926 if (FoundNonTemplateFunction) {
13927 EliminateAllTemplateMatches();
13928 EliminateLessPartialOrderingConstrainedMatches();
13929 } else
13930 EliminateAllExceptMostSpecializedTemplate();
13931 }
13932 }
13933 }
13934
13935 bool hasComplained() const { return HasComplained; }
13936
13937private:
13938 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13939 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13940 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13941 }
13942
13943 /// \return true if A is considered a better overload candidate for the
13944 /// desired type than B.
13945 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13946 // If A doesn't have exactly the correct type, we don't want to classify it
13947 // as "better" than anything else. This way, the user is required to
13948 // disambiguate for us if there are multiple candidates and no exact match.
13949 return candidateHasExactlyCorrectType(A) &&
13950 (!candidateHasExactlyCorrectType(B) ||
13951 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13952 }
13953
13954 /// \return true if we were able to eliminate all but one overload candidate,
13955 /// false otherwise.
13956 bool eliminiateSuboptimalOverloadCandidates() {
13957 // Same algorithm as overload resolution -- one pass to pick the "best",
13958 // another pass to be sure that nothing is better than the best.
13959 auto Best = Matches.begin();
13960 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13961 if (isBetterCandidate(I->second, Best->second))
13962 Best = I;
13963
13964 const FunctionDecl *BestFn = Best->second;
13965 auto IsBestOrInferiorToBest = [this, BestFn](
13966 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13967 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13968 };
13969
13970 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13971 // option, so we can potentially give the user a better error
13972 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13973 return false;
13974 Matches[0] = *Best;
13975 Matches.resize(1);
13976 return true;
13977 }
13978
13979 bool isTargetTypeAFunction() const {
13980 return TargetFunctionType->isFunctionType();
13981 }
13982
13983 // [ToType] [Return]
13984
13985 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13986 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13987 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13988 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13989 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13990 }
13991
13992 // return true if any matching specializations were found
13993 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13994 const DeclAccessPair& CurAccessFunPair) {
13995 if (CXXMethodDecl *Method
13996 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13997 // Skip non-static function templates when converting to pointer, and
13998 // static when converting to member pointer.
13999 bool CanConvertToFunctionPointer =
14000 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14001 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14002 return false;
14003 }
14004 else if (TargetTypeIsNonStaticMemberFunction)
14005 return false;
14006
14007 // C++ [over.over]p2:
14008 // If the name is a function template, template argument deduction is
14009 // done (14.8.2.2), and if the argument deduction succeeds, the
14010 // resulting template argument list is used to generate a single
14011 // function template specialization, which is added to the set of
14012 // overloaded functions considered.
14013 FunctionDecl *Specialization = nullptr;
14014 TemplateDeductionInfo Info(FailedCandidates.getLocation());
14016 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
14017 Specialization, Info, /*IsAddressOfFunction*/ true);
14018 Result != TemplateDeductionResult::Success) {
14019 // Make a note of the failed deduction for diagnostics.
14020 FailedCandidates.addCandidate()
14021 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
14022 MakeDeductionFailureInfo(Context, Result, Info));
14023 return false;
14024 }
14025
14026 // Template argument deduction ensures that we have an exact match or
14027 // compatible pointer-to-function arguments that would be adjusted by ICS.
14028 // This function template specicalization works.
14030 Context.getCanonicalType(Specialization->getType()),
14031 Context.getCanonicalType(TargetFunctionType)));
14032
14034 return false;
14035
14036 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
14037 return true;
14038 }
14039
14040 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
14041 const DeclAccessPair& CurAccessFunPair) {
14042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14043 // Skip non-static functions when converting to pointer, and static
14044 // when converting to member pointer.
14045 bool CanConvertToFunctionPointer =
14046 Method->isStatic() || Method->isExplicitObjectMemberFunction();
14047 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
14048 return false;
14049 }
14050 else if (TargetTypeIsNonStaticMemberFunction)
14051 return false;
14052
14053 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
14054 if (S.getLangOpts().CUDA) {
14055 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
14056 if (!(Caller && Caller->isImplicit()) &&
14057 !S.CUDA().IsAllowedCall(Caller, FunDecl))
14058 return false;
14059 }
14060 if (FunDecl->isMultiVersion()) {
14061 const auto *TA = FunDecl->getAttr<TargetAttr>();
14062 if (TA && !TA->isDefaultVersion())
14063 return false;
14064 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
14065 if (TVA && !TVA->isDefaultVersion())
14066 return false;
14067 }
14068
14069 // If any candidate has a placeholder return type, trigger its deduction
14070 // now.
14071 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
14072 Complain)) {
14073 HasComplained |= Complain;
14074 return false;
14075 }
14076
14077 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
14078 return false;
14079
14080 // If we're in C, we need to support types that aren't exactly identical.
14081 if (!S.getLangOpts().CPlusPlus ||
14082 candidateHasExactlyCorrectType(FunDecl)) {
14083 Matches.push_back(std::make_pair(
14084 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
14085 FoundNonTemplateFunction = true;
14086 return true;
14087 }
14088 }
14089
14090 return false;
14091 }
14092
14093 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14094 bool Ret = false;
14095
14096 // If the overload expression doesn't have the form of a pointer to
14097 // member, don't try to convert it to a pointer-to-member type.
14098 if (IsInvalidFormOfPointerToMemberFunction())
14099 return false;
14100
14101 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14102 E = OvlExpr->decls_end();
14103 I != E; ++I) {
14104 // Look through any using declarations to find the underlying function.
14105 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14106
14107 // C++ [over.over]p3:
14108 // Non-member functions and static member functions match
14109 // targets of type "pointer-to-function" or "reference-to-function."
14110 // Nonstatic member functions match targets of
14111 // type "pointer-to-member-function."
14112 // Note that according to DR 247, the containing class does not matter.
14113 if (FunctionTemplateDecl *FunctionTemplate
14114 = dyn_cast<FunctionTemplateDecl>(Fn)) {
14115 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
14116 Ret = true;
14117 }
14118 // If we have explicit template arguments supplied, skip non-templates.
14119 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14120 AddMatchingNonTemplateFunction(Fn, I.getPair()))
14121 Ret = true;
14122 }
14123 assert(Ret || Matches.empty());
14124 return Ret;
14125 }
14126
14127 void EliminateAllExceptMostSpecializedTemplate() {
14128 // [...] and any given function template specialization F1 is
14129 // eliminated if the set contains a second function template
14130 // specialization whose function template is more specialized
14131 // than the function template of F1 according to the partial
14132 // ordering rules of 14.5.5.2.
14133
14134 // The algorithm specified above is quadratic. We instead use a
14135 // two-pass algorithm (similar to the one used to identify the
14136 // best viable function in an overload set) that identifies the
14137 // best function template (if it exists).
14138
14139 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14140 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14141 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14142
14143 // TODO: It looks like FailedCandidates does not serve much purpose
14144 // here, since the no_viable diagnostic has index 0.
14145 UnresolvedSetIterator Result = S.getMostSpecialized(
14146 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14147 SourceExpr->getBeginLoc(), S.PDiag(),
14148 S.PDiag(diag::err_addr_ovl_ambiguous)
14149 << Matches[0].second->getDeclName(),
14150 S.PDiag(diag::note_ovl_candidate)
14151 << (unsigned)oc_function << (unsigned)ocs_described_template,
14152 Complain, TargetFunctionType);
14153
14154 if (Result != MatchesCopy.end()) {
14155 // Make it the first and only element
14156 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14157 Matches[0].second = cast<FunctionDecl>(*Result);
14158 Matches.resize(1);
14159 } else
14160 HasComplained |= Complain;
14161 }
14162
14163 void EliminateAllTemplateMatches() {
14164 // [...] any function template specializations in the set are
14165 // eliminated if the set also contains a non-template function, [...]
14166 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14167 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14168 ++I;
14169 else {
14170 Matches[I] = Matches[--N];
14171 Matches.resize(N);
14172 }
14173 }
14174 }
14175
14176 void EliminateLessPartialOrderingConstrainedMatches() {
14177 // C++ [over.over]p5:
14178 // [...] Any given non-template function F0 is eliminated if the set
14179 // contains a second non-template function that is more
14180 // partial-ordering-constrained than F0. [...]
14181 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14182 "Call EliminateAllTemplateMatches() first");
14183 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14184 Results.push_back(Matches[0]);
14185 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14186 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14187 FunctionDecl *F = getMorePartialOrderingConstrained(
14188 S, Matches[I].second, Results[0].second,
14189 /*IsFn1Reversed=*/false,
14190 /*IsFn2Reversed=*/false);
14191 if (!F) {
14192 Results.push_back(Matches[I]);
14193 continue;
14194 }
14195 if (F == Matches[I].second) {
14196 Results.clear();
14197 Results.push_back(Matches[I]);
14198 }
14199 }
14200 std::swap(Matches, Results);
14201 }
14202
14203 void EliminateSuboptimalCudaMatches() {
14204 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14205 Matches);
14206 }
14207
14208public:
14209 void ComplainNoMatchesFound() const {
14210 assert(Matches.empty());
14211 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14212 << OvlExpr->getName() << TargetFunctionType
14213 << OvlExpr->getSourceRange();
14214 if (FailedCandidates.empty())
14215 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14216 /*TakingAddress=*/true);
14217 else {
14218 // We have some deduction failure messages. Use them to diagnose
14219 // the function templates, and diagnose the non-template candidates
14220 // normally.
14221 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14222 IEnd = OvlExpr->decls_end();
14223 I != IEnd; ++I)
14224 if (FunctionDecl *Fun =
14225 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14227 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14228 /*TakingAddress=*/true);
14229 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14230 }
14231 }
14232
14233 bool IsInvalidFormOfPointerToMemberFunction() const {
14234 return TargetTypeIsNonStaticMemberFunction &&
14235 !OvlExprInfo.HasFormOfMemberPointer;
14236 }
14237
14238 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14239 // TODO: Should we condition this on whether any functions might
14240 // have matched, or is it more appropriate to do that in callers?
14241 // TODO: a fixit wouldn't hurt.
14242 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14243 << TargetType << OvlExpr->getSourceRange();
14244 }
14245
14246 bool IsStaticMemberFunctionFromBoundPointer() const {
14247 return StaticMemberFunctionFromBoundPointer;
14248 }
14249
14250 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14251 S.Diag(OvlExpr->getBeginLoc(),
14252 diag::err_invalid_form_pointer_member_function)
14253 << OvlExpr->getSourceRange();
14254 }
14255
14256 void ComplainOfInvalidConversion() const {
14257 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14258 << OvlExpr->getName() << TargetType;
14259 }
14260
14261 void ComplainMultipleMatchesFound() const {
14262 assert(Matches.size() > 1);
14263 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14264 << OvlExpr->getName() << OvlExpr->getSourceRange();
14265 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14266 /*TakingAddress=*/true);
14267 }
14268
14269 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14270
14271 int getNumMatches() const { return Matches.size(); }
14272
14273 FunctionDecl* getMatchingFunctionDecl() const {
14274 if (Matches.size() != 1) return nullptr;
14275 return Matches[0].second;
14276 }
14277
14278 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14279 if (Matches.size() != 1) return nullptr;
14280 return &Matches[0].first;
14281 }
14282};
14283}
14284
14285FunctionDecl *
14287 QualType TargetType,
14288 bool Complain,
14289 DeclAccessPair &FoundResult,
14290 bool *pHadMultipleCandidates) {
14291 assert(AddressOfExpr->getType() == Context.OverloadTy);
14292
14293 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14294 Complain);
14295 int NumMatches = Resolver.getNumMatches();
14296 FunctionDecl *Fn = nullptr;
14297 bool ShouldComplain = Complain && !Resolver.hasComplained();
14298 if (NumMatches == 0 && ShouldComplain) {
14299 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14300 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14301 else
14302 Resolver.ComplainNoMatchesFound();
14303 }
14304 else if (NumMatches > 1 && ShouldComplain)
14305 Resolver.ComplainMultipleMatchesFound();
14306 else if (NumMatches == 1) {
14307 Fn = Resolver.getMatchingFunctionDecl();
14308 assert(Fn);
14309 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14310 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14311 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14312 if (Complain) {
14313 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14314 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14315 else
14316 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14317 }
14318 }
14319
14320 if (pHadMultipleCandidates)
14321 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14322 return Fn;
14323}
14324
14328 OverloadExpr *Ovl = R.Expression;
14329 bool IsResultAmbiguous = false;
14330 FunctionDecl *Result = nullptr;
14331 DeclAccessPair DAP;
14332 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14333
14334 // Return positive for better, negative for worse, 0 for equal preference.
14335 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14336 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14337 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14338 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14339 };
14340
14341 // Don't use the AddressOfResolver because we're specifically looking for
14342 // cases where we have one overload candidate that lacks
14343 // enable_if/pass_object_size/...
14344 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14345 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14346 if (!FD)
14347 return nullptr;
14348
14350 continue;
14351
14352 // If we found a better result, update Result.
14353 auto FoundBetter = [&]() {
14354 IsResultAmbiguous = false;
14355 DAP = I.getPair();
14356 Result = FD;
14357 };
14358
14359 // We have more than one result - see if it is more
14360 // partial-ordering-constrained than the previous one.
14361 if (Result) {
14362 // Check CUDA preference first. If the candidates have differennt CUDA
14363 // preference, choose the one with higher CUDA preference. Otherwise,
14364 // choose the one with more constraints.
14365 if (getLangOpts().CUDA) {
14366 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14367 // FD has different preference than Result.
14368 if (PreferenceByCUDA != 0) {
14369 // FD is more preferable than Result.
14370 if (PreferenceByCUDA > 0)
14371 FoundBetter();
14372 continue;
14373 }
14374 }
14375 // FD has the same CUDA preference than Result. Continue to check
14376 // constraints.
14377
14378 // C++ [over.over]p5:
14379 // [...] If more than one function in the set remains, all function
14380 // template specializations in the set are eliminated if the set also
14381 // contains a function that is not a function template specialization.
14382 // [...]
14383 if (Result->isFunctionTemplateSpecialization() !=
14386 FoundBetter();
14387 continue;
14388 }
14389
14390 // C++ [over.over]p5:
14391 // [...] Any given non-template function F0 is eliminated if the set
14392 // contains a second non-template function that is more
14393 // partial-ordering-constrained than F0 [...]
14394 FunctionDecl *MoreConstrained =
14396 /*IsFn1Reversed=*/false,
14397 /*IsFn2Reversed=*/false);
14398 if (MoreConstrained != FD) {
14399 if (!MoreConstrained) {
14400 IsResultAmbiguous = true;
14401 AmbiguousDecls.push_back(FD);
14402 }
14403 continue;
14404 }
14405 // FD is more constrained - replace Result with it.
14406 }
14407 FoundBetter();
14408 }
14409
14410 if (IsResultAmbiguous)
14411 return nullptr;
14412
14413 if (Result) {
14414 // We skipped over some ambiguous declarations which might be ambiguous with
14415 // the selected result.
14416 for (FunctionDecl *Skipped : AmbiguousDecls) {
14417 // If skipped candidate has different CUDA preference than the result,
14418 // there is no ambiguity. Otherwise check whether they have different
14419 // constraints.
14420 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14421 continue;
14422 if (!getMoreConstrainedFunction(Skipped, Result))
14423 return nullptr;
14424 }
14425 Pair = DAP;
14426 }
14427 return Result;
14428}
14429
14431 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14432 Expr *E = SrcExpr.get();
14433 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14434
14435 DeclAccessPair DAP;
14437 if (!Found || Found->isCPUDispatchMultiVersion() ||
14438 Found->isCPUSpecificMultiVersion())
14439 return false;
14440
14441 // Emitting multiple diagnostics for a function that is both inaccessible and
14442 // unavailable is consistent with our behavior elsewhere. So, always check
14443 // for both.
14447 if (Res.isInvalid())
14448 return false;
14449 Expr *Fixed = Res.get();
14450 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14451 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14452 else
14453 SrcExpr = Fixed;
14454 return true;
14455}
14456
14458 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14459 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14460 // C++ [over.over]p1:
14461 // [...] [Note: any redundant set of parentheses surrounding the
14462 // overloaded function name is ignored (5.1). ]
14463 // C++ [over.over]p1:
14464 // [...] The overloaded function name can be preceded by the &
14465 // operator.
14466
14467 // If we didn't actually find any template-ids, we're done.
14468 if (!ovl->hasExplicitTemplateArgs())
14469 return nullptr;
14470
14471 TemplateArgumentListInfo ExplicitTemplateArgs;
14472 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14473
14474 // Look through all of the overloaded functions, searching for one
14475 // whose type matches exactly.
14476 FunctionDecl *Matched = nullptr;
14477 for (UnresolvedSetIterator I = ovl->decls_begin(),
14478 E = ovl->decls_end(); I != E; ++I) {
14479 // C++0x [temp.arg.explicit]p3:
14480 // [...] In contexts where deduction is done and fails, or in contexts
14481 // where deduction is not done, if a template argument list is
14482 // specified and it, along with any default template arguments,
14483 // identifies a single function template specialization, then the
14484 // template-id is an lvalue for the function template specialization.
14486 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14487 if (!FunctionTemplate)
14488 continue;
14489
14490 // C++ [over.over]p2:
14491 // If the name is a function template, template argument deduction is
14492 // done (14.8.2.2), and if the argument deduction succeeds, the
14493 // resulting template argument list is used to generate a single
14494 // function template specialization, which is added to the set of
14495 // overloaded functions considered.
14496 FunctionDecl *Specialization = nullptr;
14497 TemplateDeductionInfo Info(ovl->getNameLoc());
14499 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14500 /*IsAddressOfFunction*/ true);
14502 // Make a note of the failed deduction for diagnostics.
14503 if (FailedTSC)
14504 FailedTSC->addCandidate().set(
14505 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14507 continue;
14508 }
14509
14510 assert(Specialization && "no specialization and no error?");
14511
14512 // C++ [temp.deduct.call]p6:
14513 // [...] If all successful deductions yield the same deduced A, that
14514 // deduced A is the result of deduction; otherwise, the parameter is
14515 // treated as a non-deduced context.
14516 if (Matched) {
14517 if (ForTypeDeduction &&
14519 Specialization->getType()))
14520 continue;
14521 // Multiple matches; we can't resolve to a single declaration.
14522 if (Complain) {
14523 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14524 << ovl->getName();
14526 }
14527 return nullptr;
14528 }
14529
14530 Matched = Specialization;
14531 if (FoundResult) *FoundResult = I.getPair();
14532 }
14533
14534 if (Matched &&
14535 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14536 return nullptr;
14537
14538 return Matched;
14539}
14540
14542 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14543 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14544 unsigned DiagIDForComplaining) {
14545 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14546
14548
14549 DeclAccessPair found;
14550 ExprResult SingleFunctionExpression;
14552 ovl.Expression, /*complain*/ false, &found)) {
14553 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14554 SrcExpr = ExprError();
14555 return true;
14556 }
14557
14558 // It is only correct to resolve to an instance method if we're
14559 // resolving a form that's permitted to be a pointer to member.
14560 // Otherwise we'll end up making a bound member expression, which
14561 // is illegal in all the contexts we resolve like this.
14562 if (!ovl.HasFormOfMemberPointer &&
14563 isa<CXXMethodDecl>(fn) &&
14564 cast<CXXMethodDecl>(fn)->isInstance()) {
14565 if (!complain) return false;
14566
14567 Diag(ovl.Expression->getExprLoc(),
14568 diag::err_bound_member_function)
14569 << 0 << ovl.Expression->getSourceRange();
14570
14571 // TODO: I believe we only end up here if there's a mix of
14572 // static and non-static candidates (otherwise the expression
14573 // would have 'bound member' type, not 'overload' type).
14574 // Ideally we would note which candidate was chosen and why
14575 // the static candidates were rejected.
14576 SrcExpr = ExprError();
14577 return true;
14578 }
14579
14580 // Fix the expression to refer to 'fn'.
14581 SingleFunctionExpression =
14582 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14583
14584 // If desired, do function-to-pointer decay.
14585 if (doFunctionPointerConversion) {
14586 SingleFunctionExpression =
14587 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14588 if (SingleFunctionExpression.isInvalid()) {
14589 SrcExpr = ExprError();
14590 return true;
14591 }
14592 }
14593 }
14594
14595 if (!SingleFunctionExpression.isUsable()) {
14596 if (complain) {
14597 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14598 << ovl.Expression->getName()
14599 << DestTypeForComplaining
14600 << OpRangeForComplaining
14602 NoteAllOverloadCandidates(SrcExpr.get());
14603
14604 SrcExpr = ExprError();
14605 return true;
14606 }
14607
14608 return false;
14609 }
14610
14611 SrcExpr = SingleFunctionExpression;
14612 return true;
14613}
14614
14615/// Add a single candidate to the overload set.
14617 DeclAccessPair FoundDecl,
14618 TemplateArgumentListInfo *ExplicitTemplateArgs,
14619 ArrayRef<Expr *> Args,
14620 OverloadCandidateSet &CandidateSet,
14621 bool PartialOverloading,
14622 bool KnownValid) {
14623 NamedDecl *Callee = FoundDecl.getDecl();
14624 if (isa<UsingShadowDecl>(Callee))
14625 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14626
14627 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14628 if (ExplicitTemplateArgs) {
14629 assert(!KnownValid && "Explicit template arguments?");
14630 return;
14631 }
14632 // Prevent ill-formed function decls to be added as overload candidates.
14633 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14634 return;
14635
14636 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14637 /*SuppressUserConversions=*/false,
14638 PartialOverloading);
14639 return;
14640 }
14641
14642 if (FunctionTemplateDecl *FuncTemplate
14643 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14644 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14645 ExplicitTemplateArgs, Args, CandidateSet,
14646 /*SuppressUserConversions=*/false,
14647 PartialOverloading);
14648 return;
14649 }
14650
14651 assert(!KnownValid && "unhandled case in overloaded call candidate");
14652}
14653
14655 ArrayRef<Expr *> Args,
14656 OverloadCandidateSet &CandidateSet,
14657 bool PartialOverloading) {
14658
14659#ifndef NDEBUG
14660 // Verify that ArgumentDependentLookup is consistent with the rules
14661 // in C++0x [basic.lookup.argdep]p3:
14662 //
14663 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14664 // and let Y be the lookup set produced by argument dependent
14665 // lookup (defined as follows). If X contains
14666 //
14667 // -- a declaration of a class member, or
14668 //
14669 // -- a block-scope function declaration that is not a
14670 // using-declaration, or
14671 //
14672 // -- a declaration that is neither a function or a function
14673 // template
14674 //
14675 // then Y is empty.
14676
14677 if (ULE->requiresADL()) {
14679 E = ULE->decls_end(); I != E; ++I) {
14680 assert(!(*I)->getDeclContext()->isRecord());
14681 assert(isa<UsingShadowDecl>(*I) ||
14682 !(*I)->getDeclContext()->isFunctionOrMethod());
14683 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14684 }
14685 }
14686#endif
14687
14688 // It would be nice to avoid this copy.
14689 TemplateArgumentListInfo TABuffer;
14690 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14691 if (ULE->hasExplicitTemplateArgs()) {
14692 ULE->copyTemplateArgumentsInto(TABuffer);
14693 ExplicitTemplateArgs = &TABuffer;
14694 }
14695
14697 E = ULE->decls_end(); I != E; ++I)
14698 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14699 CandidateSet, PartialOverloading,
14700 /*KnownValid*/ true);
14701
14702 if (ULE->requiresADL())
14704 Args, ExplicitTemplateArgs,
14705 CandidateSet, PartialOverloading);
14706}
14707
14709 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14710 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14711 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14712 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14713 CandidateSet, false, /*KnownValid*/ false);
14714}
14715
14716/// Determine whether a declaration with the specified name could be moved into
14717/// a different namespace.
14719 switch (Name.getCXXOverloadedOperator()) {
14720 case OO_New: case OO_Array_New:
14721 case OO_Delete: case OO_Array_Delete:
14722 return false;
14723
14724 default:
14725 return true;
14726 }
14727}
14728
14729/// Attempt to recover from an ill-formed use of a non-dependent name in a
14730/// template, where the non-dependent name was declared after the template
14731/// was defined. This is common in code written for compilers which do not
14732/// correctly implement two-stage name lookup.
14733///
14734/// Returns true if a viable candidate was found and a diagnostic was issued.
14736 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14738 const OverloadCandidateSet &ResolvedCandidates,
14739 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14740 CXXRecordDecl **FoundInClass = nullptr) {
14741 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14742 return false;
14743
14744 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14745 if (DC->isTransparentContext())
14746 continue;
14747
14748 SemaRef.LookupQualifiedName(R, DC);
14749
14750 if (!R.empty()) {
14751 R.suppressDiagnostics();
14752
14753 OverloadCandidateSet Candidates(FnLoc, CSK);
14754 // We have performed a BestViableFunction over these candidates, so
14755 // exclude them.
14756 for (auto &Cand : ResolvedCandidates) {
14757 if (Cand.Function)
14758 Candidates.exclude(Cand.Function);
14759 else if (Cand.IsSurrogate)
14760 Candidates.exclude(Cand.Surrogate);
14761 }
14762 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14763 Candidates);
14764
14767 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14768
14769 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14770 // We either found non-function declarations or a best viable function
14771 // at class scope. A class-scope lookup result disables ADL. Don't
14772 // look past this, but let the caller know that we found something that
14773 // either is, or might be, usable in this class.
14774 if (FoundInClass) {
14775 *FoundInClass = RD;
14776 if (OR == OR_Success) {
14777 R.clear();
14778 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14779 R.resolveKind();
14780 }
14781 }
14782 return false;
14783 }
14784
14785 if (OR != OR_Success) {
14786 // There wasn't a unique best function or function template.
14787 return false;
14788 }
14789
14790 // Find the namespaces where ADL would have looked, and suggest
14791 // declaring the function there instead.
14792 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14793 Sema::AssociatedClassSet AssociatedClasses;
14794 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14795 AssociatedNamespaces,
14796 AssociatedClasses);
14797 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14798 if (canBeDeclaredInNamespace(R.getLookupName())) {
14799 DeclContext *Std = SemaRef.getStdNamespace();
14800 for (Sema::AssociatedNamespaceSet::iterator
14801 it = AssociatedNamespaces.begin(),
14802 end = AssociatedNamespaces.end(); it != end; ++it) {
14803 // Never suggest declaring a function within namespace 'std'.
14804 if (Std && Std->Encloses(*it))
14805 continue;
14806
14807 // Never suggest declaring a function within a namespace with a
14808 // reserved name, like __gnu_cxx.
14809 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14810 if (NS &&
14811 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14812 continue;
14813
14814 SuggestedNamespaces.insert(*it);
14815 }
14816 }
14817
14818 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14819 << R.getLookupName();
14820 if (SuggestedNamespaces.empty()) {
14821 SemaRef.Diag(Best->Function->getLocation(),
14822 diag::note_not_found_by_two_phase_lookup)
14823 << R.getLookupName() << 0;
14824 } else if (SuggestedNamespaces.size() == 1) {
14825 SemaRef.Diag(Best->Function->getLocation(),
14826 diag::note_not_found_by_two_phase_lookup)
14827 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14828 } else {
14829 // FIXME: It would be useful to list the associated namespaces here,
14830 // but the diagnostics infrastructure doesn't provide a way to produce
14831 // a localized representation of a list of items.
14832 SemaRef.Diag(Best->Function->getLocation(),
14833 diag::note_not_found_by_two_phase_lookup)
14834 << R.getLookupName() << 2;
14835 }
14836
14837 // Try to recover by calling this function.
14838 return true;
14839 }
14840
14841 R.clear();
14842 }
14843
14844 return false;
14845}
14846
14847/// Attempt to recover from ill-formed use of a non-dependent operator in a
14848/// template, where the non-dependent operator was declared after the template
14849/// was defined.
14850///
14851/// Returns true if a viable candidate was found and a diagnostic was issued.
14853 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14854 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14855 DeclarationName OpName =
14857 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14860 ResolvedCandidateSet,
14861 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14862}
14863
14864namespace {
14865class BuildRecoveryCallExprRAII {
14866 Sema &SemaRef;
14867 Sema::SatisfactionStackResetRAII SatStack;
14868
14869public:
14870 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14871 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14872 SemaRef.IsBuildingRecoveryCallExpr = true;
14873 }
14874
14875 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14876};
14877}
14878
14879/// Attempts to recover from a call where no functions were found.
14880///
14881/// This function will do one of three things:
14882/// * Diagnose, recover, and return a recovery expression.
14883/// * Diagnose, fail to recover, and return ExprError().
14884/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14885/// expected to diagnose as appropriate.
14886static ExprResult
14888 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14890 const OverloadCandidateSet &ResolvedCandidateSet,
14891 bool AllowTypoCorrection) {
14892 // Do not try to recover if it is already building a recovery call.
14893 // This stops infinite loops for template instantiations like
14894 //
14895 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14896 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14897 if (SemaRef.IsBuildingRecoveryCallExpr)
14898 return ExprResult();
14899 BuildRecoveryCallExprRAII RCE(SemaRef);
14900
14901 CXXScopeSpec SS;
14902 SS.Adopt(ULE->getQualifierLoc());
14903 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14904
14905 TemplateArgumentListInfo TABuffer;
14906 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14907 if (ULE->hasExplicitTemplateArgs()) {
14908 ULE->copyTemplateArgumentsInto(TABuffer);
14909 ExplicitTemplateArgs = &TABuffer;
14910 }
14911
14912 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14914 CXXRecordDecl *FoundInClass = nullptr;
14916 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
14917 ResolvedCandidateSet, ExplicitTemplateArgs, Args, &FoundInClass)) {
14918 // OK, diagnosed a two-phase lookup issue.
14919 } else if (ResolvedCandidateSet.empty()) {
14920 // Try to recover from an empty lookup with typo correction.
14921 R.clear();
14922 NoTypoCorrectionCCC NoTypoValidator{};
14923 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14924 ExplicitTemplateArgs != nullptr,
14925 dyn_cast<MemberExpr>(Fn));
14926 CorrectionCandidateCallback &Validator =
14927 AllowTypoCorrection
14928 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14929 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14930 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14931 Args))
14932 return ExprError();
14933 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14934 // We found a usable declaration of the name in a dependent base of some
14935 // enclosing class.
14936 // FIXME: We should also explain why the candidates found by name lookup
14937 // were not viable.
14938 if (SemaRef.DiagnoseDependentMemberLookup(R))
14939 return ExprError();
14940 } else {
14941 // We had viable candidates and couldn't recover; let the caller diagnose
14942 // this.
14943 return ExprResult();
14944 }
14945
14946 // If we get here, we should have issued a diagnostic and formed a recovery
14947 // lookup result.
14948 assert(!R.empty() && "lookup results empty despite recovery");
14949
14950 // If recovery created an ambiguity, just bail out.
14951 if (R.isAmbiguous()) {
14952 R.suppressDiagnostics();
14953 return ExprError();
14954 }
14955
14956 // Build an implicit member call if appropriate. Just drop the
14957 // casts and such from the call, we don't really care.
14958 ExprResult NewFn = ExprError();
14959 if ((*R.begin())->isCXXClassMember())
14960 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14961 ExplicitTemplateArgs, S);
14962 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14963 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14964 ExplicitTemplateArgs);
14965 else
14966 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14967
14968 if (NewFn.isInvalid())
14969 return ExprError();
14970
14971 // This shouldn't cause an infinite loop because we're giving it
14972 // an expression with viable lookup results, which should never
14973 // end up here.
14974 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14975 MultiExprArg(Args.data(), Args.size()),
14976 RParenLoc);
14977}
14978
14981 MultiExprArg Args,
14982 SourceLocation RParenLoc,
14983 OverloadCandidateSet *CandidateSet,
14984 ExprResult *Result) {
14985#ifndef NDEBUG
14986 if (ULE->requiresADL()) {
14987 // To do ADL, we must have found an unqualified name.
14988 assert(!ULE->getQualifier() && "qualified name with ADL");
14989
14990 // We don't perform ADL for implicit declarations of builtins.
14991 // Verify that this was correctly set up.
14992 FunctionDecl *F;
14993 if (ULE->decls_begin() != ULE->decls_end() &&
14994 ULE->decls_begin() + 1 == ULE->decls_end() &&
14995 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14996 F->getBuiltinID() && F->isImplicit())
14997 llvm_unreachable("performing ADL for builtin");
14998
14999 // We don't perform ADL in C.
15000 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
15001 }
15002#endif
15003
15004 UnbridgedCastsSet UnbridgedCasts;
15005 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15006 *Result = ExprError();
15007 return true;
15008 }
15009
15010 // Add the functions denoted by the callee to the set of candidate
15011 // functions, including those from argument-dependent lookup.
15012 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
15013
15014 if (getLangOpts().MSVCCompat &&
15015 CurContext->isDependentContext() && !isSFINAEContext() &&
15017
15019 if (CandidateSet->empty() ||
15020 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
15022 // In Microsoft mode, if we are inside a template class member function
15023 // then create a type dependent CallExpr. The goal is to postpone name
15024 // lookup to instantiation time to be able to search into type dependent
15025 // base classes.
15026 CallExpr *CE =
15027 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
15028 RParenLoc, CurFPFeatureOverrides());
15030 *Result = CE;
15031 return true;
15032 }
15033 }
15034
15035 if (CandidateSet->empty())
15036 return false;
15037
15038 UnbridgedCasts.restore();
15039 return false;
15040}
15041
15042// Guess at what the return type for an unresolvable overload should be.
15045 std::optional<QualType> Result;
15046 // Adjust Type after seeing a candidate.
15047 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
15048 if (!Candidate.Function)
15049 return;
15050 if (Candidate.Function->isInvalidDecl())
15051 return;
15052 QualType T = Candidate.Function->getReturnType();
15053 if (T.isNull())
15054 return;
15055 if (!Result)
15056 Result = T;
15057 else if (Result != T)
15058 Result = QualType();
15059 };
15060
15061 // Look for an unambiguous type from a progressively larger subset.
15062 // e.g. if types disagree, but all *viable* overloads return int, choose int.
15063 //
15064 // First, consider only the best candidate.
15065 if (Best && *Best != CS.end())
15066 ConsiderCandidate(**Best);
15067 // Next, consider only viable candidates.
15068 if (!Result)
15069 for (const auto &C : CS)
15070 if (C.Viable)
15071 ConsiderCandidate(C);
15072 // Finally, consider all candidates.
15073 if (!Result)
15074 for (const auto &C : CS)
15075 ConsiderCandidate(C);
15076
15077 if (!Result)
15078 return QualType();
15079 auto Value = *Result;
15080 if (Value.isNull() || Value->isUndeducedType())
15081 return QualType();
15082 return Value;
15083}
15084
15085/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
15086/// the completed call expression. If overload resolution fails, emits
15087/// diagnostics and returns ExprError()
15090 SourceLocation LParenLoc,
15091 MultiExprArg Args,
15092 SourceLocation RParenLoc,
15093 Expr *ExecConfig,
15094 OverloadCandidateSet *CandidateSet,
15096 OverloadingResult OverloadResult,
15097 bool AllowTypoCorrection) {
15098 switch (OverloadResult) {
15099 case OR_Success: {
15100 FunctionDecl *FDecl = (*Best)->Function;
15101 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
15102 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
15103 return ExprError();
15104 ExprResult Res =
15105 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15106 if (Res.isInvalid())
15107 return ExprError();
15108 return SemaRef.BuildResolvedCallExpr(
15109 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15110 /*IsExecConfig=*/false,
15111 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15112 }
15113
15114 case OR_No_Viable_Function: {
15115 if (*Best != CandidateSet->end() &&
15116 CandidateSet->getKind() ==
15118 if (CXXMethodDecl *M =
15119 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
15121 CandidateSet->NoteCandidates(
15123 Fn->getBeginLoc(),
15124 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
15125 SemaRef, OCD_AmbiguousCandidates, Args);
15126 return ExprError();
15127 }
15128 }
15129
15130 // Try to recover by looking for viable functions which the user might
15131 // have meant to call.
15132 ExprResult Recovery =
15133 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15134 *CandidateSet, AllowTypoCorrection);
15135 if (Recovery.isInvalid() || Recovery.isUsable())
15136 return Recovery;
15137
15138 // If the user passes in a function that we can't take the address of, we
15139 // generally end up emitting really bad error messages. Here, we attempt to
15140 // emit better ones.
15141 for (const Expr *Arg : Args) {
15142 if (!Arg->getType()->isFunctionType())
15143 continue;
15144 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
15145 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15146 if (FD &&
15147 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15148 Arg->getExprLoc()))
15149 return ExprError();
15150 }
15151 }
15152
15153 CandidateSet->NoteCandidates(
15155 Fn->getBeginLoc(),
15156 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15157 << ULE->getName() << Fn->getSourceRange()),
15158 SemaRef, OCD_AllCandidates, Args);
15159 break;
15160 }
15161
15162 case OR_Ambiguous:
15163 CandidateSet->NoteCandidates(
15164 PartialDiagnosticAt(Fn->getBeginLoc(),
15165 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15166 << ULE->getName() << Fn->getSourceRange()),
15167 SemaRef, OCD_AmbiguousCandidates, Args);
15168 break;
15169
15170 case OR_Deleted: {
15171 FunctionDecl *FDecl = (*Best)->Function;
15172 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15173 Fn->getSourceRange(), ULE->getName(),
15174 *CandidateSet, FDecl, Args);
15175
15176 // We emitted an error for the unavailable/deleted function call but keep
15177 // the call in the AST.
15178 ExprResult Res =
15179 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15180 if (Res.isInvalid())
15181 return ExprError();
15182 return SemaRef.BuildResolvedCallExpr(
15183 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15184 /*IsExecConfig=*/false,
15185 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15186 }
15187 }
15188
15189 // Overload resolution failed, try to recover.
15190 SmallVector<Expr *, 8> SubExprs = {Fn};
15191 SubExprs.append(Args.begin(), Args.end());
15192 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15193 chooseRecoveryType(*CandidateSet, Best));
15194}
15195
15198 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15199 if (I->Viable &&
15200 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15201 I->Viable = false;
15202 I->FailureKind = ovl_fail_addr_not_available;
15203 }
15204 }
15205}
15206
15209 SourceLocation LParenLoc,
15210 MultiExprArg Args,
15211 SourceLocation RParenLoc,
15212 Expr *ExecConfig,
15213 bool AllowTypoCorrection,
15214 bool CalleesAddressIsTaken) {
15215
15219
15220 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15221 ExprResult result;
15222
15223 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15224 &result))
15225 return result;
15226
15227 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15228 // functions that aren't addressible are considered unviable.
15229 if (CalleesAddressIsTaken)
15230 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15231
15233 OverloadingResult OverloadResult =
15234 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15235
15236 // [C++23][over.call.func]
15237 // if overload resolution selects a non-static member function,
15238 // the call is ill-formed;
15240 Best != CandidateSet.end()) {
15241 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15242 M && M->isImplicitObjectMemberFunction()) {
15243 OverloadResult = OR_No_Viable_Function;
15244 }
15245 }
15246
15247 // Model the case with a call to a templated function whose definition
15248 // encloses the call and whose return type contains a placeholder type as if
15249 // the UnresolvedLookupExpr was type-dependent.
15250 if (OverloadResult == OR_Success) {
15251 const FunctionDecl *FDecl = Best->Function;
15252 if (LangOpts.CUDA)
15253 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15254 if (FDecl && FDecl->isTemplateInstantiation() &&
15255 FDecl->getReturnType()->isUndeducedType()) {
15256
15257 // Creating dependent CallExpr is not okay if the enclosing context itself
15258 // is not dependent. This situation notably arises if a non-dependent
15259 // member function calls the later-defined overloaded static function.
15260 //
15261 // For example, in
15262 // class A {
15263 // void c() { callee(1); }
15264 // static auto callee(auto x) { }
15265 // };
15266 //
15267 // Here callee(1) is unresolved at the call site, but is not inside a
15268 // dependent context. There will be no further attempt to resolve this
15269 // call if it is made dependent.
15270
15271 if (const auto *TP =
15272 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15273 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15274 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15275 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15276 }
15277 }
15278 }
15279
15280 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15281 ExecConfig, &CandidateSet, &Best,
15282 OverloadResult, AllowTypoCorrection);
15283}
15284
15288 const UnresolvedSetImpl &Fns,
15289 bool PerformADL) {
15291 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15292 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15293}
15294
15297 bool HadMultipleCandidates) {
15298 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15299 // the FoundDecl as it impedes TransformMemberExpr.
15300 // We go a bit further here: if there's no difference in UnderlyingDecl,
15301 // then using FoundDecl vs Method shouldn't make a difference either.
15302 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15303 FoundDecl = Method;
15304 // Convert the expression to match the conversion function's implicit object
15305 // parameter.
15306 ExprResult Exp;
15307 if (Method->isExplicitObjectMemberFunction())
15309 else
15311 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15312 if (Exp.isInvalid())
15313 return true;
15314
15315 if (Method->getParent()->isLambda() &&
15316 Method->getConversionType()->isBlockPointerType()) {
15317 // This is a lambda conversion to block pointer; check if the argument
15318 // was a LambdaExpr.
15319 Expr *SubE = E;
15320 auto *CE = dyn_cast<CastExpr>(SubE);
15321 if (CE && CE->getCastKind() == CK_NoOp)
15322 SubE = CE->getSubExpr();
15323 SubE = SubE->IgnoreParens();
15324 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15325 SubE = BE->getSubExpr();
15326 if (isa<LambdaExpr>(SubE)) {
15327 // For the conversion to block pointer on a lambda expression, we
15328 // construct a special BlockLiteral instead; this doesn't really make
15329 // a difference in ARC, but outside of ARC the resulting block literal
15330 // follows the normal lifetime rules for block literals instead of being
15331 // autoreleased.
15335 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15337
15338 // FIXME: This note should be produced by a CodeSynthesisContext.
15339 if (BlockExp.isInvalid())
15340 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15341 return BlockExp;
15342 }
15343 }
15344 CallExpr *CE;
15345 QualType ResultType = Method->getReturnType();
15347 ResultType = ResultType.getNonLValueExprType(Context);
15348 if (Method->isExplicitObjectMemberFunction()) {
15349 ExprResult FnExpr =
15350 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15351 HadMultipleCandidates, E->getBeginLoc());
15352 if (FnExpr.isInvalid())
15353 return ExprError();
15354 Expr *ObjectParam = Exp.get();
15355 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15356 ResultType, VK, Exp.get()->getEndLoc(),
15358 CE->setUsesMemberSyntax(true);
15359 } else {
15360 MemberExpr *ME =
15361 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15363 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15364 HadMultipleCandidates, DeclarationNameInfo(),
15365 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15366
15367 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15368 Exp.get()->getEndLoc(),
15370 }
15371
15372 if (CheckFunctionCall(Method, CE,
15373 Method->getType()->castAs<FunctionProtoType>()))
15374 return ExprError();
15375
15377}
15378
15381 const UnresolvedSetImpl &Fns,
15382 ArrayRef<Expr *> Args, bool PerformADL) {
15383 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15384
15385 SourceLocation OpLoc = CandidateSet.getLocation();
15386 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15387
15388 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15389 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15390 if (PerformADL)
15391 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15392 /*ExplicitTemplateArgs*/ nullptr,
15393 CandidateSet);
15394 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15395}
15396
15399 const UnresolvedSetImpl &Fns,
15400 Expr *Input, bool PerformADL) {
15402 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15403 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15404 // TODO: provide better source location info.
15405 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15406
15407 if (checkPlaceholderForOverload(*this, Input))
15408 return ExprError();
15409
15410 Expr *Args[2] = { Input, nullptr };
15411 unsigned NumArgs = 1;
15412
15413 // For post-increment and post-decrement, add the implicit '0' as
15414 // the second argument, so that we know this is a post-increment or
15415 // post-decrement.
15416 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15417 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15418 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15419 SourceLocation());
15420 NumArgs = 2;
15421 }
15422
15423 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15424
15425 if (Input->isTypeDependent()) {
15427 // [C++26][expr.unary.op][expr.pre.incr]
15428 // The * operator yields an lvalue of type
15429 // The pre/post increment operators yied an lvalue.
15430 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15431 VK = VK_LValue;
15432
15433 if (Fns.empty())
15434 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15435 OK_Ordinary, OpLoc, false,
15437
15438 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15440 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15441 if (Fn.isInvalid())
15442 return ExprError();
15443 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15444 Context.DependentTy, VK_PRValue, OpLoc,
15446 }
15447
15448 // Build an empty overload set.
15450 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15451
15452 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15453
15454 // Perform overload resolution.
15456 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15457 case OR_Success: {
15458 // We found a built-in operator or an overloaded operator.
15459 FunctionDecl *FnDecl = Best->Function;
15460
15461 if (FnDecl) {
15462 Expr *Base = nullptr;
15463 // We matched an overloaded operator. Build a call to that
15464 // operator.
15465
15466 // Convert the arguments.
15467 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15468 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15469
15470 ExprResult InputInit;
15471 if (Method->isExplicitObjectMemberFunction())
15472 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15473 else
15475 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15476 if (InputInit.isInvalid())
15477 return ExprError();
15478 Base = Input = InputInit.get();
15479 } else {
15480 // Convert the arguments.
15481 ExprResult InputInit
15483 Context,
15484 FnDecl->getParamDecl(0)),
15486 Input);
15487 if (InputInit.isInvalid())
15488 return ExprError();
15489 Input = InputInit.get();
15490 }
15491
15492 // Build the actual expression node.
15493 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15494 Base, HadMultipleCandidates,
15495 OpLoc);
15496 if (FnExpr.isInvalid())
15497 return ExprError();
15498
15499 // Determine the result type.
15500 QualType ResultTy = FnDecl->getReturnType();
15502 ResultTy = ResultTy.getNonLValueExprType(Context);
15503
15504 Args[0] = Input;
15506 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15508 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15509
15510 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15511 return ExprError();
15512
15513 if (CheckFunctionCall(FnDecl, TheCall,
15514 FnDecl->getType()->castAs<FunctionProtoType>()))
15515 return ExprError();
15516 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15517 } else {
15518 // We matched a built-in operator. Convert the arguments, then
15519 // break out so that we will build the appropriate built-in
15520 // operator node.
15522 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15525 if (InputRes.isInvalid())
15526 return ExprError();
15527 Input = InputRes.get();
15528 break;
15529 }
15530 }
15531
15533 // This is an erroneous use of an operator which can be overloaded by
15534 // a non-member function. Check for non-member operators which were
15535 // defined too late to be candidates.
15536 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray,
15537 CandidateSet))
15538 // FIXME: Recover by calling the found function.
15539 return ExprError();
15540
15541 // No viable function; fall through to handling this as a
15542 // built-in operator, which will produce an error message for us.
15543 break;
15544
15545 case OR_Ambiguous:
15546 CandidateSet.NoteCandidates(
15547 PartialDiagnosticAt(OpLoc,
15548 PDiag(diag::err_ovl_ambiguous_oper_unary)
15550 << Input->getType() << Input->getSourceRange()),
15551 *this, OCD_AmbiguousCandidates, ArgsArray,
15552 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15553 return ExprError();
15554
15555 case OR_Deleted: {
15556 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15557 // object whose method was called. Later in NoteCandidates size of ArgsArray
15558 // is passed further and it eventually ends up compared to number of
15559 // function candidate parameters which never includes the object parameter,
15560 // so slice ArgsArray to make sure apples are compared to apples.
15561 StringLiteral *Msg = Best->Function->getDeletedMessage();
15562 CandidateSet.NoteCandidates(
15563 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15565 << (Msg != nullptr)
15566 << (Msg ? Msg->getString() : StringRef())
15567 << Input->getSourceRange()),
15568 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15569 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15570 return ExprError();
15571 }
15572 }
15573
15574 // Either we found no viable overloaded operator or we matched a
15575 // built-in operator. In either case, fall through to trying to
15576 // build a built-in operation.
15577 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15578}
15579
15582 const UnresolvedSetImpl &Fns,
15583 ArrayRef<Expr *> Args, bool PerformADL) {
15584 SourceLocation OpLoc = CandidateSet.getLocation();
15585
15586 OverloadedOperatorKind ExtraOp =
15589 : OO_None;
15590
15591 // Add the candidates from the given function set. This also adds the
15592 // rewritten candidates using these functions if necessary.
15593 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15594
15595 // As template candidates are not deduced immediately,
15596 // persist the array in the overload set.
15597 ArrayRef<Expr *> ReversedArgs;
15598 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15599 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15600 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15601
15602 // Add operator candidates that are member functions.
15603 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15604 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15605 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15607
15608 // In C++20, also add any rewritten member candidates.
15609 if (ExtraOp) {
15610 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15611 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15612 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15614 }
15615
15616 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15617 // performed for an assignment operator (nor for operator[] nor operator->,
15618 // which don't get here).
15619 if (Op != OO_Equal && PerformADL) {
15620 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15621 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15622 /*ExplicitTemplateArgs*/ nullptr,
15623 CandidateSet);
15624 if (ExtraOp) {
15625 DeclarationName ExtraOpName =
15626 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15627 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15628 /*ExplicitTemplateArgs*/ nullptr,
15629 CandidateSet);
15630 }
15631 }
15632
15633 // Add builtin operator candidates.
15634 //
15635 // FIXME: We don't add any rewritten candidates here. This is strictly
15636 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15637 // resulting in our selecting a rewritten builtin candidate. For example:
15638 //
15639 // enum class E { e };
15640 // bool operator!=(E, E) requires false;
15641 // bool k = E::e != E::e;
15642 //
15643 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15644 // it seems unreasonable to consider rewritten builtin candidates. A core
15645 // issue has been filed proposing to removed this requirement.
15646 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15647}
15648
15651 const UnresolvedSetImpl &Fns, Expr *LHS,
15652 Expr *RHS, bool PerformADL,
15653 bool AllowRewrittenCandidates,
15654 FunctionDecl *DefaultedFn) {
15655 Expr *Args[2] = { LHS, RHS };
15656 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15657
15658 if (!getLangOpts().CPlusPlus20)
15659 AllowRewrittenCandidates = false;
15660
15662
15663 // If either side is type-dependent, create an appropriate dependent
15664 // expression.
15665 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15666 if (Fns.empty()) {
15667 // If there are no functions to store, just build a dependent
15668 // BinaryOperator or CompoundAssignment.
15671 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15672 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15673 Context.DependentTy);
15675 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15677 }
15678
15679 // FIXME: save results of ADL from here?
15680 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15681 // TODO: provide better source location info in DNLoc component.
15682 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15683 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15685 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15686 if (Fn.isInvalid())
15687 return ExprError();
15688 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15689 Context.DependentTy, VK_PRValue, OpLoc,
15691 }
15692
15693 // If this is the .* operator, which is not overloadable, just
15694 // create a built-in binary operator.
15695 if (Opc == BO_PtrMemD) {
15696 auto CheckPlaceholder = [&](Expr *&Arg) {
15698 if (Res.isUsable())
15699 Arg = Res.get();
15700 return !Res.isUsable();
15701 };
15702
15703 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15704 // expression that contains placeholders (in either the LHS or RHS).
15705 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15706 return ExprError();
15707 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15708 }
15709
15710 // Always do placeholder-like conversions on the RHS.
15711 if (checkPlaceholderForOverload(*this, Args[1]))
15712 return ExprError();
15713
15714 // Do placeholder-like conversion on the LHS; note that we should
15715 // not get here with a PseudoObject LHS.
15716 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15717 if (checkPlaceholderForOverload(*this, Args[0]))
15718 return ExprError();
15719
15720 // If this is the assignment operator, we only perform overload resolution
15721 // if the left-hand side is a class or enumeration type. This is actually
15722 // a hack. The standard requires that we do overload resolution between the
15723 // various built-in candidates, but as DR507 points out, this can lead to
15724 // problems. So we do it this way, which pretty much follows what GCC does.
15725 // Note that we go the traditional code path for compound assignment forms.
15726 // In HLSL, user-defined structs/classes do not have constructors or
15727 // overloadable assignment operators, so we can take this shortcut too.
15728 const Type *LHSTy = Args[0]->getType().getTypePtr();
15729 if (Opc == BO_Assign &&
15730 (!LHSTy->isOverloadableType() ||
15731 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15733 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15734
15735 // Build the overload set.
15738 Op, OpLoc, AllowRewrittenCandidates));
15739 if (DefaultedFn)
15740 CandidateSet.exclude(DefaultedFn);
15741 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15742
15743 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15744
15745 // Perform overload resolution.
15747 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15748 case OR_Success: {
15749 // We found a built-in operator or an overloaded operator.
15750 FunctionDecl *FnDecl = Best->Function;
15751
15752 bool IsReversed = Best->isReversed();
15753 if (IsReversed)
15754 std::swap(Args[0], Args[1]);
15755
15756 if (FnDecl) {
15757
15758 if (FnDecl->isInvalidDecl())
15759 return ExprError();
15760
15761 Expr *Base = nullptr;
15762 // We matched an overloaded operator. Build a call to that
15763 // operator.
15764
15765 OverloadedOperatorKind ChosenOp =
15767
15768 // C++2a [over.match.oper]p9:
15769 // If a rewritten operator== candidate is selected by overload
15770 // resolution for an operator@, its return type shall be cv bool
15771 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15772 !FnDecl->getReturnType()->isBooleanType()) {
15773 bool IsExtension =
15775 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15776 : diag::err_ovl_rewrite_equalequal_not_bool)
15777 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15778 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15779 Diag(FnDecl->getLocation(), diag::note_declared_at);
15780 if (!IsExtension)
15781 return ExprError();
15782 }
15783
15784 if (AllowRewrittenCandidates && !IsReversed &&
15785 CandidateSet.getRewriteInfo().isReversible()) {
15786 // We could have reversed this operator, but didn't. Check if some
15787 // reversed form was a viable candidate, and if so, if it had a
15788 // better conversion for either parameter. If so, this call is
15789 // formally ambiguous, and allowing it is an extension.
15791 for (OverloadCandidate &Cand : CandidateSet) {
15792 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15793 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15794 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15796 *this, OpLoc, Cand.Conversions[ArgIdx],
15797 Best->Conversions[ArgIdx]) ==
15799 AmbiguousWith.push_back(Cand.Function);
15800 break;
15801 }
15802 }
15803 }
15804 }
15805
15806 if (!AmbiguousWith.empty()) {
15807 bool AmbiguousWithSelf =
15808 AmbiguousWith.size() == 1 &&
15809 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15810 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15812 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15813 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15814 if (AmbiguousWithSelf) {
15815 Diag(FnDecl->getLocation(),
15816 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15817 // Mark member== const or provide matching != to disallow reversed
15818 // args. Eg.
15819 // struct S { bool operator==(const S&); };
15820 // S()==S();
15821 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15822 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15823 !MD->isConst() &&
15824 !MD->hasCXXExplicitFunctionObjectParameter() &&
15825 Context.hasSameUnqualifiedType(
15826 MD->getFunctionObjectParameterType(),
15827 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15828 Context.hasSameUnqualifiedType(
15829 MD->getFunctionObjectParameterType(),
15830 Args[0]->getType()) &&
15831 Context.hasSameUnqualifiedType(
15832 MD->getFunctionObjectParameterType(),
15833 Args[1]->getType()))
15834 Diag(FnDecl->getLocation(),
15835 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15836 } else {
15837 Diag(FnDecl->getLocation(),
15838 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15839 for (auto *F : AmbiguousWith)
15840 Diag(F->getLocation(),
15841 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15842 }
15843 }
15844 }
15845
15846 // Check for nonnull = nullable.
15847 // This won't be caught in the arg's initialization: the parameter to
15848 // the assignment operator is not marked nonnull.
15849 if (Op == OO_Equal)
15851 Args[1]->getType(), OpLoc);
15852
15853 // Convert the arguments.
15854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15855 // Best->Access is only meaningful for class members.
15856 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15857
15858 ExprResult Arg0, Arg1;
15859 unsigned ParamIdx = 0;
15860 if (Method->isExplicitObjectMemberFunction()) {
15861 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15862 ParamIdx = 1;
15863 } else {
15865 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15866 }
15869 Context, FnDecl->getParamDecl(ParamIdx)),
15870 SourceLocation(), Args[1]);
15871 if (Arg0.isInvalid() || Arg1.isInvalid())
15872 return ExprError();
15873
15874 Base = Args[0] = Arg0.getAs<Expr>();
15875 Args[1] = RHS = Arg1.getAs<Expr>();
15876 } else {
15877 // Convert the arguments.
15880 FnDecl->getParamDecl(0)),
15881 SourceLocation(), Args[0]);
15882 if (Arg0.isInvalid())
15883 return ExprError();
15884
15885 ExprResult Arg1 =
15888 FnDecl->getParamDecl(1)),
15889 SourceLocation(), Args[1]);
15890 if (Arg1.isInvalid())
15891 return ExprError();
15892 Args[0] = LHS = Arg0.getAs<Expr>();
15893 Args[1] = RHS = Arg1.getAs<Expr>();
15894 }
15895
15896 // Build the actual expression node.
15897 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15898 Best->FoundDecl, Base,
15899 HadMultipleCandidates, OpLoc);
15900 if (FnExpr.isInvalid())
15901 return ExprError();
15902
15903 if (auto *Pattern = FnDecl->getInstantiatedFromMemberFunction();
15904 Pattern && Pattern->getOverloadedOperator() == OO_Spaceship)
15905 Pattern->setIsUsed();
15906
15907 // Determine the result type.
15908 QualType ResultTy = FnDecl->getReturnType();
15910 ResultTy = ResultTy.getNonLValueExprType(Context);
15911
15912 CallExpr *TheCall;
15913 ArrayRef<const Expr *> ArgsArray(Args, 2);
15914 const Expr *ImplicitThis = nullptr;
15915
15916 // We always create a CXXOperatorCallExpr, even for explicit object
15917 // members; CodeGen should take care not to emit the this pointer.
15919 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15921 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15922 IsReversed);
15923
15924 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15925 Method && Method->isImplicitObjectMemberFunction()) {
15926 // Cut off the implicit 'this'.
15927 ImplicitThis = ArgsArray[0];
15928 ArgsArray = ArgsArray.slice(1);
15929 }
15930
15931 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15932 FnDecl))
15933 return ExprError();
15934
15935 if (Op == OO_Equal) {
15936 // Check for a self move.
15937 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15938 // lifetime check.
15940 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15941 Args[1]);
15942 }
15943 if (ImplicitThis) {
15944 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15945 QualType ThisTypeFromDecl = Context.getPointerType(
15946 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15947
15948 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15949 ThisTypeFromDecl);
15950 }
15951
15952 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15953 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15955
15956 ExprResult R = MaybeBindToTemporary(TheCall);
15957 if (R.isInvalid())
15958 return ExprError();
15959
15960 R = CheckForImmediateInvocation(R, FnDecl);
15961 if (R.isInvalid())
15962 return ExprError();
15963
15964 // For a rewritten candidate, we've already reversed the arguments
15965 // if needed. Perform the rest of the rewrite now.
15966 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15967 (Op == OO_Spaceship && IsReversed)) {
15968 if (Op == OO_ExclaimEqual) {
15969 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15970 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15971 } else {
15972 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15973 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15974 Expr *ZeroLiteral =
15976
15979 Ctx.Entity = FnDecl;
15981
15983 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15984 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15985 /*AllowRewrittenCandidates=*/false);
15986
15988 }
15989 if (R.isInvalid())
15990 return ExprError();
15991 } else {
15992 assert(ChosenOp == Op && "unexpected operator name");
15993 }
15994
15995 // Make a note in the AST if we did any rewriting.
15996 if (Best->RewriteKind != CRK_None)
15997 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15998
15999 return R;
16000 } else {
16001 // We matched a built-in operator. Convert the arguments, then
16002 // break out so that we will build the appropriate built-in
16003 // operator node.
16005 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16008 if (ArgsRes0.isInvalid())
16009 return ExprError();
16010 Args[0] = ArgsRes0.get();
16011
16013 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16016 if (ArgsRes1.isInvalid())
16017 return ExprError();
16018 Args[1] = ArgsRes1.get();
16019 break;
16020 }
16021 }
16022
16023 case OR_No_Viable_Function: {
16024 // C++ [over.match.oper]p9:
16025 // If the operator is the operator , [...] and there are no
16026 // viable functions, then the operator is assumed to be the
16027 // built-in operator and interpreted according to clause 5.
16028 if (Opc == BO_Comma)
16029 break;
16030
16031 // When defaulting an 'operator<=>', we can try to synthesize a three-way
16032 // compare result using '==' and '<'.
16033 if (DefaultedFn && Opc == BO_Cmp) {
16034 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
16035 Args[1], DefaultedFn);
16036 if (E.isInvalid() || E.isUsable())
16037 return E;
16038 }
16039
16040 // For class as left operand for assignment or compound assignment
16041 // operator do not fall through to handling in built-in, but report that
16042 // no overloaded assignment operator found
16044 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
16045 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
16046 Args, OpLoc);
16047 DeferDiagsRAII DDR(*this,
16048 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
16049 if (Args[0]->getType()->isRecordType() &&
16050 Opc >= BO_Assign && Opc <= BO_OrAssign) {
16051 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16053 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16054 if (Args[0]->getType()->isIncompleteType()) {
16055 Diag(OpLoc, diag::note_assign_lhs_incomplete)
16056 << Args[0]->getType()
16057 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
16058 }
16059 } else {
16060 // This is an erroneous use of an operator which can be overloaded by
16061 // a non-member function. Check for non-member operators which were
16062 // defined too late to be candidates.
16063 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args,
16064 CandidateSet))
16065 // FIXME: Recover by calling the found function.
16066 return ExprError();
16067
16068 // No viable function; try to create a built-in operation, which will
16069 // produce an error. Then, show the non-viable candidates.
16070 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16071 }
16072 assert(Result.isInvalid() &&
16073 "C++ binary operator overloading is missing candidates!");
16074 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
16075 return Result;
16076 }
16077
16078 case OR_Ambiguous:
16079 CandidateSet.NoteCandidates(
16080 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16082 << Args[0]->getType()
16083 << Args[1]->getType()
16084 << Args[0]->getSourceRange()
16085 << Args[1]->getSourceRange()),
16087 OpLoc);
16088 return ExprError();
16089
16090 case OR_Deleted: {
16091 if (isImplicitlyDeleted(Best->Function)) {
16092 FunctionDecl *DeletedFD = Best->Function;
16094 DeletedFD->getDefaultedFunctionKind();
16095 if (DFK.isSpecialMember()) {
16096 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
16097 << Args[0]->getType() << DFK.asSpecialMember();
16098 } else {
16099 assert(DFK.isComparison());
16100 Diag(OpLoc, diag::err_ovl_deleted_comparison)
16101 << Args[0]->getType() << DeletedFD;
16102 }
16103
16104 // The user probably meant to call this special member. Just
16105 // explain why it's deleted.
16106 NoteDeletedFunction(DeletedFD);
16107 return ExprError();
16108 }
16109
16110 StringLiteral *Msg = Best->Function->getDeletedMessage();
16111 CandidateSet.NoteCandidates(
16113 OpLoc,
16114 PDiag(diag::err_ovl_deleted_oper)
16115 << getOperatorSpelling(Best->Function->getDeclName()
16116 .getCXXOverloadedOperator())
16117 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16118 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16120 OpLoc);
16121 return ExprError();
16122 }
16123 }
16124
16125 // We matched a built-in operator; build it.
16126 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16127}
16128
16130 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16131 FunctionDecl *DefaultedFn) {
16132 const ComparisonCategoryInfo *Info =
16133 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
16134 // If we're not producing a known comparison category type, we can't
16135 // synthesize a three-way comparison. Let the caller diagnose this.
16136 if (!Info)
16137 return ExprResult((Expr*)nullptr);
16138
16139 // If we ever want to perform this synthesis more generally, we will need to
16140 // apply the temporary materialization conversion to the operands.
16141 assert(LHS->isGLValue() && RHS->isGLValue() &&
16142 "cannot use prvalue expressions more than once");
16143 Expr *OrigLHS = LHS;
16144 Expr *OrigRHS = RHS;
16145
16146 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16147 // each of them multiple times below.
16148 LHS = new (Context)
16149 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16150 LHS->getObjectKind(), LHS);
16151 RHS = new (Context)
16152 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16153 RHS->getObjectKind(), RHS);
16154
16155 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16156 DefaultedFn);
16157 if (Eq.isInvalid())
16158 return ExprError();
16159
16160 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16161 true, DefaultedFn);
16162 if (Less.isInvalid())
16163 return ExprError();
16164
16166 if (Info->isPartial()) {
16167 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16168 DefaultedFn);
16169 if (Greater.isInvalid())
16170 return ExprError();
16171 }
16172
16173 // Form the list of comparisons we're going to perform.
16174 struct Comparison {
16177 } Comparisons[4] =
16183 };
16184
16185 int I = Info->isPartial() ? 3 : 2;
16186
16187 // Combine the comparisons with suitable conditional expressions.
16189 for (; I >= 0; --I) {
16190 // Build a reference to the comparison category constant.
16191 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16192 // FIXME: Missing a constant for a comparison category. Diagnose this?
16193 if (!VI)
16194 return ExprResult((Expr*)nullptr);
16195 ExprResult ThisResult =
16197 if (ThisResult.isInvalid())
16198 return ExprError();
16199
16200 // Build a conditional unless this is the final case.
16201 if (Result.get()) {
16202 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16203 ThisResult.get(), Result.get());
16204 if (Result.isInvalid())
16205 return ExprError();
16206 } else {
16207 Result = ThisResult;
16208 }
16209 }
16210
16211 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16212 // bind the OpaqueValueExprs before they're (repeatedly) used.
16213 Expr *SyntacticForm = BinaryOperator::Create(
16214 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16215 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16217 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16218 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16219}
16220
16222 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16223 MultiExprArg Args, SourceLocation LParenLoc) {
16224
16225 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16226 unsigned NumParams = Proto->getNumParams();
16227 unsigned NumArgsSlots =
16228 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16229 // Build the full argument list for the method call (the implicit object
16230 // parameter is placed at the beginning of the list).
16231 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16232 bool IsError = false;
16233 // Initialize the implicit object parameter.
16234 // Check the argument types.
16235 for (unsigned i = 0; i != NumParams; i++) {
16236 Expr *Arg;
16237 if (i < Args.size()) {
16238 Arg = Args[i];
16239 ExprResult InputInit =
16241 S.Context, Method->getParamDecl(i)),
16242 SourceLocation(), Arg);
16243 IsError |= InputInit.isInvalid();
16244 Arg = InputInit.getAs<Expr>();
16245 } else {
16246 ExprResult DefArg =
16247 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16248 if (DefArg.isInvalid()) {
16249 IsError = true;
16250 break;
16251 }
16252 Arg = DefArg.getAs<Expr>();
16253 }
16254
16255 MethodArgs.push_back(Arg);
16256 }
16257 return IsError;
16258}
16259
16261 SourceLocation RLoc,
16262 Expr *Base,
16263 MultiExprArg ArgExpr) {
16265 Args.push_back(Base);
16266 for (auto *e : ArgExpr) {
16267 Args.push_back(e);
16268 }
16269 DeclarationName OpName =
16270 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16271
16272 SourceRange Range = ArgExpr.empty()
16273 ? SourceRange{}
16274 : SourceRange(ArgExpr.front()->getBeginLoc(),
16275 ArgExpr.back()->getEndLoc());
16276
16277 // If either side is type-dependent, create an appropriate dependent
16278 // expression.
16280
16281 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16282 // CHECKME: no 'operator' keyword?
16283 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16284 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16286 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16287 if (Fn.isInvalid())
16288 return ExprError();
16289 // Can't add any actual overloads yet
16290
16291 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16292 Context.DependentTy, VK_PRValue, RLoc,
16294 }
16295
16296 // Handle placeholders
16297 UnbridgedCastsSet UnbridgedCasts;
16298 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16299 return ExprError();
16300 }
16301 // Build an empty overload set.
16303
16304 // Subscript can only be overloaded as a member function.
16305
16306 // Add operator candidates that are member functions.
16307 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16308
16309 // Add builtin operator candidates.
16310 if (Args.size() == 2)
16311 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16312
16313 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16314
16315 // Perform overload resolution.
16317 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16318 case OR_Success: {
16319 // We found a built-in operator or an overloaded operator.
16320 FunctionDecl *FnDecl = Best->Function;
16321
16322 if (FnDecl) {
16323 // We matched an overloaded operator. Build a call to that
16324 // operator.
16325
16326 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16327
16328 // Convert the arguments.
16330 SmallVector<Expr *, 2> MethodArgs;
16331
16332 // Initialize the object parameter.
16333 if (Method->isExplicitObjectMemberFunction()) {
16334 ExprResult Res =
16336 if (Res.isInvalid())
16337 return ExprError();
16338 Args[0] = Res.get();
16339 ArgExpr = Args;
16340 } else {
16342 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16343 if (Arg0.isInvalid())
16344 return ExprError();
16345
16346 MethodArgs.push_back(Arg0.get());
16347 }
16348
16350 *this, MethodArgs, Method, ArgExpr, LLoc);
16351 if (IsError)
16352 return ExprError();
16353
16354 // Build the actual expression node.
16355 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16356 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16357 ExprResult FnExpr =
16358 CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, Base,
16359 HadMultipleCandidates, OpLocInfo);
16360 if (FnExpr.isInvalid())
16361 return ExprError();
16362
16363 // Determine the result type
16364 QualType ResultTy = FnDecl->getReturnType();
16366 ResultTy = ResultTy.getNonLValueExprType(Context);
16367
16369 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16371
16372 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16373 return ExprError();
16374
16375 if (CheckFunctionCall(Method, TheCall,
16376 Method->getType()->castAs<FunctionProtoType>()))
16377 return ExprError();
16378
16380 FnDecl);
16381 } else {
16382 // We matched a built-in operator. Convert the arguments, then
16383 // break out so that we will build the appropriate built-in
16384 // operator node.
16386 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16389 if (ArgsRes0.isInvalid())
16390 return ExprError();
16391 Args[0] = ArgsRes0.get();
16392
16394 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16397 if (ArgsRes1.isInvalid())
16398 return ExprError();
16399 Args[1] = ArgsRes1.get();
16400
16401 break;
16402 }
16403 }
16404
16405 case OR_No_Viable_Function: {
16407 CandidateSet.empty()
16408 ? (PDiag(diag::err_ovl_no_oper)
16409 << Args[0]->getType() << /*subscript*/ 0
16410 << Args[0]->getSourceRange() << Range)
16411 : (PDiag(diag::err_ovl_no_viable_subscript)
16412 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16413 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16414 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16415 return ExprError();
16416 }
16417
16418 case OR_Ambiguous:
16419 if (Args.size() == 2) {
16420 CandidateSet.NoteCandidates(
16422 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16423 << "[]" << Args[0]->getType() << Args[1]->getType()
16424 << Args[0]->getSourceRange() << Range),
16425 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16426 } else {
16427 CandidateSet.NoteCandidates(
16429 PDiag(diag::err_ovl_ambiguous_subscript_call)
16430 << Args[0]->getType()
16431 << Args[0]->getSourceRange() << Range),
16432 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16433 }
16434 return ExprError();
16435
16436 case OR_Deleted: {
16437 StringLiteral *Msg = Best->Function->getDeletedMessage();
16438 CandidateSet.NoteCandidates(
16440 PDiag(diag::err_ovl_deleted_oper)
16441 << "[]" << (Msg != nullptr)
16442 << (Msg ? Msg->getString() : StringRef())
16443 << Args[0]->getSourceRange() << Range),
16444 *this, OCD_AllCandidates, Args, "[]", LLoc);
16445 return ExprError();
16446 }
16447 }
16448
16449 // We matched a built-in operator; build it.
16450 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16451}
16452
16454 SourceLocation LParenLoc,
16455 MultiExprArg Args,
16456 SourceLocation RParenLoc,
16457 Expr *ExecConfig, bool IsExecConfig,
16458 bool AllowRecovery) {
16459 assert(MemExprE->getType() == Context.BoundMemberTy ||
16460 MemExprE->getType() == Context.OverloadTy);
16461
16462 // Dig out the member expression. This holds both the object
16463 // argument and the member function we're referring to.
16464 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16465
16466 // Determine whether this is a call to a pointer-to-member function.
16467 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16468 assert(op->getType() == Context.BoundMemberTy);
16469 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16470
16471 QualType fnType =
16472 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16473
16474 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16475 QualType resultType = proto->getCallResultType(Context);
16477
16478 // Check that the object type isn't more qualified than the
16479 // member function we're calling.
16480 Qualifiers funcQuals = proto->getMethodQuals();
16481
16482 QualType objectType = op->getLHS()->getType();
16483 if (op->getOpcode() == BO_PtrMemI)
16484 objectType = objectType->castAs<PointerType>()->getPointeeType();
16485 Qualifiers objectQuals = objectType.getQualifiers();
16486
16487 Qualifiers difference = objectQuals - funcQuals;
16488 difference.removeObjCGCAttr();
16489 difference.removeAddressSpace();
16490 if (difference) {
16491 std::string qualsString = difference.getAsString();
16492 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16493 << fnType.getUnqualifiedType()
16494 << qualsString
16495 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16496 }
16497
16499 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16501
16502 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16503 call, nullptr))
16504 return ExprError();
16505
16506 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16507 return ExprError();
16508
16509 if (CheckOtherCall(call, proto))
16510 return ExprError();
16511
16512 return MaybeBindToTemporary(call);
16513 }
16514
16515 // We only try to build a recovery expr at this level if we can preserve
16516 // the return type, otherwise we return ExprError() and let the caller
16517 // recover.
16518 auto BuildRecoveryExpr = [&](QualType Type) {
16519 if (!AllowRecovery)
16520 return ExprError();
16521 std::vector<Expr *> SubExprs = {MemExprE};
16522 llvm::append_range(SubExprs, Args);
16523 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16524 Type);
16525 };
16526 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16527 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16528 RParenLoc, CurFPFeatureOverrides());
16529
16530 UnbridgedCastsSet UnbridgedCasts;
16531 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16532 return ExprError();
16533
16534 MemberExpr *MemExpr;
16535 CXXMethodDecl *Method = nullptr;
16536 bool HadMultipleCandidates = false;
16537 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16538 NestedNameSpecifier Qualifier = std::nullopt;
16539 if (isa<MemberExpr>(NakedMemExpr)) {
16540 MemExpr = cast<MemberExpr>(NakedMemExpr);
16542 FoundDecl = MemExpr->getFoundDecl();
16543 Qualifier = MemExpr->getQualifier();
16544 UnbridgedCasts.restore();
16545 } else {
16546 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16547 Qualifier = UnresExpr->getQualifier();
16548
16549 QualType ObjectType = UnresExpr->getBaseType();
16550 Expr::Classification ObjectClassification
16552 : UnresExpr->getBase()->Classify(Context);
16553
16554 // Add overload candidates
16555 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16557
16558 // FIXME: avoid copy.
16559 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16560 if (UnresExpr->hasExplicitTemplateArgs()) {
16561 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16562 TemplateArgs = &TemplateArgsBuffer;
16563 }
16564
16566 E = UnresExpr->decls_end(); I != E; ++I) {
16567
16568 QualType ExplicitObjectType = ObjectType;
16569
16570 NamedDecl *Func = *I;
16571 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16573 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16574
16575 bool HasExplicitParameter = false;
16576 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16577 M && M->hasCXXExplicitFunctionObjectParameter())
16578 HasExplicitParameter = true;
16579 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16580 M &&
16581 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16582 HasExplicitParameter = true;
16583
16584 if (HasExplicitParameter)
16585 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16586
16587 // Microsoft supports direct constructor calls.
16588 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16590 CandidateSet,
16591 /*SuppressUserConversions*/ false);
16592 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16593 // If explicit template arguments were provided, we can't call a
16594 // non-template member function.
16595 if (TemplateArgs)
16596 continue;
16597
16598 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16599 ObjectClassification, Args, CandidateSet,
16600 /*SuppressUserConversions=*/false);
16601 } else {
16603 I.getPair(), ActingDC, TemplateArgs,
16604 ExplicitObjectType, ObjectClassification,
16605 Args, CandidateSet,
16606 /*SuppressUserConversions=*/false);
16607 }
16608 }
16609
16610 HadMultipleCandidates = (CandidateSet.size() > 1);
16611
16612 DeclarationName DeclName = UnresExpr->getMemberName();
16613
16614 UnbridgedCasts.restore();
16615
16617 bool Succeeded = false;
16618 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16619 Best)) {
16620 case OR_Success:
16621 Method = cast<CXXMethodDecl>(Best->Function);
16622 FoundDecl = Best->FoundDecl;
16623 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16624 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16625 break;
16626 // If FoundDecl is different from Method (such as if one is a template
16627 // and the other a specialization), make sure DiagnoseUseOfDecl is
16628 // called on both.
16629 // FIXME: This would be more comprehensively addressed by modifying
16630 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16631 // being used.
16632 if (Method != FoundDecl.getDecl() &&
16634 break;
16635 Succeeded = true;
16636 break;
16637
16639 CandidateSet.NoteCandidates(
16641 UnresExpr->getMemberLoc(),
16642 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16643 << DeclName << MemExprE->getSourceRange()),
16644 *this, OCD_AllCandidates, Args);
16645 break;
16646 case OR_Ambiguous:
16647 CandidateSet.NoteCandidates(
16648 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16649 PDiag(diag::err_ovl_ambiguous_member_call)
16650 << DeclName << MemExprE->getSourceRange()),
16651 *this, OCD_AmbiguousCandidates, Args);
16652 break;
16653 case OR_Deleted:
16655 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16656 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16657 break;
16658 }
16659 // Overload resolution fails, try to recover.
16660 if (!Succeeded)
16661 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16662
16663 ExprResult Res =
16664 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16665 if (Res.isInvalid())
16666 return ExprError();
16667 MemExprE = Res.get();
16668
16669 // If overload resolution picked a static member
16670 // build a non-member call based on that function.
16671 if (Method->isStatic()) {
16672 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16673 ExecConfig, IsExecConfig);
16674 }
16675
16676 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16677 }
16678
16679 QualType ResultType = Method->getReturnType();
16681 ResultType = ResultType.getNonLValueExprType(Context);
16682
16683 assert(Method && "Member call to something that isn't a method?");
16684 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16685
16686 CallExpr *TheCall = nullptr;
16688 if (Method->isExplicitObjectMemberFunction()) {
16689 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16690 NewArgs))
16691 return ExprError();
16692
16693 // FIXME: avoid copy.
16694 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16695 if (MemExpr->hasExplicitTemplateArgs()) {
16696 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16697 TemplateArgs = &TemplateArgsBuffer;
16698 }
16699
16700 // Build the actual expression node.
16702 *this, MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(),
16703 Method, FoundDecl, MemExpr, HadMultipleCandidates,
16704 MemExpr->getMemberNameInfo(), TemplateArgs);
16705 if (FnExpr.isInvalid())
16706 return ExprError();
16707
16708 TheCall =
16709 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16710 CurFPFeatureOverrides(), Proto->getNumParams());
16711 TheCall->setUsesMemberSyntax(true);
16712 } else {
16713 // Convert the object argument (for a non-static member function call).
16715 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16716 if (ObjectArg.isInvalid())
16717 return ExprError();
16718 MemExpr->setBase(ObjectArg.get());
16719 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16720 RParenLoc, CurFPFeatureOverrides(),
16721 Proto->getNumParams());
16722 }
16723
16724 // Check for a valid return type.
16725 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16726 TheCall, Method))
16727 return BuildRecoveryExpr(ResultType);
16728
16729 // Convert the rest of the arguments
16730 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16731 RParenLoc))
16732 return BuildRecoveryExpr(ResultType);
16733
16734 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16735
16736 if (CheckFunctionCall(Method, TheCall, Proto))
16737 return ExprError();
16738
16739 // In the case the method to call was not selected by the overloading
16740 // resolution process, we still need to handle the enable_if attribute. Do
16741 // that here, so it will not hide previous -- and more relevant -- errors.
16742 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16743 if (const EnableIfAttr *Attr =
16744 CheckEnableIf(Method, LParenLoc, Args, true)) {
16745 Diag(MemE->getMemberLoc(),
16746 diag::err_ovl_no_viable_member_function_in_call)
16747 << Method << Method->getSourceRange();
16748 Diag(Method->getLocation(),
16749 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16750 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16751 return ExprError();
16752 }
16753 }
16754
16756 TheCall->getDirectCallee()->isPureVirtual()) {
16757 const FunctionDecl *MD = TheCall->getDirectCallee();
16758
16759 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16761 Diag(MemExpr->getBeginLoc(),
16762 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16764 << MD->getParent();
16765
16766 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16767 if (getLangOpts().AppleKext)
16768 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16769 << MD->getParent() << MD->getDeclName();
16770 }
16771 }
16772
16773 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16774 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16775 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16776 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16777 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16778 MemExpr->getMemberLoc());
16779 }
16780
16782 TheCall->getDirectCallee());
16783}
16784
16787 SourceLocation LParenLoc,
16788 MultiExprArg Args,
16789 SourceLocation RParenLoc) {
16790 if (checkPlaceholderForOverload(*this, Obj))
16791 return ExprError();
16792 ExprResult Object = Obj;
16793
16794 UnbridgedCastsSet UnbridgedCasts;
16795 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16796 return ExprError();
16797
16798 assert(Object.get()->getType()->isRecordType() &&
16799 "Requires object type argument");
16800
16801 // C++ [over.call.object]p1:
16802 // If the primary-expression E in the function call syntax
16803 // evaluates to a class object of type "cv T", then the set of
16804 // candidate functions includes at least the function call
16805 // operators of T. The function call operators of T are obtained by
16806 // ordinary lookup of the name operator() in the context of
16807 // (E).operator().
16808 OverloadCandidateSet CandidateSet(LParenLoc,
16810 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16811
16812 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16813 diag::err_incomplete_object_call, Object.get()))
16814 return true;
16815
16816 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16817 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16819 R.suppressAccessDiagnostics();
16820
16821 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16822 Oper != OperEnd; ++Oper) {
16823 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16824 Object.get()->Classify(Context), Args, CandidateSet,
16825 /*SuppressUserConversion=*/false);
16826 }
16827
16828 // When calling a lambda, both the call operator, and
16829 // the conversion operator to function pointer
16830 // are considered. But when constraint checking
16831 // on the call operator fails, it will also fail on the
16832 // conversion operator as the constraints are always the same.
16833 // As the user probably does not intend to perform a surrogate call,
16834 // we filter them out to produce better error diagnostics, ie to avoid
16835 // showing 2 failed overloads instead of one.
16836 bool IgnoreSurrogateFunctions = false;
16837 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16838 const OverloadCandidate &Candidate = *CandidateSet.begin();
16839 if (!Candidate.Viable &&
16841 IgnoreSurrogateFunctions = true;
16842 }
16843
16844 // C++ [over.call.object]p2:
16845 // In addition, for each (non-explicit in C++0x) conversion function
16846 // declared in T of the form
16847 //
16848 // operator conversion-type-id () cv-qualifier;
16849 //
16850 // where cv-qualifier is the same cv-qualification as, or a
16851 // greater cv-qualification than, cv, and where conversion-type-id
16852 // denotes the type "pointer to function of (P1,...,Pn) returning
16853 // R", or the type "reference to pointer to function of
16854 // (P1,...,Pn) returning R", or the type "reference to function
16855 // of (P1,...,Pn) returning R", a surrogate call function [...]
16856 // is also considered as a candidate function. Similarly,
16857 // surrogate call functions are added to the set of candidate
16858 // functions for each conversion function declared in an
16859 // accessible base class provided the function is not hidden
16860 // within T by another intervening declaration.
16861 const auto &Conversions = Record->getVisibleConversionFunctions();
16862 for (auto I = Conversions.begin(), E = Conversions.end();
16863 !IgnoreSurrogateFunctions && I != E; ++I) {
16864 NamedDecl *D = *I;
16865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16866 if (isa<UsingShadowDecl>(D))
16867 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16868
16869 // Skip over templated conversion functions; they aren't
16870 // surrogates.
16872 continue;
16873
16875 if (!Conv->isExplicit()) {
16876 // Strip the reference type (if any) and then the pointer type (if
16877 // any) to get down to what might be a function type.
16878 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16879 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16880 ConvType = ConvPtrType->getPointeeType();
16881
16882 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16883 {
16884 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16885 Object.get(), Args, CandidateSet);
16886 }
16887 }
16888 }
16889
16890 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16891
16892 // Perform overload resolution.
16894 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16895 Best)) {
16896 case OR_Success:
16897 // Overload resolution succeeded; we'll build the appropriate call
16898 // below.
16899 break;
16900
16901 case OR_No_Viable_Function: {
16903 CandidateSet.empty()
16904 ? (PDiag(diag::err_ovl_no_oper)
16905 << Object.get()->getType() << /*call*/ 1
16906 << Object.get()->getSourceRange())
16907 : (PDiag(diag::err_ovl_no_viable_object_call)
16908 << Object.get()->getType() << Object.get()->getSourceRange());
16909 CandidateSet.NoteCandidates(
16910 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16911 OCD_AllCandidates, Args);
16912 break;
16913 }
16914 case OR_Ambiguous:
16915 if (!R.isAmbiguous())
16916 CandidateSet.NoteCandidates(
16917 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16918 PDiag(diag::err_ovl_ambiguous_object_call)
16919 << Object.get()->getType()
16920 << Object.get()->getSourceRange()),
16921 *this, OCD_AmbiguousCandidates, Args);
16922 break;
16923
16924 case OR_Deleted: {
16925 // FIXME: Is this diagnostic here really necessary? It seems that
16926 // 1. we don't have any tests for this diagnostic, and
16927 // 2. we already issue err_deleted_function_use for this later on anyway.
16928 StringLiteral *Msg = Best->Function->getDeletedMessage();
16929 CandidateSet.NoteCandidates(
16930 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16931 PDiag(diag::err_ovl_deleted_object_call)
16932 << Object.get()->getType() << (Msg != nullptr)
16933 << (Msg ? Msg->getString() : StringRef())
16934 << Object.get()->getSourceRange()),
16935 *this, OCD_AllCandidates, Args);
16936 break;
16937 }
16938 }
16939
16940 if (Best == CandidateSet.end())
16941 return true;
16942
16943 UnbridgedCasts.restore();
16944
16945 if (Best->Function == nullptr) {
16946 // Since there is no function declaration, this is one of the
16947 // surrogate candidates. Dig out the conversion function.
16948 CXXConversionDecl *Conv
16950 Best->Conversions[0].UserDefined.ConversionFunction);
16951
16952 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16953 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16954 "Found Decl & conversion-to-functionptr should be same, right?!");
16955 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16956 Best->FoundDecl);
16957 if (DiagnoseUseOfDecl(Conv, LParenLoc))
16958 return ExprError();
16959 // We selected one of the surrogate functions that converts the
16960 // object parameter to a function pointer. Perform the conversion
16961 // on the object argument, then let BuildCallExpr finish the job.
16962
16963 // Create an implicit member expr to refer to the conversion operator.
16964 // and then call it.
16965 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16966 Conv, HadMultipleCandidates);
16967 if (Call.isInvalid())
16968 return ExprError();
16969 // Record usage of conversion in an implicit cast.
16971 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16972 nullptr, VK_PRValue, CurFPFeatureOverrides());
16973
16974 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16975 }
16976
16977 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16978
16979 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16980 // that calls this method, using Object for the implicit object
16981 // parameter and passing along the remaining arguments.
16982 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16983
16984 // An error diagnostic has already been printed when parsing the declaration.
16985 if (Method->isInvalidDecl())
16986 return ExprError();
16987
16988 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16989 unsigned NumParams = Proto->getNumParams();
16990
16991 DeclarationNameInfo OpLocInfo(
16992 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16993 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16994 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, Obj,
16995 HadMultipleCandidates, OpLocInfo);
16996 if (NewFn.isInvalid())
16997 return true;
16998
16999 SmallVector<Expr *, 8> MethodArgs;
17000 MethodArgs.reserve(NumParams + 1);
17001
17002 bool IsError = false;
17003
17004 // Initialize the object parameter.
17006 if (Method->isExplicitObjectMemberFunction()) {
17007 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
17008 } else {
17010 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17011 if (ObjRes.isInvalid())
17012 IsError = true;
17013 else
17014 Object = ObjRes;
17015 MethodArgs.push_back(Object.get());
17016 }
17017
17019 *this, MethodArgs, Method, Args, LParenLoc);
17020
17021 // If this is a variadic call, handle args passed through "...".
17022 if (Proto->isVariadic()) {
17023 // Promote the arguments (C99 6.5.2.2p7).
17024 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
17026 Args[i], VariadicCallType::Method, nullptr);
17027 IsError |= Arg.isInvalid();
17028 MethodArgs.push_back(Arg.get());
17029 }
17030 }
17031
17032 if (IsError)
17033 return true;
17034
17035 DiagnoseSentinelCalls(Method, LParenLoc, Args);
17036
17037 // Once we've built TheCall, all of the expressions are properly owned.
17038 QualType ResultTy = Method->getReturnType();
17040 ResultTy = ResultTy.getNonLValueExprType(Context);
17041
17043 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
17045
17046 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
17047 return true;
17048
17049 if (CheckFunctionCall(Method, TheCall, Proto))
17050 return true;
17051
17053}
17054
17056 SourceLocation OpLoc,
17057 bool *NoArrowOperatorFound) {
17058 assert(Base->getType()->isRecordType() &&
17059 "left-hand side must have class type");
17060
17062 return ExprError();
17063
17064 SourceLocation Loc = Base->getExprLoc();
17065
17066 // C++ [over.ref]p1:
17067 //
17068 // [...] An expression x->m is interpreted as (x.operator->())->m
17069 // for a class object x of type T if T::operator->() exists and if
17070 // the operator is selected as the best match function by the
17071 // overload resolution mechanism (13.3).
17072 DeclarationName OpName =
17073 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
17075
17076 if (RequireCompleteType(Loc, Base->getType(),
17077 diag::err_typecheck_incomplete_tag, Base))
17078 return ExprError();
17079
17080 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
17081 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
17082 R.suppressAccessDiagnostics();
17083
17084 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
17085 Oper != OperEnd; ++Oper) {
17086 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
17087 {}, CandidateSet,
17088 /*SuppressUserConversion=*/false);
17089 }
17090
17091 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17092
17093 // Perform overload resolution.
17095 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
17096 case OR_Success:
17097 // Overload resolution succeeded; we'll build the call below.
17098 break;
17099
17100 case OR_No_Viable_Function: {
17101 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
17102 if (CandidateSet.empty()) {
17103 QualType BaseType = Base->getType();
17104 if (NoArrowOperatorFound) {
17105 // Report this specific error to the caller instead of emitting a
17106 // diagnostic, as requested.
17107 *NoArrowOperatorFound = true;
17108 return ExprError();
17109 }
17110 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
17111 << BaseType << Base->getSourceRange();
17112 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17113 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
17114 << FixItHint::CreateReplacement(OpLoc, ".");
17115 }
17116 } else
17117 Diag(OpLoc, diag::err_ovl_no_viable_oper)
17118 << "operator->" << Base->getSourceRange();
17119 CandidateSet.NoteCandidates(*this, Base, Cands);
17120 return ExprError();
17121 }
17122 case OR_Ambiguous:
17123 if (!R.isAmbiguous())
17124 CandidateSet.NoteCandidates(
17125 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
17126 << "->" << Base->getType()
17127 << Base->getSourceRange()),
17129 return ExprError();
17130
17131 case OR_Deleted: {
17132 StringLiteral *Msg = Best->Function->getDeletedMessage();
17133 CandidateSet.NoteCandidates(
17134 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
17135 << "->" << (Msg != nullptr)
17136 << (Msg ? Msg->getString() : StringRef())
17137 << Base->getSourceRange()),
17138 *this, OCD_AllCandidates, Base);
17139 return ExprError();
17140 }
17141 }
17142
17143 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
17144
17145 // Convert the object parameter.
17146 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
17147
17148 if (Method->isExplicitObjectMemberFunction()) {
17150 if (R.isInvalid())
17151 return ExprError();
17152 Base = R.get();
17153 } else {
17155 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17156 if (BaseResult.isInvalid())
17157 return ExprError();
17158 Base = BaseResult.get();
17159 }
17160
17161 // Build the operator call.
17162 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17163 Base, HadMultipleCandidates, OpLoc);
17164 if (FnExpr.isInvalid())
17165 return ExprError();
17166
17167 QualType ResultTy = Method->getReturnType();
17169 ResultTy = ResultTy.getNonLValueExprType(Context);
17170
17171 CallExpr *TheCall =
17172 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17173 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17174
17175 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17176 return ExprError();
17177
17178 if (CheckFunctionCall(Method, TheCall,
17179 Method->getType()->castAs<FunctionProtoType>()))
17180 return ExprError();
17181
17183}
17184
17186 DeclarationNameInfo &SuffixInfo,
17187 ArrayRef<Expr*> Args,
17188 SourceLocation LitEndLoc,
17189 TemplateArgumentListInfo *TemplateArgs) {
17190 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17191
17192 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17194 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17195 TemplateArgs);
17196
17197 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17198
17199 // Perform overload resolution. This will usually be trivial, but might need
17200 // to perform substitutions for a literal operator template.
17202 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17203 case OR_Success:
17204 case OR_Deleted:
17205 break;
17206
17208 CandidateSet.NoteCandidates(
17209 PartialDiagnosticAt(UDSuffixLoc,
17210 PDiag(diag::err_ovl_no_viable_function_in_call)
17211 << R.getLookupName()),
17212 *this, OCD_AllCandidates, Args);
17213 return ExprError();
17214
17215 case OR_Ambiguous:
17216 CandidateSet.NoteCandidates(
17217 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17218 << R.getLookupName()),
17219 *this, OCD_AmbiguousCandidates, Args);
17220 return ExprError();
17221 }
17222
17223 FunctionDecl *FD = Best->Function;
17224 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, nullptr,
17225 HadMultipleCandidates, SuffixInfo);
17226 if (Fn.isInvalid())
17227 return true;
17228
17229 // Check the argument types. This should almost always be a no-op, except
17230 // that array-to-pointer decay is applied to string literals.
17231 Expr *ConvArgs[2];
17232 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17235 SourceLocation(), Args[ArgIdx]);
17236 if (InputInit.isInvalid())
17237 return true;
17238 ConvArgs[ArgIdx] = InputInit.get();
17239 }
17240
17241 QualType ResultTy = FD->getReturnType();
17243 ResultTy = ResultTy.getNonLValueExprType(Context);
17244
17246 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17247 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17248
17249 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17250 return ExprError();
17251
17252 if (CheckFunctionCall(FD, UDL, nullptr))
17253 return ExprError();
17254
17256}
17257
17260 SourceLocation RangeLoc,
17261 const DeclarationNameInfo &NameInfo,
17262 LookupResult &MemberLookup,
17263 OverloadCandidateSet *CandidateSet,
17264 Expr *Range, ExprResult *CallExpr) {
17265 Scope *S = nullptr;
17266
17268 if (!MemberLookup.empty()) {
17269 ExprResult MemberRef =
17270 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17271 /*IsPtr=*/false, CXXScopeSpec(),
17272 /*TemplateKWLoc=*/SourceLocation(),
17273 /*FirstQualifierInScope=*/nullptr,
17274 MemberLookup,
17275 /*TemplateArgs=*/nullptr, S);
17276 if (MemberRef.isInvalid()) {
17277 *CallExpr = ExprError();
17278 return FRS_DiagnosticIssued;
17279 }
17280 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17281 if (CallExpr->isInvalid()) {
17282 *CallExpr = ExprError();
17283 return FRS_DiagnosticIssued;
17284 }
17285 } else {
17286 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17288 NameInfo, UnresolvedSet<0>());
17289 if (FnR.isInvalid())
17290 return FRS_DiagnosticIssued;
17292
17293 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17294 CandidateSet, CallExpr);
17295 if (CandidateSet->empty() || CandidateSetError) {
17296 *CallExpr = ExprError();
17297 return FRS_NoViableFunction;
17298 }
17300 OverloadingResult OverloadResult =
17301 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17302
17303 if (OverloadResult == OR_No_Viable_Function) {
17304 *CallExpr = ExprError();
17305 return FRS_NoViableFunction;
17306 }
17307 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17308 Loc, nullptr, CandidateSet, &Best,
17309 OverloadResult,
17310 /*AllowTypoCorrection=*/false);
17311 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17312 *CallExpr = ExprError();
17313 return FRS_DiagnosticIssued;
17314 }
17315 }
17316 return FRS_Success;
17317}
17318
17320 FunctionDecl *Fn) {
17321 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17322 ExprResult SubExpr =
17323 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17324 if (SubExpr.isInvalid())
17325 return ExprError();
17326 if (SubExpr.get() == PE->getSubExpr())
17327 return PE;
17328
17329 return new (Context)
17330 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17331 }
17332
17333 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17334 ExprResult SubExpr =
17335 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17336 if (SubExpr.isInvalid())
17337 return ExprError();
17338 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17339 SubExpr.get()->getType()) &&
17340 "Implicit cast type cannot be determined from overload");
17341 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17342 if (SubExpr.get() == ICE->getSubExpr())
17343 return ICE;
17344
17345 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17346 SubExpr.get(), nullptr, ICE->getValueKind(),
17348 }
17349
17350 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17351 if (!GSE->isResultDependent()) {
17352 ExprResult SubExpr =
17353 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17354 if (SubExpr.isInvalid())
17355 return ExprError();
17356 if (SubExpr.get() == GSE->getResultExpr())
17357 return GSE;
17358
17359 // Replace the resulting type information before rebuilding the generic
17360 // selection expression.
17361 ArrayRef<Expr *> A = GSE->getAssocExprs();
17362 SmallVector<Expr *, 4> AssocExprs(A);
17363 unsigned ResultIdx = GSE->getResultIndex();
17364 AssocExprs[ResultIdx] = SubExpr.get();
17365
17366 if (GSE->isExprPredicate())
17368 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17369 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17370 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17371 ResultIdx);
17373 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17374 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17375 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17376 ResultIdx);
17377 }
17378 // Rather than fall through to the unreachable, return the original generic
17379 // selection expression.
17380 return GSE;
17381 }
17382
17383 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17384 assert(UnOp->getOpcode() == UO_AddrOf &&
17385 "Can only take the address of an overloaded function");
17386 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17387 if (!Method->isImplicitObjectMemberFunction()) {
17388 // Do nothing: the address of static and
17389 // explicit object member functions is a (non-member) function pointer.
17390 } else {
17391 // Fix the subexpression, which really has to be an
17392 // UnresolvedLookupExpr holding an overloaded member function
17393 // or template.
17394 ExprResult SubExpr =
17395 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17396 if (SubExpr.isInvalid())
17397 return ExprError();
17398 if (SubExpr.get() == UnOp->getSubExpr())
17399 return UnOp;
17400
17401 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17402 SubExpr.get(), Method))
17403 return ExprError();
17404
17405 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17406 "fixed to something other than a decl ref");
17407 NestedNameSpecifier Qualifier =
17408 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17409 assert(Qualifier &&
17410 "fixed to a member ref with no nested name qualifier");
17411
17412 // We have taken the address of a pointer to member
17413 // function. Perform the computation here so that we get the
17414 // appropriate pointer to member type.
17415 QualType MemPtrType = Context.getMemberPointerType(
17416 Fn->getType(), Qualifier,
17417 cast<CXXRecordDecl>(Method->getDeclContext()));
17418 // Under the MS ABI, lock down the inheritance model now.
17419 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17420 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17421
17422 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17423 MemPtrType, VK_PRValue, OK_Ordinary,
17424 UnOp->getOperatorLoc(), false,
17426 }
17427 }
17428 ExprResult SubExpr =
17429 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17430 if (SubExpr.isInvalid())
17431 return ExprError();
17432 if (SubExpr.get() == UnOp->getSubExpr())
17433 return UnOp;
17434
17435 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17436 SubExpr.get());
17437 }
17438
17439 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17440 if (Found.getAccess() == AS_none) {
17442 }
17443 // FIXME: avoid copy.
17444 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17445 if (ULE->hasExplicitTemplateArgs()) {
17446 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17447 TemplateArgs = &TemplateArgsBuffer;
17448 }
17449
17450 QualType Type = Fn->getType();
17451 ExprValueKind ValueKind =
17452 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17453 ? VK_LValue
17454 : VK_PRValue;
17455
17456 // FIXME: Duplicated from BuildDeclarationNameExpr.
17457 if (unsigned BID = Fn->getBuiltinID()) {
17458 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17459 Type = Context.BuiltinFnTy;
17460 ValueKind = VK_PRValue;
17461 }
17462 }
17463
17465 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17466 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17467 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17468 return DRE;
17469 }
17470
17471 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17472 // FIXME: avoid copy.
17473 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17474 if (MemExpr->hasExplicitTemplateArgs()) {
17475 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17476 TemplateArgs = &TemplateArgsBuffer;
17477 }
17478
17479 Expr *Base;
17480
17481 // If we're filling in a static method where we used to have an
17482 // implicit member access, rewrite to a simple decl ref.
17483 if (MemExpr->isImplicitAccess()) {
17484 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17486 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17487 MemExpr->getQualifierLoc(), Found.getDecl(),
17488 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17489 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17490 return DRE;
17491 } else {
17492 SourceLocation Loc = MemExpr->getMemberLoc();
17493 if (MemExpr->getQualifier())
17494 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17495 Base =
17496 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17497 }
17498 } else
17499 Base = MemExpr->getBase();
17500
17501 ExprValueKind valueKind;
17502 QualType type;
17503 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17504 valueKind = VK_LValue;
17505 type = Fn->getType();
17506 } else {
17507 valueKind = VK_PRValue;
17508 type = Context.BoundMemberTy;
17509 }
17510
17511 return BuildMemberExpr(
17512 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17513 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17514 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17515 type, valueKind, OK_Ordinary, TemplateArgs);
17516 }
17517
17518 llvm_unreachable("Invalid reference to overloaded function");
17519}
17520
17526
17527bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17529 if (!PartialOverloading || !Function)
17530 return true;
17531 if (Function->isVariadic())
17532 return false;
17533 if (const auto *Proto =
17534 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17535 if (Proto->isTemplateVariadic())
17536 return false;
17537 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17538 if (const auto *Proto =
17539 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17540 if (Proto->isTemplateVariadic())
17541 return false;
17542 return true;
17543}
17544
17546 DeclarationName Name,
17547 OverloadCandidateSet &CandidateSet,
17548 FunctionDecl *Fn, MultiExprArg Args,
17549 bool IsMember) {
17550 StringLiteral *Msg = Fn->getDeletedMessage();
17551 CandidateSet.NoteCandidates(
17552 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17553 << IsMember << Name << (Msg != nullptr)
17554 << (Msg ? Msg->getString() : StringRef())
17555 << Range),
17556 *this, OCD_AllCandidates, Args);
17557}
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 AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:186
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:32
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress, TemplateSpecCandidateSetKind CandidateSetKind=TemplateSpecCandidateSetKind::Normal)
Diagnose a failed template-argument deduction.
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 IsHLSLPackedTypeConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &DimensionICK, Expr *From)
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 bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, const OverloadCandidateSet &ResolvedCandidateSet)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
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 ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, const OverloadCandidateSet &ResolvedCandidateSet, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
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 bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, const OverloadCandidateSet &ResolvedCandidates, 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 void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
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 ExprResult CreateFunctionRefExpr(Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
A convenience routine for creating a decayed reference to a function.
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 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 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 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)
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:158
bool isAbsent() const
Definition APValue.h:545
bool isFloat() const
Definition APValue.h:550
bool isInt() const
Definition APValue.h:549
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
APFloat & getFloat()
Definition APValue.h:587
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:860
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
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
CanQualType MetaInfoTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:976
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:975
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:3990
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:401
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8262
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4086
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2217
StringRef getOpcodeStr() const
Definition Expr.h:4152
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
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:5144
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4227
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
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:2642
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
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:3106
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3009
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3013
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
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:724
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:2719
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:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
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:654
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:1028
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1569
bool hasDefinition() const
Definition DeclCXX.h:562
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:291
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:2991
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:1549
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3174
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3155
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3373
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:3362
QualType getElementType() const
Definition TypeBase.h:3372
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:5166
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
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:4490
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4512
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4509
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2120
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:1294
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:1487
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
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:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
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:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:818
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:803
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:794
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:630
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4150
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4368
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4266
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1973
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1957
const Expr * getExpr() const
Definition DeclCXX.h:1958
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1496
The return type of classify().
Definition Expr.h:340
bool isLValue() const
Definition Expr.h:391
bool isPRValue() const
Definition Expr.h:394
bool isXValue() const
Definition Expr.h:392
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:399
bool isRValue() const
Definition Expr.h:395
This represents one expression.
Definition Expr.h:113
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:288
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
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:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:286
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3378
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:855
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:859
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
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:835
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:4110
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:480
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:416
QualType getType() const
Definition Expr.h:145
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3299
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2123
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2152
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2932
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4254
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4242
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3809
param_iterator param_end()
Definition Decl.h:2918
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3713
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3917
QualType getReturnType() const
Definition Decl.h:2980
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
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:4313
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4362
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3794
param_iterator param_begin()
Definition Decl.h:2917
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3124
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4378
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4306
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3921
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4179
bool isConsteval() const
Definition Decl.h:2609
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3757
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3291
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:2997
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:3762
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4214
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3873
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5920
unsigned getNumParams() const
Definition TypeBase.h:5694
Qualifiers getMethodQuals() const
Definition TypeBase.h:5842
QualType getParamType(unsigned i) const
Definition TypeBase.h:5696
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5820
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5856
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:4723
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4794
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4651
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
ExtInfo getExtInfo() const
Definition TypeBase.h:4968
CallingConv getCallConv() const
Definition TypeBase.h:4967
QualType getReturnType() const
Definition TypeBase.h:4952
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4980
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:4765
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:3901
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:626
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:677
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:774
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:681
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:831
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:685
bool hasInitializerListContainerType() const
Definition Overload.h:813
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:738
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:820
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:689
QualType getInitializerListContainerType() const
Definition Overload.h:823
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5356
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5472
unsigned getNumInits() const
Definition Expr.h:5389
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2535
const Expr * getInit(unsigned Init) const
Definition Expr.h:5411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2553
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:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
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:4454
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3412
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3601
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3523
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding the member name, if any.
Definition Expr.h:3529
NestedNameSpecifierLoc getQualifierLoc() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name,...
Definition Expr.h:3514
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3495
bool hasExplicitTemplateArgs() const
Determines whether the member name was followed by an explicit template argument list.
Definition Expr.h:3556
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3509
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:3560
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3630
Expr * getBase() const
Definition Expr.h:3489
void setBase(Expr *E)
Definition Expr.h:3488
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1830
DeclarationNameInfo getMemberNameInfo() const
Retrieve the member declaration name info.
Definition Expr.h:3589
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3499
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3783
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5847
QualType getPointeeType() const
Definition TypeBase.h:3769
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:241
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1682
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
Represent a C++ namespace.
Definition Decl.h:593
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>::".
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8031
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8087
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8176
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8145
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8099
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8139
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2011
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8151
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1202
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
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:1364
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:1466
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1400
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:1416
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1354
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1189
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1185
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1180
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1175
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1194
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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:1372
SourceLocation getLocation() const
Definition Overload.h:1352
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1431
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1353
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1391
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:3143
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3295
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3204
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3259
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3256
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3234
decls_iterator decls_begin() const
Definition ExprCXX.h:3236
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3247
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3269
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3265
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3325
decls_iterator decls_end() const
Definition ExprCXX.h:3239
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3253
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:2230
Represents a parameter to a function.
Definition Decl.h:1820
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3049
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5238
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8524
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8535
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3827
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8486
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:8631
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
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:8600
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8567
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8492
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
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:8611
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8478
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8386
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8393
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4984
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:854
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:861
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
bool hasOnlyConst() const
Definition TypeBase.h:459
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasConst() const
Definition TypeBase.h:458
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasRestrict() const
Definition TypeBase.h:478
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:709
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeUnaligned()
Definition TypeBase.h:516
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
bool hasVolatile() const
Definition TypeBase.h:468
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
Represents a struct/union/class.
Definition Decl.h:4464
field_range fields() const
Definition Decl.h:4667
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4652
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
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:1710
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1755
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:211
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:462
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:399
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:409
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:311
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:10485
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.
RAII class to control scope of DeferDiags.
Definition Sema.h:10208
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1412
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1447
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:12673
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12707
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:1474
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:10226
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:9494
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9521
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9506
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9502
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:418
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:169
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:1499
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:10568
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10571
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10577
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10575
@ AR_dependent
Definition Sema.h:1718
@ AR_accessible
Definition Sema.h:1716
@ AR_inaccessible
Definition Sema.h:1717
@ AR_delayed
Definition Sema.h:1719
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:2107
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:1769
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:1332
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:702
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:228
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1544
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:768
ASTContext & getASTContext() const
Definition Sema.h:935
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:778
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....
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
@ FRS_Success
Definition Sema.h:10956
@ FRS_DiagnosticIssued
Definition Sema.h:10958
@ FRS_NoViableFunction
Definition Sema.h:10957
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9487
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:10277
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:1236
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:3744
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:12371
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:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1330
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:1509
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9486
MemberPointerConversionDirection
Definition Sema.h:10409
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:10596
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:648
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:15778
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:10022
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:7119
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:1472
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:8332
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:14184
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:7616
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:13927
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:15733
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:127
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:6882
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6851
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:10401
SourceManager & SourceMgr
Definition Sema.h:1335
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1334
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:524
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:6559
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:1479
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:8812
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:301
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:395
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:360
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:312
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:306
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:365
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:342
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:327
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:394
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:337
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:370
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:321
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:332
void setToType(unsigned Idx, QualType T)
Definition Overload.h:399
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:387
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:352
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:317
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:356
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:347
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:377
QualType getToType(unsigned Idx) const
Definition Overload.h:414
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:1823
StringRef getString() const
Definition Expr.h:1891
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:686
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:728
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:713
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.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3677
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBlockPointerType() const
Definition TypeBase.h:8703
bool isVoidType() const
Definition TypeBase.h:9068
bool isBooleanType() const
Definition TypeBase.h:9209
bool isObjCBuiltinType() const
Definition TypeBase.h:8913
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
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:2122
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:920
bool isIncompleteArrayType() const
Definition TypeBase.h:8790
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isFloat16Type() const
Definition TypeBase.h:9081
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:857
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
bool isRValueReferenceType() const
Definition TypeBase.h:8715
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:8786
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9239
bool isArrayType() const
Definition TypeBase.h:8782
bool isCharType() const
Definition Type.cpp:2319
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9144
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2550
bool isPointerType() const
Definition TypeBase.h:8683
bool isArrayParameterType() const
Definition TypeBase.h:8798
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2795
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
bool isEnumeralType() const
Definition TypeBase.h:8814
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2282
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8883
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2355
bool isExtVectorBoolType() const
Definition TypeBase.h:8830
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8870
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isLValueReferenceType() const
Definition TypeBase.h:8711
bool isBitIntType() const
Definition TypeBase.h:8958
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2631
bool isAnyComplexType() const
Definition TypeBase.h:8818
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9132
bool isHalfType() const
Definition TypeBase.h:9076
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9050
bool isQueueT() const
Definition TypeBase.h:8939
bool isMemberPointerType() const
Definition TypeBase.h:8764
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9222
bool isObjCIdType() const
Definition TypeBase.h:8895
bool isMatrixType() const
Definition TypeBase.h:8846
bool isOverflowBehaviorType() const
Definition TypeBase.h:8854
bool isHLSLBuiltinPackedType() const
Definition TypeBase.h:9013
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9215
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8931
bool isMetaInfoType() const
Definition TypeBase.h:9072
bool isBFloat16Type() const
Definition TypeBase.h:9093
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8679
bool isObjCObjectPointerType() const
Definition TypeBase.h:8862
bool isVectorType() const
Definition TypeBase.h:8822
bool isObjCClassType() const
Definition TypeBase.h:8901
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2816
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9025
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:2460
bool isAnyPointerType() const
Definition TypeBase.h:8691
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:8927
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9109
bool isRecordType() const
Definition TypeBase.h:8810
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:868
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2292
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1462
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:5201
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1438
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3442
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:464
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4180
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4288
QualType getBaseType() const
Definition ExprCXX.h:4262
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4272
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4253
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4298
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4292
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:645
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:998
QualType getType() const
Definition Decl.h:724
unsigned getNumElements() const
Definition TypeBase.h:4288
QualType getElementType() const
Definition TypeBase.h:4287
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:278
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...
Top level wrappers for InstallAPI frontend operations.
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:817
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
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:65
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
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:863
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:891
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:900
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:883
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:887
@ 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:928
@ ovl_fail_too_few_arguments
Definition Overload.h:865
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:907
@ ovl_fail_too_many_arguments
Definition Overload.h:864
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:915
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:924
@ ovl_fail_bad_conversion
Definition Overload.h:866
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:896
@ ovl_fail_bad_deduction
Definition Overload.h:867
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:911
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:920
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:904
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:872
@ Comparison
A comparison.
Definition Sema.h:661
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:224
@ ICR_Conversion
Conversion.
Definition Overload.h:238
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:250
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:260
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:266
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:229
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:253
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:241
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:247
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:244
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:263
@ ICR_Promotion
Promotion.
Definition Overload.h:232
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:226
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:257
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:235
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:165
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1066
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:128
@ AS_none
Definition Specifiers.h:131
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:933
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:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h: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:217
@ ICK_HLSL_Packed_Type_Conversion
HLSL packed type conversion to and from uint.
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
TemplateSpecCandidateSetKind
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:683
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:706
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:727
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:685
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:723
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:581
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:217
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2019
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
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:277
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:279
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:285
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:293
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:282
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:289
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:316
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:374
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:424
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:419
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:395
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:381
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:414
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:398
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:387
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:401
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:411
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:405
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:408
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1527
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:832
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:840
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:838
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
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:6028
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:442
__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:526
ConversionSet::const_iterator const_iterator
Definition Overload.h:562
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:527
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:553
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
QualType getToType() const
Definition Overload.h:611
QualType getFromType() const
Definition Overload.h:610
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).
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:1106
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
SmallVectorImpl< PartialDiagnosticAt > * ExtendedDiag
Location where we spot ptr to int cast or null subobject while evaluating constant expression in MS c...
Definition Expr.h:654
Extra information about a function prototype.
Definition TypeBase.h:5501
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5506
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1199
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:1221
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1248
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1210
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1212
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1238
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:937
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:1002
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:993
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1067
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1041
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1006
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:983
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:951
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:947
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:942
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1014
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:963
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:977
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1032
unsigned getNumParams() const
Definition Overload.h:1080
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1010
unsigned TookAddressOfOverload
Definition Overload.h:996
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1019
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1023
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:960
DeductionFailureInfo DeductionFailure
Definition Overload.h:1026
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:967
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:955
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1037
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10688
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10695
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13338
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13423
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13472
Abstract class used to diagnose incomplete types.
Definition Sema.h:8409
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
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)
void NoteDeductionFailure(Sema &S, bool ForTakingAddress, TemplateSpecCandidateSetKind CandidateSetKind)
Diagnose a template argument deduction failure.
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:481
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:493
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:515
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:506
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:510
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:501
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:520
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.