clang 23.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence &SCS1,
123 const StandardConversionSequence &SCS2);
124
127 const StandardConversionSequence& SCS1,
128 const StandardConversionSequence& SCS2);
129
130/// GetConversionRank - Retrieve the implicit conversion rank
131/// corresponding to the given implicit conversion kind.
133 static const ImplicitConversionRank Rank[] = {
160 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
161 // it was omitted by the patch that added
162 // ICK_Zero_Event_Conversion
163 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Queue_Conversion
174 };
175 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
176 return Rank[(int)Kind];
177}
178
197
198/// GetImplicitConversionName - Return the name of this kind of
199/// implicit conversion.
201 static const char *const Name[] = {
202 "No conversion",
203 "Lvalue-to-rvalue",
204 "Array-to-pointer",
205 "Function-to-pointer",
206 "Function pointer conversion",
207 "Qualification",
208 "Integral promotion",
209 "Floating point promotion",
210 "Complex promotion",
211 "Integral conversion",
212 "Floating conversion",
213 "Complex conversion",
214 "Floating-integral conversion",
215 "Pointer conversion",
216 "Pointer-to-member conversion",
217 "Boolean conversion",
218 "Compatible-types conversion",
219 "Derived-to-base conversion",
220 "Vector conversion",
221 "SVE Vector conversion",
222 "RVV Vector conversion",
223 "Vector splat",
224 "Complex-real conversion",
225 "Block Pointer conversion",
226 "Transparent Union Conversion",
227 "Writeback conversion",
228 "OpenCL Zero Event Conversion",
229 "OpenCL Zero Queue Conversion",
230 "C specific type conversion",
231 "Incompatible pointer conversion",
232 "Fixed point conversion",
233 "HLSL vector truncation",
234 "HLSL matrix truncation",
235 "Non-decaying array conversion",
236 "HLSL vector splat",
237 "HLSL matrix splat",
238 };
239 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
240 return Name[Kind];
241}
242
243/// StandardConversionSequence - Set the standard conversion
244/// sequence to the identity conversion.
262
263/// getRank - Retrieve the rank of this standard conversion sequence
264/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
265/// implicit conversions.
278
279/// isPointerConversionToBool - Determines whether this conversion is
280/// a conversion of a pointer or pointer-to-member to bool. This is
281/// used as part of the ranking of standard conversion sequences
282/// (C++ 13.3.3.2p4).
284 // Note that FromType has not necessarily been transformed by the
285 // array-to-pointer or function-to-pointer implicit conversions, so
286 // check for their presence as well as checking whether FromType is
287 // a pointer.
288 if (getToType(1)->isBooleanType() &&
289 (getFromType()->isPointerType() ||
290 getFromType()->isMemberPointerType() ||
291 getFromType()->isObjCObjectPointerType() ||
292 getFromType()->isBlockPointerType() ||
294 return true;
295
296 return false;
297}
298
299/// isPointerConversionToVoidPointer - Determines whether this
300/// conversion is a conversion of a pointer to a void pointer. This is
301/// used as part of the ranking of standard conversion sequences (C++
302/// 13.3.3.2p4).
303bool
306 QualType FromType = getFromType();
307 QualType ToType = getToType(1);
308
309 // Note that FromType has not necessarily been transformed by the
310 // array-to-pointer implicit conversion, so check for its presence
311 // and redo the conversion to get a pointer.
313 FromType = Context.getArrayDecayedType(FromType);
314
315 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
316 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
317 return ToPtrType->getPointeeType()->isVoidType();
318
319 return false;
320}
321
322/// Skip any implicit casts which could be either part of a narrowing conversion
323/// or after one in an implicit conversion.
325 const Expr *Converted) {
326 // We can have cleanups wrapping the converted expression; these need to be
327 // preserved so that destructors run if necessary.
328 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
329 Expr *Inner =
330 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
331 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
332 EWC->getObjects());
333 }
334
335 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
336 switch (ICE->getCastKind()) {
337 case CK_NoOp:
338 case CK_IntegralCast:
339 case CK_IntegralToBoolean:
340 case CK_IntegralToFloating:
341 case CK_BooleanToSignedIntegral:
342 case CK_FloatingToIntegral:
343 case CK_FloatingToBoolean:
344 case CK_FloatingCast:
345 Converted = ICE->getSubExpr();
346 continue;
347
348 default:
349 return Converted;
350 }
351 }
352
353 return Converted;
354}
355
356/// Check if this standard conversion sequence represents a narrowing
357/// conversion, according to C++11 [dcl.init.list]p7.
358///
359/// \param Ctx The AST context.
360/// \param Converted The result of applying this standard conversion sequence.
361/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
362/// value of the expression prior to the narrowing conversion.
363/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
364/// type of the expression prior to the narrowing conversion.
365/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
366/// from floating point types to integral types should be ignored.
368 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
369 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
370 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
371 "narrowing check outside C++");
372
373 // C++11 [dcl.init.list]p7:
374 // A narrowing conversion is an implicit conversion ...
375 QualType FromType = getToType(0);
376 QualType ToType = getToType(1);
377
378 // A conversion to an enumeration type is narrowing if the conversion to
379 // the underlying type is narrowing. This only arises for expressions of
380 // the form 'Enum{init}'.
381 if (const auto *ED = ToType->getAsEnumDecl())
382 ToType = ED->getIntegerType();
383
384 switch (Second) {
385 // 'bool' is an integral type; dispatch to the right place to handle it.
387 if (FromType->isRealFloatingType())
388 goto FloatingIntegralConversion;
390 goto IntegralConversion;
391 // -- from a pointer type or pointer-to-member type to bool, or
392 return NK_Type_Narrowing;
393
394 // -- from a floating-point type to an integer type, or
395 //
396 // -- from an integer type or unscoped enumeration type to a floating-point
397 // type, except where the source is a constant expression and the actual
398 // value after conversion will fit into the target type and will produce
399 // the original value when converted back to the original type, or
401 FloatingIntegralConversion:
402 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
403 return NK_Type_Narrowing;
404 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
405 ToType->isRealFloatingType()) {
406 if (IgnoreFloatToIntegralConversion)
407 return NK_Not_Narrowing;
408 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
409 assert(Initializer && "Unknown conversion expression");
410
411 // If it's value-dependent, we can't tell whether it's narrowing.
412 if (Initializer->isValueDependent())
414
415 if (std::optional<llvm::APSInt> IntConstantValue =
416 Initializer->getIntegerConstantExpr(Ctx)) {
417 // Convert the integer to the floating type.
418 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
419 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
420 llvm::APFloat::rmNearestTiesToEven);
421 // And back.
422 llvm::APSInt ConvertedValue = *IntConstantValue;
423 bool ignored;
424 llvm::APFloat::opStatus Status = Result.convertToInteger(
425 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
426 // If the converted-back integer has unspecified value, or if the
427 // resulting value is different, this was a narrowing conversion.
428 if (Status == llvm::APFloat::opInvalidOp ||
429 *IntConstantValue != ConvertedValue) {
430 ConstantValue = APValue(*IntConstantValue);
431 ConstantType = Initializer->getType();
433 }
434 } else {
435 // Variables are always narrowings.
437 }
438 }
439 return NK_Not_Narrowing;
440
441 // -- from long double to double or float, or from double to float, except
442 // where the source is a constant expression and the actual value after
443 // conversion is within the range of values that can be represented (even
444 // if it cannot be represented exactly), or
446 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
447 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
448 // FromType is larger than ToType.
449 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
450
451 // If it's value-dependent, we can't tell whether it's narrowing.
452 if (Initializer->isValueDependent())
454
456 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
457 ((Ctx.getLangOpts().CPlusPlus &&
458 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
459 // Constant!
460 if (Ctx.getLangOpts().C23)
461 ConstantValue = R.Val;
462 assert(ConstantValue.isFloat());
463 llvm::APFloat FloatVal = ConstantValue.getFloat();
464 // Convert the source value into the target type.
465 bool ignored;
466 llvm::APFloat Converted = FloatVal;
467 llvm::APFloat::opStatus ConvertStatus =
468 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
469 llvm::APFloat::rmNearestTiesToEven, &ignored);
470 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
471 llvm::APFloat::rmNearestTiesToEven, &ignored);
472 if (Ctx.getLangOpts().C23) {
473 if (FloatVal.isNaN() && Converted.isNaN() &&
474 !FloatVal.isSignaling() && !Converted.isSignaling()) {
475 // Quiet NaNs are considered the same value, regardless of
476 // payloads.
477 return NK_Not_Narrowing;
478 }
479 // For normal values, check exact equality.
480 if (!Converted.bitwiseIsEqual(FloatVal)) {
481 ConstantType = Initializer->getType();
483 }
484 } else {
485 // If there was no overflow, the source value is within the range of
486 // values that can be represented.
487 if (ConvertStatus & llvm::APFloat::opOverflow) {
488 ConstantType = Initializer->getType();
490 }
491 }
492 } else {
494 }
495 }
496 return NK_Not_Narrowing;
497
498 // -- from an integer type or unscoped enumeration type to an integer type
499 // that cannot represent all the values of the original type, except where
500 // (CWG2627) -- the source is a bit-field whose width w is less than that
501 // of its type (or, for an enumeration type, its underlying type) and the
502 // target type can represent all the values of a hypothetical extended
503 // integer type with width w and with the same signedness as the original
504 // type or
505 // -- the source is a constant expression and the actual value after
506 // conversion will fit into the target type and will produce the original
507 // value when converted back to the original type.
509 IntegralConversion: {
510 assert(FromType->isIntegralOrUnscopedEnumerationType());
511 assert(ToType->isIntegralOrUnscopedEnumerationType());
512 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
513 unsigned FromWidth = Ctx.getIntWidth(FromType);
514 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
515 const unsigned ToWidth = Ctx.getIntWidth(ToType);
516
517 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
518 bool ToSigned, unsigned ToWidth) {
519 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
520 !(FromSigned && !ToSigned);
521 };
522
523 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
524 return NK_Not_Narrowing;
525
526 // Not all values of FromType can be represented in ToType.
527 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
528
529 bool DependentBitField = false;
530 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
531 if (BitField->getBitWidth()->isValueDependent())
532 DependentBitField = true;
533 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
534 BitFieldWidth < FromWidth) {
535 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
536 return NK_Not_Narrowing;
537
538 // The initializer will be truncated to the bit-field width
539 FromWidth = BitFieldWidth;
540 }
541 }
542
543 // If it's value-dependent, we can't tell whether it's narrowing.
544 if (Initializer->isValueDependent())
546
547 std::optional<llvm::APSInt> OptInitializerValue =
548 Initializer->getIntegerConstantExpr(Ctx);
549 if (!OptInitializerValue) {
550 // If the bit-field width was dependent, it might end up being small
551 // enough to fit in the target type (unless the target type is unsigned
552 // and the source type is signed, in which case it will never fit)
553 if (DependentBitField && !(FromSigned && !ToSigned))
555
556 // Otherwise, such a conversion is always narrowing
558 }
559 llvm::APSInt &InitializerValue = *OptInitializerValue;
560 bool Narrowing = false;
561 if (FromWidth < ToWidth) {
562 // Negative -> unsigned is narrowing. Otherwise, more bits is never
563 // narrowing.
564 if (InitializerValue.isSigned() && InitializerValue.isNegative())
565 Narrowing = true;
566 } else {
567 // Add a bit to the InitializerValue so we don't have to worry about
568 // signed vs. unsigned comparisons.
569 InitializerValue =
570 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
571 // Convert the initializer to and from the target width and signed-ness.
572 llvm::APSInt ConvertedValue = InitializerValue;
573 ConvertedValue = ConvertedValue.trunc(ToWidth);
574 ConvertedValue.setIsSigned(ToSigned);
575 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
576 ConvertedValue.setIsSigned(InitializerValue.isSigned());
577 // If the result is different, this was a narrowing conversion.
578 if (ConvertedValue != InitializerValue)
579 Narrowing = true;
580 }
581 if (Narrowing) {
582 ConstantType = Initializer->getType();
583 ConstantValue = APValue(InitializerValue);
585 }
586
587 return NK_Not_Narrowing;
588 }
589 case ICK_Complex_Real:
590 if (FromType->isComplexType() && !ToType->isComplexType())
591 return NK_Type_Narrowing;
592 return NK_Not_Narrowing;
593
595 if (Ctx.getLangOpts().C23) {
596 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
598 if (Initializer->EvaluateAsRValue(R, Ctx)) {
599 ConstantValue = R.Val;
600 assert(ConstantValue.isFloat());
601 llvm::APFloat FloatVal = ConstantValue.getFloat();
602 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
603 // value, the unqualified versions of the type of the initializer and
604 // the corresponding real type of the object declared shall be
605 // compatible.
606 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
607 ConstantType = Initializer->getType();
609 }
610 }
611 }
612 return NK_Not_Narrowing;
613 default:
614 // Other kinds of conversions are not narrowings.
615 return NK_Not_Narrowing;
616 }
617}
618
619/// dump - Print this standard conversion sequence to standard
620/// error. Useful for debugging overloading issues.
621LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
622 raw_ostream &OS = llvm::errs();
623 bool PrintedSomething = false;
624 if (First != ICK_Identity) {
626 PrintedSomething = true;
627 }
628
629 if (Second != ICK_Identity) {
630 if (PrintedSomething) {
631 OS << " -> ";
632 }
634
635 if (CopyConstructor) {
636 OS << " (by copy constructor)";
637 } else if (DirectBinding) {
638 OS << " (direct reference binding)";
639 } else if (ReferenceBinding) {
640 OS << " (reference binding)";
641 }
642 PrintedSomething = true;
643 }
644
645 if (Third != ICK_Identity) {
646 if (PrintedSomething) {
647 OS << " -> ";
648 }
650 PrintedSomething = true;
651 }
652
653 if (!PrintedSomething) {
654 OS << "No conversions required";
655 }
656}
657
658/// dump - Print this user-defined conversion sequence to standard
659/// error. Useful for debugging overloading issues.
661 raw_ostream &OS = llvm::errs();
662 if (Before.First || Before.Second || Before.Third) {
663 Before.dump();
664 OS << " -> ";
665 }
667 OS << '\'' << *ConversionFunction << '\'';
668 else
669 OS << "aggregate initialization";
670 if (After.First || After.Second || After.Third) {
671 OS << " -> ";
672 After.dump();
673 }
674}
675
676/// dump - Print this implicit conversion sequence to standard
677/// error. Useful for debugging overloading issues.
679 raw_ostream &OS = llvm::errs();
681 OS << "Worst list element conversion: ";
682 switch (ConversionKind) {
684 OS << "Standard conversion: ";
685 Standard.dump();
686 break;
688 OS << "User-defined conversion: ";
689 UserDefined.dump();
690 break;
692 OS << "Ellipsis conversion";
693 break;
695 OS << "Ambiguous conversion";
696 break;
697 case BadConversion:
698 OS << "Bad conversion";
699 break;
700 }
701
702 OS << "\n";
703}
704
708
710 conversions().~ConversionSet();
711}
712
713void
719
720namespace {
721 // Structure used by DeductionFailureInfo to store
722 // template argument information.
723 struct DFIArguments {
724 TemplateArgument FirstArg;
725 TemplateArgument SecondArg;
726 };
727 // Structure used by DeductionFailureInfo to store
728 // template parameter and template argument information.
729 struct DFIParamWithArguments : DFIArguments {
730 TemplateParameter Param;
731 };
732 // Structure used by DeductionFailureInfo to store template argument
733 // information and the index of the problematic call argument.
734 struct DFIDeducedMismatchArgs : DFIArguments {
735 TemplateArgumentList *TemplateArgs;
736 unsigned CallArgIndex;
737 };
738 // Structure used by DeductionFailureInfo to store information about
739 // unsatisfied constraints.
740 struct CNSInfo {
741 TemplateArgumentList *TemplateArgs;
742 ConstraintSatisfaction Satisfaction;
743 };
744}
745
746/// Convert from Sema's representation of template deduction information
747/// to the form used in overload-candidate information.
751 TemplateDeductionInfo &Info) {
753 Result.Result = static_cast<unsigned>(TDK);
754 Result.HasDiagnostic = false;
755 switch (TDK) {
762 Result.Data = nullptr;
763 break;
764
767 Result.Data = Info.Param.getOpaqueValue();
768 break;
769
772 // FIXME: Should allocate from normal heap so that we can free this later.
773 auto *Saved = new (Context) DFIDeducedMismatchArgs;
774 Saved->FirstArg = Info.FirstArg;
775 Saved->SecondArg = Info.SecondArg;
776 Saved->TemplateArgs = Info.takeSugared();
777 Saved->CallArgIndex = Info.CallArgIndex;
778 Result.Data = Saved;
779 break;
780 }
781
783 // FIXME: Should allocate from normal heap so that we can free this later.
784 DFIArguments *Saved = new (Context) DFIArguments;
785 Saved->FirstArg = Info.FirstArg;
786 Saved->SecondArg = Info.SecondArg;
787 Result.Data = Saved;
788 break;
789 }
790
792 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
795 // FIXME: Should allocate from normal heap so that we can free this later.
796 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
797 Saved->Param = Info.Param;
798 Saved->FirstArg = Info.FirstArg;
799 Saved->SecondArg = Info.SecondArg;
800 Result.Data = Saved;
801 break;
802 }
803
805 Result.Data = Info.takeSugared();
806 if (Info.hasSFINAEDiagnostic()) {
810 Result.HasDiagnostic = true;
811 }
812 break;
813
815 CNSInfo *Saved = new (Context) CNSInfo;
816 Saved->TemplateArgs = Info.takeSugared();
817 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
818 Result.Data = Saved;
819 break;
820 }
821
825 llvm_unreachable("not a deduction failure");
826 }
827
828 return Result;
829}
830
832 switch (static_cast<TemplateDeductionResult>(Result)) {
842 break;
843
850 // FIXME: Destroy the data?
851 Data = nullptr;
852 break;
853
855 // FIXME: Destroy the template argument list?
856 Data = nullptr;
858 Diag->~PartialDiagnosticAt();
859 HasDiagnostic = false;
860 }
861 break;
862
864 // FIXME: Destroy the template argument list?
865 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
866 Data = nullptr;
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
873 // Unhandled
876 break;
877 }
878}
879
881 if (HasDiagnostic)
882 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
883 return nullptr;
884}
885
919
955
987
1019
1021 switch (static_cast<TemplateDeductionResult>(Result)) {
1024 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1025
1026 default:
1027 return std::nullopt;
1028 }
1029}
1030
1032 const FunctionDecl *Y) {
1033 if (!X || !Y)
1034 return false;
1035 if (X->getNumParams() != Y->getNumParams())
1036 return false;
1037 // FIXME: when do rewritten comparison operators
1038 // with explicit object parameters correspond?
1039 // https://cplusplus.github.io/CWG/issues/2797.html
1040 for (unsigned I = 0; I < X->getNumParams(); ++I)
1041 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1042 Y->getParamDecl(I)->getType()))
1043 return false;
1044 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1045 auto *FTY = Y->getDescribedFunctionTemplate();
1046 if (!FTY)
1047 return false;
1048 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1049 FTY->getTemplateParameters()))
1050 return false;
1051 }
1052 return true;
1053}
1054
1056 Expr *FirstOperand, FunctionDecl *EqFD) {
1057 assert(EqFD->getOverloadedOperator() ==
1058 OverloadedOperatorKind::OO_EqualEqual);
1059 // C++2a [over.match.oper]p4:
1060 // A non-template function or function template F named operator== is a
1061 // rewrite target with first operand o unless a search for the name operator!=
1062 // in the scope S from the instantiation context of the operator expression
1063 // finds a function or function template that would correspond
1064 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1065 // scope of the class type of o if F is a class member, and the namespace
1066 // scope of which F is a member otherwise. A function template specialization
1067 // named operator== is a rewrite target if its function template is a rewrite
1068 // target.
1070 OverloadedOperatorKind::OO_ExclaimEqual);
1071 if (isa<CXXMethodDecl>(EqFD)) {
1072 // If F is a class member, search scope is class type of first operand.
1073 QualType RHS = FirstOperand->getType();
1074 auto *RHSRec = RHS->getAsCXXRecordDecl();
1075 if (!RHSRec)
1076 return true;
1077 LookupResult Members(S, NotEqOp, OpLoc,
1079 S.LookupQualifiedName(Members, RHSRec);
1080 Members.suppressAccessDiagnostics();
1081 for (NamedDecl *Op : Members)
1082 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1083 return false;
1084 return true;
1085 }
1086 // Otherwise the search scope is the namespace scope of which F is a member.
1087 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1088 auto *NotEqFD = Op->getAsFunction();
1089 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1090 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1091 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1093 cast<Decl>(Op->getLexicalDeclContext())))
1094 return false;
1095 }
1096 return true;
1097}
1098
1100 OverloadedOperatorKind Op) const {
1102 return false;
1103 return Op == OO_EqualEqual || Op == OO_Spaceship;
1104}
1105
1107 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1108 auto Op = FD->getOverloadedOperator();
1109 if (!allowsReversed(Op))
1110 return false;
1111 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1112 assert(OriginalArgs.size() == 2);
1114 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1115 return false;
1116 }
1117 // Don't bother adding a reversed candidate that can never be a better
1118 // match than the non-reversed version.
1119 return FD->getNumNonObjectParams() != 2 ||
1121 FD->getParamDecl(1)->getType()) ||
1122 FD->hasAttr<EnableIfAttr>();
1123}
1124
1125void OverloadCandidateSet::destroyCandidates() {
1126 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1127 for (auto &C : i->Conversions)
1128 C.~ImplicitConversionSequence();
1129 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1130 i->DeductionFailure.Destroy();
1131 }
1132}
1133
1135 destroyCandidates();
1136 SlabAllocator.Reset();
1137 NumInlineBytesUsed = 0;
1138 Candidates.clear();
1139 Functions.clear();
1140 Kind = CSK;
1141 FirstDeferredCandidate = nullptr;
1142 DeferredCandidatesCount = 0;
1143 HasDeferredTemplateConstructors = false;
1144 ResolutionByPerfectCandidateIsDisabled = false;
1145}
1146
1147namespace {
1148 class UnbridgedCastsSet {
1149 struct Entry {
1150 Expr **Addr;
1151 Expr *Saved;
1152 };
1153 SmallVector<Entry, 2> Entries;
1154
1155 public:
1156 void save(Sema &S, Expr *&E) {
1157 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1158 Entry entry = { &E, E };
1159 Entries.push_back(entry);
1160 E = S.ObjC().stripARCUnbridgedCast(E);
1161 }
1162
1163 void restore() {
1164 for (SmallVectorImpl<Entry>::iterator
1165 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1166 *i->Addr = i->Saved;
1167 }
1168 };
1169}
1170
1171/// checkPlaceholderForOverload - Do any interesting placeholder-like
1172/// preprocessing on the given expression.
1173///
1174/// \param unbridgedCasts a collection to which to add unbridged casts;
1175/// without this, they will be immediately diagnosed as errors
1176///
1177/// Return true on unrecoverable error.
1178static bool
1180 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1181 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1182 // We can't handle overloaded expressions here because overload
1183 // resolution might reasonably tweak them.
1184 if (placeholder->getKind() == BuiltinType::Overload) return false;
1185
1186 // If the context potentially accepts unbridged ARC casts, strip
1187 // the unbridged cast and add it to the collection for later restoration.
1188 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1189 unbridgedCasts) {
1190 unbridgedCasts->save(S, E);
1191 return false;
1192 }
1193
1194 // Go ahead and check everything else.
1195 ExprResult result = S.CheckPlaceholderExpr(E);
1196 if (result.isInvalid())
1197 return true;
1198
1199 E = result.get();
1200 return false;
1201 }
1202
1203 // Nothing to do.
1204 return false;
1205}
1206
1207/// checkArgPlaceholdersForOverload - Check a set of call operands for
1208/// placeholders.
1210 UnbridgedCastsSet &unbridged) {
1211 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1212 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1213 return true;
1214
1215 return false;
1216}
1217
1219 const LookupResult &Old, NamedDecl *&Match,
1220 bool NewIsUsingDecl) {
1221 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1222 I != E; ++I) {
1223 NamedDecl *OldD = *I;
1224
1225 bool OldIsUsingDecl = false;
1226 if (isa<UsingShadowDecl>(OldD)) {
1227 OldIsUsingDecl = true;
1228
1229 // We can always introduce two using declarations into the same
1230 // context, even if they have identical signatures.
1231 if (NewIsUsingDecl) continue;
1232
1233 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1234 }
1235
1236 // A using-declaration does not conflict with another declaration
1237 // if one of them is hidden.
1238 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1239 continue;
1240
1241 // If either declaration was introduced by a using declaration,
1242 // we'll need to use slightly different rules for matching.
1243 // Essentially, these rules are the normal rules, except that
1244 // function templates hide function templates with different
1245 // return types or template parameter lists.
1246 bool UseMemberUsingDeclRules =
1247 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1248 !New->getFriendObjectKind();
1249
1250 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1251 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1252 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1254 continue;
1255 }
1256
1257 if (!isa<FunctionTemplateDecl>(OldD) &&
1258 !shouldLinkPossiblyHiddenDecl(*I, New))
1259 continue;
1260
1261 Match = *I;
1262 return OverloadKind::Match;
1263 }
1264
1265 // Builtins that have custom typechecking or have a reference should
1266 // not be overloadable or redeclarable.
1267 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1268 Match = *I;
1270 }
1271 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1272 // We can overload with these, which can show up when doing
1273 // redeclaration checks for UsingDecls.
1274 assert(Old.getLookupKind() == LookupUsingDeclName);
1275 } else if (isa<TagDecl>(OldD)) {
1276 // We can always overload with tags by hiding them.
1277 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1278 // Optimistically assume that an unresolved using decl will
1279 // overload; if it doesn't, we'll have to diagnose during
1280 // template instantiation.
1281 //
1282 // Exception: if the scope is dependent and this is not a class
1283 // member, the using declaration can only introduce an enumerator.
1284 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1285 Match = *I;
1287 }
1288 } else {
1289 // (C++ 13p1):
1290 // Only function declarations can be overloaded; object and type
1291 // declarations cannot be overloaded.
1292 Match = *I;
1294 }
1295 }
1296
1297 // C++ [temp.friend]p1:
1298 // For a friend function declaration that is not a template declaration:
1299 // -- if the name of the friend is a qualified or unqualified template-id,
1300 // [...], otherwise
1301 // -- if the name of the friend is a qualified-id and a matching
1302 // non-template function is found in the specified class or namespace,
1303 // the friend declaration refers to that function, otherwise,
1304 // -- if the name of the friend is a qualified-id and a matching function
1305 // template is found in the specified class or namespace, the friend
1306 // declaration refers to the deduced specialization of that function
1307 // template, otherwise
1308 // -- the name shall be an unqualified-id [...]
1309 // If we get here for a qualified friend declaration, we've just reached the
1310 // third bullet. If the type of the friend is dependent, skip this lookup
1311 // until instantiation.
1312 if (New->getFriendObjectKind() && New->getQualifier() &&
1313 !New->getDescribedFunctionTemplate() &&
1314 !New->getDependentSpecializationInfo() &&
1315 !New->getType()->isDependentType()) {
1316 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1317 TemplateSpecResult.addAllDecls(Old);
1318 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1319 /*QualifiedFriend*/true)) {
1320 New->setInvalidDecl();
1322 }
1323
1324 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1325 return OverloadKind::Match;
1326 }
1327
1329}
1330
1331template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1332 assert(D && "function decl should not be null");
1333 if (auto *A = D->getAttr<AttrT>())
1334 return !A->isImplicit();
1335 return false;
1336}
1337
1339 FunctionDecl *Old,
1340 bool UseMemberUsingDeclRules,
1341 bool ConsiderCudaAttrs,
1342 bool UseOverrideRules = false) {
1343 // C++ [basic.start.main]p2: This function shall not be overloaded.
1344 if (New->isMain())
1345 return false;
1346
1347 // MSVCRT user defined entry points cannot be overloaded.
1348 if (New->isMSVCRTEntryPoint())
1349 return false;
1350
1351 NamedDecl *OldDecl = Old;
1352 NamedDecl *NewDecl = New;
1354 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1355
1356 // C++ [temp.fct]p2:
1357 // A function template can be overloaded with other function templates
1358 // and with normal (non-template) functions.
1359 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1360 return true;
1361
1362 // Is the function New an overload of the function Old?
1363 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1364 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1365
1366 // Compare the signatures (C++ 1.3.10) of the two functions to
1367 // determine whether they are overloads. If we find any mismatch
1368 // in the signature, they are overloads.
1369
1370 // If either of these functions is a K&R-style function (no
1371 // prototype), then we consider them to have matching signatures.
1372 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1374 return false;
1375
1376 const auto *OldType = cast<FunctionProtoType>(OldQType);
1377 const auto *NewType = cast<FunctionProtoType>(NewQType);
1378
1379 // The signature of a function includes the types of its
1380 // parameters (C++ 1.3.10), which includes the presence or absence
1381 // of the ellipsis; see C++ DR 357).
1382 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1383 return true;
1384
1385 // For member-like friends, the enclosing class is part of the signature.
1386 if ((New->isMemberLikeConstrainedFriend() ||
1388 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1389 return true;
1390
1391 // Compare the parameter lists.
1392 // This can only be done once we have establish that friend functions
1393 // inhabit the same context, otherwise we might tried to instantiate
1394 // references to non-instantiated entities during constraint substitution.
1395 // GH78101.
1396 if (NewTemplate) {
1397 OldDecl = OldTemplate;
1398 NewDecl = NewTemplate;
1399 // C++ [temp.over.link]p4:
1400 // The signature of a function template consists of its function
1401 // signature, its return type and its template parameter list. The names
1402 // of the template parameters are significant only for establishing the
1403 // relationship between the template parameters and the rest of the
1404 // signature.
1405 //
1406 // We check the return type and template parameter lists for function
1407 // templates first; the remaining checks follow.
1408 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1409 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1410 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1411 bool SameReturnType = SemaRef.Context.hasSameType(
1412 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1413 // FIXME(GH58571): Match template parameter list even for non-constrained
1414 // template heads. This currently ensures that the code prior to C++20 is
1415 // not newly broken.
1416 bool ConstraintsInTemplateHead =
1419 // C++ [namespace.udecl]p11:
1420 // The set of declarations named by a using-declarator that inhabits a
1421 // class C does not include member functions and member function
1422 // templates of a base class that "correspond" to (and thus would
1423 // conflict with) a declaration of a function or function template in
1424 // C.
1425 // Comparing return types is not required for the "correspond" check to
1426 // decide whether a member introduced by a shadow declaration is hidden.
1427 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1428 !SameTemplateParameterList)
1429 return true;
1430 if (!UseMemberUsingDeclRules &&
1431 (!SameTemplateParameterList || !SameReturnType))
1432 return true;
1433 }
1434
1435 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1436 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1437
1438 int OldParamsOffset = 0;
1439 int NewParamsOffset = 0;
1440
1441 // When determining if a method is an overload from a base class, act as if
1442 // the implicit object parameter are of the same type.
1443
1444 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1446 auto ThisType = M->getFunctionObjectParameterReferenceType();
1447 if (ThisType.isConstQualified())
1448 Q.removeConst();
1449 return Q;
1450 }
1451
1452 // We do not allow overloading based off of '__restrict'.
1453 Q.removeRestrict();
1454
1455 // We may not have applied the implicit const for a constexpr member
1456 // function yet (because we haven't yet resolved whether this is a static
1457 // or non-static member function). Add it now, on the assumption that this
1458 // is a redeclaration of OldMethod.
1459 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1460 (M->isConstexpr() || M->isConsteval()) &&
1461 !isa<CXXConstructorDecl>(NewMethod))
1462 Q.addConst();
1463 return Q;
1464 };
1465
1466 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1467 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1468 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1469
1470 if (OldMethod->isExplicitObjectMemberFunction()) {
1471 BS.Quals.removeVolatile();
1472 DS.Quals.removeVolatile();
1473 }
1474
1475 return BS.Quals == DS.Quals;
1476 };
1477
1478 auto CompareType = [&](QualType Base, QualType D) {
1479 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1480 auto DS = D.getNonReferenceType().getCanonicalType().split();
1481
1482 if (!AreQualifiersEqual(BS, DS))
1483 return false;
1484
1485 if (OldMethod->isImplicitObjectMemberFunction() &&
1486 OldMethod->getParent() != NewMethod->getParent()) {
1487 CanQualType ParentType =
1488 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1489 if (ParentType.getTypePtr() != BS.Ty)
1490 return false;
1491 BS.Ty = DS.Ty;
1492 }
1493
1494 // FIXME: should we ignore some type attributes here?
1495 if (BS.Ty != DS.Ty)
1496 return false;
1497
1498 if (Base->isLValueReferenceType())
1499 return D->isLValueReferenceType();
1500 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1501 };
1502
1503 // If the function is a class member, its signature includes the
1504 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1505 auto DiagnoseInconsistentRefQualifiers = [&]() {
1506 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1507 return false;
1508 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1509 return false;
1510 if (OldMethod->isExplicitObjectMemberFunction() ||
1511 NewMethod->isExplicitObjectMemberFunction())
1512 return false;
1513 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1514 NewMethod->getRefQualifier() == RQ_None)) {
1515 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1516 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1517 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1518 return true;
1519 }
1520 return false;
1521 };
1522
1523 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1524 OldParamsOffset++;
1525 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1526 NewParamsOffset++;
1527
1528 if (OldType->getNumParams() - OldParamsOffset !=
1529 NewType->getNumParams() - NewParamsOffset ||
1531 {OldType->param_type_begin() + OldParamsOffset,
1532 OldType->param_type_end()},
1533 {NewType->param_type_begin() + NewParamsOffset,
1534 NewType->param_type_end()},
1535 nullptr)) {
1536 return true;
1537 }
1538
1539 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1540 !NewMethod->isStatic()) {
1541 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1542 const CXXMethodDecl *New) {
1543 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1544 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1545
1546 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1547 return F->getRefQualifier() == RQ_None &&
1548 !F->isExplicitObjectMemberFunction();
1549 };
1550
1551 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1552 CompareType(OldObjectType.getNonReferenceType(),
1553 NewObjectType.getNonReferenceType()))
1554 return true;
1555 return CompareType(OldObjectType, NewObjectType);
1556 }(OldMethod, NewMethod);
1557
1558 if (!HaveCorrespondingObjectParameters) {
1559 if (DiagnoseInconsistentRefQualifiers())
1560 return true;
1561 // CWG2554
1562 // and, if at least one is an explicit object member function, ignoring
1563 // object parameters
1564 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1565 !OldMethod->isExplicitObjectMemberFunction()))
1566 return true;
1567 }
1568 }
1569
1570 if (!UseOverrideRules &&
1571 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1572 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1573 OldRC = Old->getTrailingRequiresClause();
1574 if (!NewRC != !OldRC)
1575 return true;
1576 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1577 return true;
1578 if (NewRC &&
1579 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1580 NewDecl, NewRC.ConstraintExpr))
1581 return true;
1582 }
1583
1584 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1585 NewMethod->isImplicitObjectMemberFunction()) {
1586 if (DiagnoseInconsistentRefQualifiers())
1587 return true;
1588 }
1589
1590 // Though pass_object_size is placed on parameters and takes an argument, we
1591 // consider it to be a function-level modifier for the sake of function
1592 // identity. Either the function has one or more parameters with
1593 // pass_object_size or it doesn't.
1596 return true;
1597
1598 // enable_if attributes are an order-sensitive part of the signature.
1600 NewI = New->specific_attr_begin<EnableIfAttr>(),
1601 NewE = New->specific_attr_end<EnableIfAttr>(),
1602 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1603 OldE = Old->specific_attr_end<EnableIfAttr>();
1604 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1605 if (NewI == NewE || OldI == OldE)
1606 return true;
1607 llvm::FoldingSetNodeID NewID, OldID;
1608 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1609 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1610 if (NewID != OldID)
1611 return true;
1612 }
1613
1614 // At this point, it is known that the two functions have the same signature.
1615 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1616 // Don't allow overloading of destructors. (In theory we could, but it
1617 // would be a giant change to clang.)
1619 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1620 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1621 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1622 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1623 "Unexpected invalid target.");
1624
1625 // Allow overloading of functions with same signature and different CUDA
1626 // target attributes.
1627 if (NewTarget != OldTarget) {
1628 // Special case: non-constexpr function is allowed to override
1629 // constexpr virtual function
1630 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1631 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1636 return false;
1637 }
1638 return true;
1639 }
1640 }
1641 }
1642 }
1643
1644 // The signatures match; this is not an overload.
1645 return false;
1646}
1647
1649 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1650 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1651 ConsiderCudaAttrs);
1652}
1653
1655 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1656 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1657 /*UseMemberUsingDeclRules=*/false,
1658 /*ConsiderCudaAttrs=*/true,
1659 /*UseOverrideRules=*/true);
1660}
1661
1662/// Tries a user-defined conversion from From to ToType.
1663///
1664/// Produces an implicit conversion sequence for when a standard conversion
1665/// is not an option. See TryImplicitConversion for more information.
1668 bool SuppressUserConversions,
1669 AllowedExplicit AllowExplicit,
1670 bool InOverloadResolution,
1671 bool CStyle,
1672 bool AllowObjCWritebackConversion,
1673 bool AllowObjCConversionOnExplicit) {
1675
1676 if (SuppressUserConversions) {
1677 // We're not in the case above, so there is no conversion that
1678 // we can perform.
1680 return ICS;
1681 }
1682
1683 // Attempt user-defined conversion.
1684 OverloadCandidateSet Conversions(From->getExprLoc(),
1686 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1687 Conversions, AllowExplicit,
1688 AllowObjCConversionOnExplicit)) {
1689 case OR_Success:
1690 case OR_Deleted:
1691 ICS.setUserDefined();
1692 // C++ [over.ics.user]p4:
1693 // A conversion of an expression of class type to the same class
1694 // type is given Exact Match rank, and a conversion of an
1695 // expression of class type to a base class of that type is
1696 // given Conversion rank, in spite of the fact that a copy
1697 // constructor (i.e., a user-defined conversion function) is
1698 // called for those cases.
1700 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1701 QualType FromType;
1702 SourceLocation FromLoc;
1703 // C++11 [over.ics.list]p6, per DR2137:
1704 // C++17 [over.ics.list]p6:
1705 // If C is not an initializer-list constructor and the initializer list
1706 // has a single element of type cv U, where U is X or a class derived
1707 // from X, the implicit conversion sequence has Exact Match rank if U is
1708 // X, or Conversion rank if U is derived from X.
1709 bool FromListInit = false;
1710 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1711 InitList && InitList->getNumInits() == 1 &&
1713 const Expr *SingleInit = InitList->getInit(0);
1714 FromType = SingleInit->getType();
1715 FromLoc = SingleInit->getBeginLoc();
1716 FromListInit = true;
1717 } else {
1718 FromType = From->getType();
1719 FromLoc = From->getBeginLoc();
1720 }
1721 QualType FromCanon =
1723 QualType ToCanon
1725 if ((FromCanon == ToCanon ||
1726 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1727 // Turn this into a "standard" conversion sequence, so that it
1728 // gets ranked with standard conversion sequences.
1730 ICS.setStandard();
1732 ICS.Standard.setFromType(FromType);
1733 ICS.Standard.setAllToTypes(ToType);
1734 ICS.Standard.FromBracedInitList = FromListInit;
1737 if (ToCanon != FromCanon)
1739 }
1740 }
1741 break;
1742
1743 case OR_Ambiguous:
1744 ICS.setAmbiguous();
1745 ICS.Ambiguous.setFromType(From->getType());
1746 ICS.Ambiguous.setToType(ToType);
1747 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1748 Cand != Conversions.end(); ++Cand)
1749 if (Cand->Best)
1750 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1751 break;
1752
1753 // Fall through.
1756 break;
1757 }
1758
1759 return ICS;
1760}
1761
1762/// TryImplicitConversion - Attempt to perform an implicit conversion
1763/// from the given expression (Expr) to the given type (ToType). This
1764/// function returns an implicit conversion sequence that can be used
1765/// to perform the initialization. Given
1766///
1767/// void f(float f);
1768/// void g(int i) { f(i); }
1769///
1770/// this routine would produce an implicit conversion sequence to
1771/// describe the initialization of f from i, which will be a standard
1772/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1773/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1774//
1775/// Note that this routine only determines how the conversion can be
1776/// performed; it does not actually perform the conversion. As such,
1777/// it will not produce any diagnostics if no conversion is available,
1778/// but will instead return an implicit conversion sequence of kind
1779/// "BadConversion".
1780///
1781/// If @p SuppressUserConversions, then user-defined conversions are
1782/// not permitted.
1783/// If @p AllowExplicit, then explicit user-defined conversions are
1784/// permitted.
1785///
1786/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1787/// writeback conversion, which allows __autoreleasing id* parameters to
1788/// be initialized with __strong id* or __weak id* arguments.
1789static ImplicitConversionSequence
1791 bool SuppressUserConversions,
1792 AllowedExplicit AllowExplicit,
1793 bool InOverloadResolution,
1794 bool CStyle,
1795 bool AllowObjCWritebackConversion,
1796 bool AllowObjCConversionOnExplicit) {
1798 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1799 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1800 ICS.setStandard();
1801 return ICS;
1802 }
1803
1804 if (!S.getLangOpts().CPlusPlus) {
1806 return ICS;
1807 }
1808
1809 // C++ [over.ics.user]p4:
1810 // A conversion of an expression of class type to the same class
1811 // type is given Exact Match rank, and a conversion of an
1812 // expression of class type to a base class of that type is
1813 // given Conversion rank, in spite of the fact that a copy/move
1814 // constructor (i.e., a user-defined conversion function) is
1815 // called for those cases.
1816 QualType FromType = From->getType();
1817 if (ToType->isRecordType() &&
1818 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1819 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1820 ICS.setStandard();
1822 ICS.Standard.setFromType(FromType);
1823 ICS.Standard.setAllToTypes(ToType);
1824
1825 // We don't actually check at this point whether there is a valid
1826 // copy/move constructor, since overloading just assumes that it
1827 // exists. When we actually perform initialization, we'll find the
1828 // appropriate constructor to copy the returned object, if needed.
1829 ICS.Standard.CopyConstructor = nullptr;
1830
1831 // Determine whether this is considered a derived-to-base conversion.
1832 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1834
1835 return ICS;
1836 }
1837
1838 if (S.getLangOpts().HLSL) {
1839 // Handle conversion of the HLSL resource types.
1840 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1841 if (FromTy->isHLSLAttributedResourceType()) {
1842 // Attributed resource types can convert to other attributed
1843 // resource types with the same attributes and contained types,
1844 // or to __hlsl_resource_t without any attributes.
1845 bool CanConvert = false;
1846 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1847 if (ToTy->isHLSLAttributedResourceType()) {
1848 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1849 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1850 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1851 FromResType->getWrappedType()) &&
1852 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1853 FromResType->getContainedType()) &&
1854 ToResType->getAttrs() == FromResType->getAttrs())
1855 CanConvert = true;
1856 } else if (ToTy->isHLSLResourceType()) {
1857 CanConvert = true;
1858 }
1859 if (CanConvert) {
1860 ICS.setStandard();
1862 ICS.Standard.setFromType(FromType);
1863 ICS.Standard.setAllToTypes(ToType);
1864 return ICS;
1865 }
1866 }
1867 }
1868
1869 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1870 AllowExplicit, InOverloadResolution, CStyle,
1871 AllowObjCWritebackConversion,
1872 AllowObjCConversionOnExplicit);
1873}
1874
1875ImplicitConversionSequence
1877 bool SuppressUserConversions,
1878 AllowedExplicit AllowExplicit,
1879 bool InOverloadResolution,
1880 bool CStyle,
1881 bool AllowObjCWritebackConversion) {
1882 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1883 AllowExplicit, InOverloadResolution, CStyle,
1884 AllowObjCWritebackConversion,
1885 /*AllowObjCConversionOnExplicit=*/false);
1886}
1887
1889 AssignmentAction Action,
1890 bool AllowExplicit) {
1891 if (checkPlaceholderForOverload(*this, From))
1892 return ExprError();
1893
1894 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1895 bool AllowObjCWritebackConversion =
1896 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1897 Action == AssignmentAction::Sending);
1898 if (getLangOpts().ObjC)
1899 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1900 From->getType(), From);
1902 *this, From, ToType,
1903 /*SuppressUserConversions=*/false,
1904 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1905 /*InOverloadResolution=*/false,
1906 /*CStyle=*/false, AllowObjCWritebackConversion,
1907 /*AllowObjCConversionOnExplicit=*/false);
1908 return PerformImplicitConversion(From, ToType, ICS, Action);
1909}
1910
1912 QualType &ResultTy) const {
1913 bool Changed = IsFunctionConversion(FromType, ToType);
1914 if (Changed)
1915 ResultTy = ToType;
1916 return Changed;
1917}
1918
1919bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1920 if (Context.hasSameUnqualifiedType(FromType, ToType))
1921 return false;
1922
1923 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1924 // or F(t noexcept) -> F(t)
1925 // where F adds one of the following at most once:
1926 // - a pointer
1927 // - a member pointer
1928 // - a block pointer
1929 // Changes here need matching changes in FindCompositePointerType.
1930 CanQualType CanTo = Context.getCanonicalType(ToType);
1931 CanQualType CanFrom = Context.getCanonicalType(FromType);
1932 Type::TypeClass TyClass = CanTo->getTypeClass();
1933 if (TyClass != CanFrom->getTypeClass()) return false;
1934 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1935 if (TyClass == Type::Pointer) {
1936 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1937 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1938 } else if (TyClass == Type::BlockPointer) {
1939 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1940 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1941 } else if (TyClass == Type::MemberPointer) {
1942 auto ToMPT = CanTo.castAs<MemberPointerType>();
1943 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1944 // A function pointer conversion cannot change the class of the function.
1945 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1946 FromMPT->getMostRecentCXXRecordDecl()))
1947 return false;
1948 CanTo = ToMPT->getPointeeType();
1949 CanFrom = FromMPT->getPointeeType();
1950 } else {
1951 return false;
1952 }
1953
1954 TyClass = CanTo->getTypeClass();
1955 if (TyClass != CanFrom->getTypeClass()) return false;
1956 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1957 return false;
1958 }
1959
1960 const auto *FromFn = cast<FunctionType>(CanFrom);
1961 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1962
1963 const auto *ToFn = cast<FunctionType>(CanTo);
1964 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1965
1966 bool Changed = false;
1967
1968 // Drop 'noreturn' if not present in target type.
1969 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1970 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1971 Changed = true;
1972 }
1973
1974 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1975 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1976
1977 if (FromFPT && ToFPT) {
1978 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1979 QualType NewTy = Context.getFunctionType(
1980 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1981 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1982 ToFPT->hasCFIUncheckedCallee()));
1983 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1984 FromFn = FromFPT;
1985 Changed = true;
1986 }
1987 }
1988
1989 // Drop 'noexcept' if not present in target type.
1990 if (FromFPT && ToFPT) {
1991 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1992 FromFn = cast<FunctionType>(
1993 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1994 EST_None)
1995 .getTypePtr());
1996 Changed = true;
1997 }
1998
1999 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2000 // only if the ExtParameterInfo lists of the two function prototypes can be
2001 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2003 bool CanUseToFPT, CanUseFromFPT;
2004 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2005 CanUseFromFPT, NewParamInfos) &&
2006 CanUseToFPT && !CanUseFromFPT) {
2007 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2008 ExtInfo.ExtParameterInfos =
2009 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2010 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2011 FromFPT->getParamTypes(), ExtInfo);
2012 FromFn = QT->getAs<FunctionType>();
2013 Changed = true;
2014 }
2015
2016 if (Context.hasAnyFunctionEffects()) {
2017 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2018
2019 // Transparently add/drop effects; here we are concerned with
2020 // language rules/canonicalization. Adding/dropping effects is a warning.
2021 const auto FromFX = FromFPT->getFunctionEffects();
2022 const auto ToFX = ToFPT->getFunctionEffects();
2023 if (FromFX != ToFX) {
2024 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2025 ExtInfo.FunctionEffects = ToFX;
2026 QualType QT = Context.getFunctionType(
2027 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2028 FromFn = QT->getAs<FunctionType>();
2029 Changed = true;
2030 }
2031 }
2032 }
2033
2034 if (!Changed)
2035 return false;
2036
2037 assert(QualType(FromFn, 0).isCanonical());
2038 if (QualType(FromFn, 0) != CanTo) return false;
2039
2040 return true;
2041}
2042
2043/// Determine whether the conversion from FromType to ToType is a valid
2044/// floating point conversion.
2045///
2046static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2047 QualType ToType) {
2048 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2049 return false;
2050 // FIXME: disable conversions between long double, __ibm128 and __float128
2051 // if their representation is different until there is back end support
2052 // We of course allow this conversion if long double is really double.
2053
2054 // Conversions between bfloat16 and float16 are currently not supported.
2055 if ((FromType->isBFloat16Type() &&
2056 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2057 (ToType->isBFloat16Type() &&
2058 (FromType->isFloat16Type() || FromType->isHalfType())))
2059 return false;
2060
2061 // Conversions between IEEE-quad and IBM-extended semantics are not
2062 // permitted.
2063 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2064 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2065 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2066 &ToSem == &llvm::APFloat::IEEEquad()) ||
2067 (&FromSem == &llvm::APFloat::IEEEquad() &&
2068 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2069 return false;
2070 return true;
2071}
2072
2074 QualType ToType,
2076 Expr *From) {
2077 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2078 return true;
2079
2080 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2082 return true;
2083 }
2084
2085 if (IsFloatingPointConversion(S, FromType, ToType)) {
2087 return true;
2088 }
2089
2090 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2092 return true;
2093 }
2094
2095 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2097 ToType->isRealFloatingType())) {
2099 return true;
2100 }
2101
2102 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2104 return true;
2105 }
2106
2107 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2108 ToType->isIntegralType(S.Context)) {
2110 return true;
2111 }
2112
2113 return false;
2114}
2115
2116/// Determine whether the conversion from FromType to ToType is a valid
2117/// matrix conversion.
2118///
2119/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2120/// conversion.
2121static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2123 ImplicitConversionKind &ElConv, Expr *From,
2124 bool InOverloadResolution, bool CStyle) {
2125 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2126 if (!S.getLangOpts().HLSL)
2127 return false;
2128
2129 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2130 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2131
2132 // If both arguments are matrix, handle possible matrix truncation and
2133 // element conversion.
2134 if (ToMatrixType && FromMatrixType) {
2135 unsigned FromCols = FromMatrixType->getNumColumns();
2136 unsigned ToCols = ToMatrixType->getNumColumns();
2137 if (FromCols < ToCols)
2138 return false;
2139
2140 unsigned FromRows = FromMatrixType->getNumRows();
2141 unsigned ToRows = ToMatrixType->getNumRows();
2142 if (FromRows < ToRows)
2143 return false;
2144
2145 if (FromRows == ToRows && FromCols == ToCols)
2146 ElConv = ICK_Identity;
2147 else
2149
2150 QualType FromElTy = FromMatrixType->getElementType();
2151 QualType ToElTy = ToMatrixType->getElementType();
2152 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2153 return true;
2154 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2155 }
2156
2157 // Matrix splat from any arithmetic type to a matrix.
2158 if (ToMatrixType && FromType->isArithmeticType()) {
2159 ElConv = ICK_HLSL_Matrix_Splat;
2160 QualType ToElTy = ToMatrixType->getElementType();
2161 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2162 }
2163 if (FromMatrixType && !ToMatrixType) {
2165 QualType FromElTy = FromMatrixType->getElementType();
2166 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2167 return true;
2168 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2169 }
2170
2171 return false;
2172}
2173
2174/// Determine whether the conversion from FromType to ToType is a valid
2175/// vector conversion.
2176///
2177/// \param ICK Will be set to the vector conversion kind, if this is a vector
2178/// conversion.
2179static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2181 ImplicitConversionKind &ElConv, Expr *From,
2182 bool InOverloadResolution, bool CStyle) {
2183 // We need at least one of these types to be a vector type to have a vector
2184 // conversion.
2185 if (!ToType->isVectorType() && !FromType->isVectorType())
2186 return false;
2187
2188 // Identical types require no conversions.
2189 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2190 return false;
2191
2192 // HLSL allows implicit truncation of vector types.
2193 if (S.getLangOpts().HLSL) {
2194 auto *ToExtType = ToType->getAs<ExtVectorType>();
2195 auto *FromExtType = FromType->getAs<ExtVectorType>();
2196
2197 // If both arguments are vectors, handle possible vector truncation and
2198 // element conversion.
2199 if (ToExtType && FromExtType) {
2200 unsigned FromElts = FromExtType->getNumElements();
2201 unsigned ToElts = ToExtType->getNumElements();
2202 if (FromElts < ToElts)
2203 return false;
2204 if (FromElts == ToElts)
2205 ElConv = ICK_Identity;
2206 else
2208
2209 QualType FromElTy = FromExtType->getElementType();
2210 QualType ToElTy = ToExtType->getElementType();
2211 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2212 return true;
2213 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2214 }
2215 if (FromExtType && !ToExtType) {
2217 QualType FromElTy = FromExtType->getElementType();
2218 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2219 return true;
2220 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2221 }
2222 // Fallthrough for the case where ToType is a vector and FromType is not.
2223 }
2224
2225 // There are no conversions between extended vector types, only identity.
2226 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2227 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2228 // Implicit conversions require the same number of elements.
2229 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2230 return false;
2231
2232 // Permit implicit conversions from integral values to boolean vectors.
2233 if (ToType->isExtVectorBoolType() &&
2234 FromExtType->getElementType()->isIntegerType()) {
2236 return true;
2237 }
2238 // There are no other conversions between extended vector types.
2239 return false;
2240 }
2241
2242 // Vector splat from any arithmetic type to a vector.
2243 if (FromType->isArithmeticType()) {
2244 if (S.getLangOpts().HLSL) {
2245 ElConv = ICK_HLSL_Vector_Splat;
2246 QualType ToElTy = ToExtType->getElementType();
2247 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2248 From);
2249 }
2250 ICK = ICK_Vector_Splat;
2251 return true;
2252 }
2253 }
2254
2255 if (ToType->isSVESizelessBuiltinType() ||
2256 FromType->isSVESizelessBuiltinType())
2257 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2258 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2260 return true;
2261 }
2262
2263 if (ToType->isRVVSizelessBuiltinType() ||
2264 FromType->isRVVSizelessBuiltinType())
2265 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2266 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2268 return true;
2269 }
2270
2271 // We can perform the conversion between vector types in the following cases:
2272 // 1)vector types are equivalent AltiVec and GCC vector types
2273 // 2)lax vector conversions are permitted and the vector types are of the
2274 // same size
2275 // 3)the destination type does not have the ARM MVE strict-polymorphism
2276 // attribute, which inhibits lax vector conversion for overload resolution
2277 // only
2278 if (ToType->isVectorType() && FromType->isVectorType()) {
2279 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2280 (S.isLaxVectorConversion(FromType, ToType) &&
2281 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2282 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2283 S.isLaxVectorConversion(FromType, ToType) &&
2284 S.anyAltivecTypes(FromType, ToType) &&
2285 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2286 !InOverloadResolution && !CStyle) {
2287 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2288 << FromType << ToType;
2289 }
2291 return true;
2292 }
2293 }
2294
2295 return false;
2296}
2297
2298static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2299 bool InOverloadResolution,
2300 StandardConversionSequence &SCS,
2301 bool CStyle);
2302
2303static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2304 QualType ToType,
2305 bool InOverloadResolution,
2306 StandardConversionSequence &SCS,
2307 bool CStyle);
2308
2309/// IsStandardConversion - Determines whether there is a standard
2310/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2311/// expression From to the type ToType. Standard conversion sequences
2312/// only consider non-class types; for conversions that involve class
2313/// types, use TryImplicitConversion. If a conversion exists, SCS will
2314/// contain the standard conversion sequence required to perform this
2315/// conversion and this routine will return true. Otherwise, this
2316/// routine will return false and the value of SCS is unspecified.
2317static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2318 bool InOverloadResolution,
2320 bool CStyle,
2321 bool AllowObjCWritebackConversion) {
2322 QualType FromType = From->getType();
2323
2324 // Standard conversions (C++ [conv])
2326 SCS.IncompatibleObjC = false;
2327 SCS.setFromType(FromType);
2328 SCS.CopyConstructor = nullptr;
2329
2330 // There are no standard conversions for class types in C++, so
2331 // abort early. When overloading in C, however, we do permit them.
2332 if (S.getLangOpts().CPlusPlus &&
2333 (FromType->isRecordType() || ToType->isRecordType()))
2334 return false;
2335
2336 // The first conversion can be an lvalue-to-rvalue conversion,
2337 // array-to-pointer conversion, or function-to-pointer conversion
2338 // (C++ 4p1).
2339
2340 if (FromType == S.Context.OverloadTy) {
2341 DeclAccessPair AccessPair;
2342 if (FunctionDecl *Fn
2343 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2344 AccessPair)) {
2345 // We were able to resolve the address of the overloaded function,
2346 // so we can convert to the type of that function.
2347 FromType = Fn->getType();
2348 SCS.setFromType(FromType);
2349
2350 // we can sometimes resolve &foo<int> regardless of ToType, so check
2351 // if the type matches (identity) or we are converting to bool
2353 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2354 // if the function type matches except for [[noreturn]], it's ok
2355 if (!S.IsFunctionConversion(FromType,
2357 // otherwise, only a boolean conversion is standard
2358 if (!ToType->isBooleanType())
2359 return false;
2360 }
2361
2362 // Check if the "from" expression is taking the address of an overloaded
2363 // function and recompute the FromType accordingly. Take advantage of the
2364 // fact that non-static member functions *must* have such an address-of
2365 // expression.
2366 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2367 if (Method && !Method->isStatic() &&
2368 !Method->isExplicitObjectMemberFunction()) {
2369 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2370 "Non-unary operator on non-static member address");
2371 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2372 == UO_AddrOf &&
2373 "Non-address-of operator on non-static member address");
2374 FromType = S.Context.getMemberPointerType(
2375 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2376 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2377 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2378 UO_AddrOf &&
2379 "Non-address-of operator for overloaded function expression");
2380 FromType = S.Context.getPointerType(FromType);
2381 }
2382 } else {
2383 return false;
2384 }
2385 }
2386
2387 bool argIsLValue = From->isGLValue();
2388 // To handle conversion from ArrayParameterType to ConstantArrayType
2389 // this block must be above the one below because Array parameters
2390 // do not decay and when handling HLSLOutArgExprs and
2391 // the From expression is an LValue.
2392 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2393 ToType->isConstantArrayType()) {
2394 // HLSL constant array parameters do not decay, so if the argument is a
2395 // constant array and the parameter is an ArrayParameterType we have special
2396 // handling here.
2397 if (ToType->isArrayParameterType()) {
2398 FromType = S.Context.getArrayParameterType(FromType);
2399 } else if (FromType->isArrayParameterType()) {
2400 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2401 FromType = APT->getConstantArrayType(S.Context);
2402 }
2403
2405
2406 // Don't consider qualifiers, which include things like address spaces
2407 if (FromType.getCanonicalType().getUnqualifiedType() !=
2409 return false;
2410
2411 SCS.setAllToTypes(ToType);
2412 return true;
2413 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2414 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2415 // Lvalue-to-rvalue conversion (C++11 4.1):
2416 // A glvalue (3.10) of a non-function, non-array type T can
2417 // be converted to a prvalue.
2418
2420
2421 // C11 6.3.2.1p2:
2422 // ... if the lvalue has atomic type, the value has the non-atomic version
2423 // of the type of the lvalue ...
2424 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2425 FromType = Atomic->getValueType();
2426
2427 // If T is a non-class type, the type of the rvalue is the
2428 // cv-unqualified version of T. Otherwise, the type of the rvalue
2429 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2430 // just strip the qualifiers because they don't matter.
2431 FromType = FromType.getUnqualifiedType();
2432 } else if (FromType->isArrayType()) {
2433 // Array-to-pointer conversion (C++ 4.2)
2435
2436 // An lvalue or rvalue of type "array of N T" or "array of unknown
2437 // bound of T" can be converted to an rvalue of type "pointer to
2438 // T" (C++ 4.2p1).
2439 FromType = S.Context.getArrayDecayedType(FromType);
2440
2441 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2442 // This conversion is deprecated in C++03 (D.4)
2444
2445 // For the purpose of ranking in overload resolution
2446 // (13.3.3.1.1), this conversion is considered an
2447 // array-to-pointer conversion followed by a qualification
2448 // conversion (4.4). (C++ 4.2p2)
2449 SCS.Second = ICK_Identity;
2452 SCS.setAllToTypes(FromType);
2453 return true;
2454 }
2455 } else if (FromType->isFunctionType() && argIsLValue) {
2456 // Function-to-pointer conversion (C++ 4.3).
2458
2459 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2460 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2462 return false;
2463
2464 // An lvalue of function type T can be converted to an rvalue of
2465 // type "pointer to T." The result is a pointer to the
2466 // function. (C++ 4.3p1).
2467 FromType = S.Context.getPointerType(FromType);
2468 } else {
2469 // We don't require any conversions for the first step.
2470 SCS.First = ICK_Identity;
2471 }
2472 SCS.setToType(0, FromType);
2473
2474 // The second conversion can be an integral promotion, floating
2475 // point promotion, integral conversion, floating point conversion,
2476 // floating-integral conversion, pointer conversion,
2477 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2478 // For overloading in C, this can also be a "compatible-type"
2479 // conversion.
2480 bool IncompatibleObjC = false;
2482 ImplicitConversionKind DimensionICK = ICK_Identity;
2483 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2484 // The unqualified versions of the types are the same: there's no
2485 // conversion to do.
2486 SCS.Second = ICK_Identity;
2487 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2488 // Integral promotion (C++ 4.5).
2490 FromType = ToType.getUnqualifiedType();
2491 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2492 // Floating point promotion (C++ 4.6).
2494 FromType = ToType.getUnqualifiedType();
2495 } else if (S.IsComplexPromotion(FromType, ToType)) {
2496 // Complex promotion (Clang extension)
2498 FromType = ToType.getUnqualifiedType();
2499 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2500 // OverflowBehaviorType promotions
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2504 // OverflowBehaviorType conversions
2506 FromType = ToType.getUnqualifiedType();
2507 } else if (ToType->isBooleanType() &&
2508 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2509 FromType->isBlockPointerType() ||
2510 FromType->isMemberPointerType())) {
2511 // Boolean conversions (C++ 4.12).
2513 FromType = S.Context.BoolTy;
2514 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2515 ToType->isIntegralType(S.Context)) {
2516 // Integral conversions (C++ 4.7).
2518 FromType = ToType.getUnqualifiedType();
2519 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2520 // Complex conversions (C99 6.3.1.6)
2522 FromType = ToType.getUnqualifiedType();
2523 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2524 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2525 // Complex-real conversions (C99 6.3.1.7)
2527 FromType = ToType.getUnqualifiedType();
2528 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2529 // Floating point conversions (C++ 4.8).
2531 FromType = ToType.getUnqualifiedType();
2532 } else if ((FromType->isRealFloatingType() &&
2533 ToType->isIntegralType(S.Context)) ||
2535 ToType->isRealFloatingType())) {
2536
2537 // Floating-integral conversions (C++ 4.9).
2539 FromType = ToType.getUnqualifiedType();
2540 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2542 } else if (AllowObjCWritebackConversion &&
2543 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2546 FromType, IncompatibleObjC)) {
2547 // Pointer conversions (C++ 4.10).
2549 SCS.IncompatibleObjC = IncompatibleObjC;
2550 FromType = FromType.getUnqualifiedType();
2551 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2552 InOverloadResolution, FromType)) {
2553 // Pointer to member conversions (4.11).
2555 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2556 From, InOverloadResolution, CStyle)) {
2557 SCS.Second = SecondICK;
2558 SCS.Dimension = DimensionICK;
2559 FromType = ToType.getUnqualifiedType();
2560 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2561 From, InOverloadResolution, CStyle)) {
2562 SCS.Second = SecondICK;
2563 SCS.Dimension = DimensionICK;
2564 FromType = ToType.getUnqualifiedType();
2565 } else if (!S.getLangOpts().CPlusPlus &&
2566 S.Context.typesAreCompatible(ToType, FromType)) {
2567 // Compatible conversions (Clang extension for C function overloading)
2569 FromType = ToType.getUnqualifiedType();
2571 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2573 FromType = ToType;
2574 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2575 CStyle)) {
2576 // tryAtomicConversion has updated the standard conversion sequence
2577 // appropriately.
2578 return true;
2580 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2581 return true;
2582 } else if (ToType->isEventT() &&
2584 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2586 FromType = ToType;
2587 } else if (ToType->isQueueT() &&
2589 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2591 FromType = ToType;
2592 } else if (ToType->isSamplerT() &&
2595 FromType = ToType;
2596 } else if ((ToType->isFixedPointType() &&
2597 FromType->isConvertibleToFixedPointType()) ||
2598 (FromType->isFixedPointType() &&
2599 ToType->isConvertibleToFixedPointType())) {
2601 FromType = ToType;
2602 } else {
2603 // No second conversion required.
2604 SCS.Second = ICK_Identity;
2605 }
2606 SCS.setToType(1, FromType);
2607
2608 // The third conversion can be a function pointer conversion or a
2609 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2610 bool ObjCLifetimeConversion;
2611 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2612 // Function pointer conversions (removing 'noexcept') including removal of
2613 // 'noreturn' (Clang extension).
2615 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2616 ObjCLifetimeConversion)) {
2618 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2619 FromType = ToType;
2620 } else {
2621 // No conversion required
2622 SCS.Third = ICK_Identity;
2623 }
2624
2625 // C++ [over.best.ics]p6:
2626 // [...] Any difference in top-level cv-qualification is
2627 // subsumed by the initialization itself and does not constitute
2628 // a conversion. [...]
2629 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2630 QualType CanonTo = S.Context.getCanonicalType(ToType);
2631 if (CanonFrom.getLocalUnqualifiedType()
2632 == CanonTo.getLocalUnqualifiedType() &&
2633 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2634 FromType = ToType;
2635 CanonFrom = CanonTo;
2636 }
2637
2638 SCS.setToType(2, FromType);
2639
2640 if (CanonFrom == CanonTo)
2641 return true;
2642
2643 // If we have not converted the argument type to the parameter type,
2644 // this is a bad conversion sequence, unless we're resolving an overload in C.
2645 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2646 return false;
2647
2648 ExprResult ER = ExprResult{From};
2649 AssignConvertType Conv =
2651 /*Diagnose=*/false,
2652 /*DiagnoseCFAudited=*/false,
2653 /*ConvertRHS=*/false);
2654 ImplicitConversionKind SecondConv;
2655 switch (Conv) {
2657 case AssignConvertType::
2658 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2659 SecondConv = ICK_C_Only_Conversion;
2660 break;
2661 // For our purposes, discarding qualifiers is just as bad as using an
2662 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2663 // qualifiers, as well.
2668 break;
2669 default:
2670 return false;
2671 }
2672
2673 // First can only be an lvalue conversion, so we pretend that this was the
2674 // second conversion. First should already be valid from earlier in the
2675 // function.
2676 SCS.Second = SecondConv;
2677 SCS.setToType(1, ToType);
2678
2679 // Third is Identity, because Second should rank us worse than any other
2680 // conversion. This could also be ICK_Qualification, but it's simpler to just
2681 // lump everything in with the second conversion, and we don't gain anything
2682 // from making this ICK_Qualification.
2683 SCS.Third = ICK_Identity;
2684 SCS.setToType(2, ToType);
2685 return true;
2686}
2687
2688static bool
2690 QualType &ToType,
2691 bool InOverloadResolution,
2693 bool CStyle) {
2694
2695 const RecordType *UT = ToType->getAsUnionType();
2696 if (!UT)
2697 return false;
2698 // The field to initialize within the transparent union.
2699 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2700 if (!UD->hasAttr<TransparentUnionAttr>())
2701 return false;
2702 // It's compatible if the expression matches any of the fields.
2703 for (const auto *it : UD->fields()) {
2704 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2705 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2706 ToType = it->getType();
2707 return true;
2708 }
2709 }
2710 return false;
2711}
2712
2713bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2714 const BuiltinType *To = ToType->getAs<BuiltinType>();
2715 // All integers are built-in.
2716 if (!To) {
2717 return false;
2718 }
2719
2720 // An rvalue of type char, signed char, unsigned char, short int, or
2721 // unsigned short int can be converted to an rvalue of type int if
2722 // int can represent all the values of the source type; otherwise,
2723 // the source rvalue can be converted to an rvalue of type unsigned
2724 // int (C++ 4.5p1).
2725 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2726 !FromType->isEnumeralType()) {
2727 if ( // We can promote any signed, promotable integer type to an int
2728 (FromType->isSignedIntegerType() ||
2729 // We can promote any unsigned integer type whose size is
2730 // less than int to an int.
2731 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2732 return To->getKind() == BuiltinType::Int;
2733 }
2734
2735 return To->getKind() == BuiltinType::UInt;
2736 }
2737
2738 // C++11 [conv.prom]p3:
2739 // A prvalue of an unscoped enumeration type whose underlying type is not
2740 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2741 // following types that can represent all the values of the enumeration
2742 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2743 // unsigned int, long int, unsigned long int, long long int, or unsigned
2744 // long long int. If none of the types in that list can represent all the
2745 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2746 // type can be converted to an rvalue a prvalue of the extended integer type
2747 // with lowest integer conversion rank (4.13) greater than the rank of long
2748 // long in which all the values of the enumeration can be represented. If
2749 // there are two such extended types, the signed one is chosen.
2750 // C++11 [conv.prom]p4:
2751 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2752 // can be converted to a prvalue of its underlying type. Moreover, if
2753 // integral promotion can be applied to its underlying type, a prvalue of an
2754 // unscoped enumeration type whose underlying type is fixed can also be
2755 // converted to a prvalue of the promoted underlying type.
2756 if (const auto *FromED = FromType->getAsEnumDecl()) {
2757 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2758 // provided for a scoped enumeration.
2759 if (FromED->isScoped())
2760 return false;
2761
2762 // We can perform an integral promotion to the underlying type of the enum,
2763 // even if that's not the promoted type. Note that the check for promoting
2764 // the underlying type is based on the type alone, and does not consider
2765 // the bitfield-ness of the actual source expression.
2766 if (FromED->isFixed()) {
2767 QualType Underlying = FromED->getIntegerType();
2768 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2769 IsIntegralPromotion(nullptr, Underlying, ToType);
2770 }
2771
2772 // We have already pre-calculated the promotion type, so this is trivial.
2773 if (ToType->isIntegerType() &&
2774 isCompleteType(From->getBeginLoc(), FromType))
2775 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2776
2777 // C++ [conv.prom]p5:
2778 // If the bit-field has an enumerated type, it is treated as any other
2779 // value of that type for promotion purposes.
2780 //
2781 // ... so do not fall through into the bit-field checks below in C++.
2782 if (getLangOpts().CPlusPlus)
2783 return false;
2784 }
2785
2786 // C++0x [conv.prom]p2:
2787 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2788 // to an rvalue a prvalue of the first of the following types that can
2789 // represent all the values of its underlying type: int, unsigned int,
2790 // long int, unsigned long int, long long int, or unsigned long long int.
2791 // If none of the types in that list can represent all the values of its
2792 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2793 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2794 // type.
2795 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2796 ToType->isIntegerType()) {
2797 // Determine whether the type we're converting from is signed or
2798 // unsigned.
2799 bool FromIsSigned = FromType->isSignedIntegerType();
2800 uint64_t FromSize = Context.getTypeSize(FromType);
2801
2802 // The types we'll try to promote to, in the appropriate
2803 // order. Try each of these types.
2804 QualType PromoteTypes[6] = {
2805 Context.IntTy, Context.UnsignedIntTy,
2806 Context.LongTy, Context.UnsignedLongTy ,
2807 Context.LongLongTy, Context.UnsignedLongLongTy
2808 };
2809 for (int Idx = 0; Idx < 6; ++Idx) {
2810 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2811 if (FromSize < ToSize ||
2812 (FromSize == ToSize &&
2813 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2814 // We found the type that we can promote to. If this is the
2815 // type we wanted, we have a promotion. Otherwise, no
2816 // promotion.
2817 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2818 }
2819 }
2820 }
2821
2822 // An rvalue for an integral bit-field (9.6) can be converted to an
2823 // rvalue of type int if int can represent all the values of the
2824 // bit-field; otherwise, it can be converted to unsigned int if
2825 // unsigned int can represent all the values of the bit-field. If
2826 // the bit-field is larger yet, no integral promotion applies to
2827 // it. If the bit-field has an enumerated type, it is treated as any
2828 // other value of that type for promotion purposes (C++ 4.5p3).
2829 // FIXME: We should delay checking of bit-fields until we actually perform the
2830 // conversion.
2831 //
2832 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2833 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2834 // bit-fields and those whose underlying type is larger than int) for GCC
2835 // compatibility.
2836 if (From) {
2837 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2838 std::optional<llvm::APSInt> BitWidth;
2839 if (FromType->isIntegralType(Context) &&
2840 (BitWidth =
2841 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2842 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2843 ToSize = Context.getTypeSize(ToType);
2844
2845 // Are we promoting to an int from a bitfield that fits in an int?
2846 if (*BitWidth < ToSize ||
2847 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2848 return To->getKind() == BuiltinType::Int;
2849 }
2850
2851 // Are we promoting to an unsigned int from an unsigned bitfield
2852 // that fits into an unsigned int?
2853 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2854 return To->getKind() == BuiltinType::UInt;
2855 }
2856
2857 return false;
2858 }
2859 }
2860 }
2861
2862 // An rvalue of type bool can be converted to an rvalue of type int,
2863 // with false becoming zero and true becoming one (C++ 4.5p4).
2864 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2865 return true;
2866 }
2867
2868 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2869 // integral type.
2870 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2871 ToType->isIntegerType())
2872 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2873
2874 return false;
2875}
2876
2878 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2879 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2880 /// An rvalue of type float can be converted to an rvalue of type
2881 /// double. (C++ 4.6p1).
2882 if (FromBuiltin->getKind() == BuiltinType::Float &&
2883 ToBuiltin->getKind() == BuiltinType::Double)
2884 return true;
2885
2886 // C99 6.3.1.5p1:
2887 // When a float is promoted to double or long double, or a
2888 // double is promoted to long double [...].
2889 if (!getLangOpts().CPlusPlus &&
2890 (FromBuiltin->getKind() == BuiltinType::Float ||
2891 FromBuiltin->getKind() == BuiltinType::Double) &&
2892 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2893 ToBuiltin->getKind() == BuiltinType::Float128 ||
2894 ToBuiltin->getKind() == BuiltinType::Ibm128))
2895 return true;
2896
2897 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2898 // or not native half types are enabled.
2899 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2900 (ToBuiltin->getKind() == BuiltinType::Float ||
2901 ToBuiltin->getKind() == BuiltinType::Double))
2902 return true;
2903
2904 // Half can be promoted to float.
2905 if (!getLangOpts().NativeHalfType &&
2906 FromBuiltin->getKind() == BuiltinType::Half &&
2907 ToBuiltin->getKind() == BuiltinType::Float)
2908 return true;
2909 }
2910
2911 return false;
2912}
2913
2915 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2916 if (!FromComplex)
2917 return false;
2918
2919 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2920 if (!ToComplex)
2921 return false;
2922
2923 return IsFloatingPointPromotion(FromComplex->getElementType(),
2924 ToComplex->getElementType()) ||
2925 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2926 ToComplex->getElementType());
2927}
2928
2930 if (!getLangOpts().OverflowBehaviorTypes)
2931 return false;
2932
2933 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2934 return false;
2935
2936 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2937}
2938
2940 QualType ToType) {
2941 if (!getLangOpts().OverflowBehaviorTypes)
2942 return false;
2943
2944 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2945 if (ToType->isBooleanType())
2946 return false;
2947 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2948 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2949 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2950 if (ToED->isScoped())
2951 return false;
2952 }
2953 return true;
2954 }
2955
2956 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2957 return true;
2958
2959 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2960 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2961
2962 return false;
2963}
2964
2965/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2966/// the pointer type FromPtr to a pointer to type ToPointee, with the
2967/// same type qualifiers as FromPtr has on its pointee type. ToType,
2968/// if non-empty, will be a pointer to ToType that may or may not have
2969/// the right set of qualifiers on its pointee.
2970///
2971static QualType
2973 QualType ToPointee, QualType ToType,
2974 ASTContext &Context,
2975 bool StripObjCLifetime = false) {
2976 assert((FromPtr->getTypeClass() == Type::Pointer ||
2977 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2978 "Invalid similarly-qualified pointer type");
2979
2980 /// Conversions to 'id' subsume cv-qualifier conversions.
2981 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2982 return ToType.getUnqualifiedType();
2983
2984 QualType CanonFromPointee
2985 = Context.getCanonicalType(FromPtr->getPointeeType());
2986 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2987 Qualifiers Quals = CanonFromPointee.getQualifiers();
2988
2989 if (StripObjCLifetime)
2990 Quals.removeObjCLifetime();
2991
2992 // Exact qualifier match -> return the pointer type we're converting to.
2993 if (CanonToPointee.getLocalQualifiers() == Quals) {
2994 // ToType is exactly what we need. Return it.
2995 if (!ToType.isNull())
2996 return ToType.getUnqualifiedType();
2997
2998 // Build a pointer to ToPointee. It has the right qualifiers
2999 // already.
3000 if (isa<ObjCObjectPointerType>(ToType))
3001 return Context.getObjCObjectPointerType(ToPointee);
3002 return Context.getPointerType(ToPointee);
3003 }
3004
3005 // Just build a canonical type that has the right qualifiers.
3006 QualType QualifiedCanonToPointee
3007 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3008
3009 if (isa<ObjCObjectPointerType>(ToType))
3010 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3011 return Context.getPointerType(QualifiedCanonToPointee);
3012}
3013
3015 bool InOverloadResolution,
3016 ASTContext &Context) {
3017 // Handle value-dependent integral null pointer constants correctly.
3018 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3019 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3021 return !InOverloadResolution;
3022
3023 return Expr->isNullPointerConstant(Context,
3024 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3026}
3027
3029 bool InOverloadResolution,
3030 QualType& ConvertedType,
3031 bool &IncompatibleObjC) {
3032 IncompatibleObjC = false;
3033 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3034 IncompatibleObjC))
3035 return true;
3036
3037 // Conversion from a null pointer constant to any Objective-C pointer type.
3038 if (ToType->isObjCObjectPointerType() &&
3039 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3040 ConvertedType = ToType;
3041 return true;
3042 }
3043
3044 // Blocks: Block pointers can be converted to void*.
3045 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3046 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3047 ConvertedType = ToType;
3048 return true;
3049 }
3050 // Blocks: A null pointer constant can be converted to a block
3051 // pointer type.
3052 if (ToType->isBlockPointerType() &&
3053 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3054 ConvertedType = ToType;
3055 return true;
3056 }
3057
3058 // If the left-hand-side is nullptr_t, the right side can be a null
3059 // pointer constant.
3060 if (ToType->isNullPtrType() &&
3061 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3062 ConvertedType = ToType;
3063 return true;
3064 }
3065
3066 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3067 if (!ToTypePtr)
3068 return false;
3069
3070 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3071 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3072 ConvertedType = ToType;
3073 return true;
3074 }
3075
3076 // Beyond this point, both types need to be pointers
3077 // , including objective-c pointers.
3078 QualType ToPointeeType = ToTypePtr->getPointeeType();
3079 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3080 !getLangOpts().ObjCAutoRefCount) {
3081 ConvertedType = BuildSimilarlyQualifiedPointerType(
3082 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3083 Context);
3084 return true;
3085 }
3086 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3087 if (!FromTypePtr)
3088 return false;
3089
3090 QualType FromPointeeType = FromTypePtr->getPointeeType();
3091
3092 // If the unqualified pointee types are the same, this can't be a
3093 // pointer conversion, so don't do all of the work below.
3094 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3095 return false;
3096
3097 // An rvalue of type "pointer to cv T," where T is an object type,
3098 // can be converted to an rvalue of type "pointer to cv void" (C++
3099 // 4.10p2).
3100 if (FromPointeeType->isIncompleteOrObjectType() &&
3101 ToPointeeType->isVoidType()) {
3102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3103 ToPointeeType,
3104 ToType, Context,
3105 /*StripObjCLifetime=*/true);
3106 return true;
3107 }
3108
3109 // MSVC allows implicit function to void* type conversion.
3110 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3111 ToPointeeType->isVoidType()) {
3112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3113 ToPointeeType,
3114 ToType, Context);
3115 return true;
3116 }
3117
3118 // When we're overloading in C, we allow a special kind of pointer
3119 // conversion for compatible-but-not-identical pointee types.
3120 if (!getLangOpts().CPlusPlus &&
3121 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3122 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3123 ToPointeeType,
3124 ToType, Context);
3125 return true;
3126 }
3127
3128 // C++ [conv.ptr]p3:
3129 //
3130 // An rvalue of type "pointer to cv D," where D is a class type,
3131 // can be converted to an rvalue of type "pointer to cv B," where
3132 // B is a base class (clause 10) of D. If B is an inaccessible
3133 // (clause 11) or ambiguous (10.2) base class of D, a program that
3134 // necessitates this conversion is ill-formed. The result of the
3135 // conversion is a pointer to the base class sub-object of the
3136 // derived class object. The null pointer value is converted to
3137 // the null pointer value of the destination type.
3138 //
3139 // Note that we do not check for ambiguity or inaccessibility
3140 // here. That is handled by CheckPointerConversion.
3141 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3142 ToPointeeType->isRecordType() &&
3143 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3144 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3146 ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3152 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3153 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3154 ToPointeeType,
3155 ToType, Context);
3156 return true;
3157 }
3158
3159 return false;
3160}
3161
3162/// Adopt the given qualifiers for the given type.
3164 Qualifiers TQs = T.getQualifiers();
3165
3166 // Check whether qualifiers already match.
3167 if (TQs == Qs)
3168 return T;
3169
3170 if (Qs.compatiblyIncludes(TQs, Context))
3171 return Context.getQualifiedType(T, Qs);
3172
3173 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3174}
3175
3177 QualType& ConvertedType,
3178 bool &IncompatibleObjC) {
3179 if (!getLangOpts().ObjC)
3180 return false;
3181
3182 // The set of qualifiers on the type we're converting from.
3183 Qualifiers FromQualifiers = FromType.getQualifiers();
3184
3185 // First, we handle all conversions on ObjC object pointer types.
3186 const ObjCObjectPointerType* ToObjCPtr =
3187 ToType->getAs<ObjCObjectPointerType>();
3188 const ObjCObjectPointerType *FromObjCPtr =
3189 FromType->getAs<ObjCObjectPointerType>();
3190
3191 if (ToObjCPtr && FromObjCPtr) {
3192 // If the pointee types are the same (ignoring qualifications),
3193 // then this is not a pointer conversion.
3194 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3195 FromObjCPtr->getPointeeType()))
3196 return false;
3197
3198 // Conversion between Objective-C pointers.
3199 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3200 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3201 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3202 if (getLangOpts().CPlusPlus && LHS && RHS &&
3204 FromObjCPtr->getPointeeType(), getASTContext()))
3205 return false;
3206 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3207 ToObjCPtr->getPointeeType(),
3208 ToType, Context);
3209 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3210 return true;
3211 }
3212
3213 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3214 // Okay: this is some kind of implicit downcast of Objective-C
3215 // interfaces, which is permitted. However, we're going to
3216 // complain about it.
3217 IncompatibleObjC = true;
3218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3219 ToObjCPtr->getPointeeType(),
3220 ToType, Context);
3221 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3222 return true;
3223 }
3224 }
3225 // Beyond this point, both types need to be C pointers or block pointers.
3226 QualType ToPointeeType;
3227 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3228 ToPointeeType = ToCPtr->getPointeeType();
3229 else if (const BlockPointerType *ToBlockPtr =
3230 ToType->getAs<BlockPointerType>()) {
3231 // Objective C++: We're able to convert from a pointer to any object
3232 // to a block pointer type.
3233 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3234 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3235 return true;
3236 }
3237 ToPointeeType = ToBlockPtr->getPointeeType();
3238 }
3239 else if (FromType->getAs<BlockPointerType>() &&
3240 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3241 // Objective C++: We're able to convert from a block pointer type to a
3242 // pointer to any object.
3243 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3244 return true;
3245 }
3246 else
3247 return false;
3248
3249 QualType FromPointeeType;
3250 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3251 FromPointeeType = FromCPtr->getPointeeType();
3252 else if (const BlockPointerType *FromBlockPtr =
3253 FromType->getAs<BlockPointerType>())
3254 FromPointeeType = FromBlockPtr->getPointeeType();
3255 else
3256 return false;
3257
3258 // If we have pointers to pointers, recursively check whether this
3259 // is an Objective-C conversion.
3260 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3261 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3262 IncompatibleObjC)) {
3263 // We always complain about this conversion.
3264 IncompatibleObjC = true;
3265 ConvertedType = Context.getPointerType(ConvertedType);
3266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3267 return true;
3268 }
3269 // Allow conversion of pointee being objective-c pointer to another one;
3270 // as in I* to id.
3271 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3272 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3273 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3274 IncompatibleObjC)) {
3275
3276 ConvertedType = Context.getPointerType(ConvertedType);
3277 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3278 return true;
3279 }
3280
3281 // If we have pointers to functions or blocks, check whether the only
3282 // differences in the argument and result types are in Objective-C
3283 // pointer conversions. If so, we permit the conversion (but
3284 // complain about it).
3285 const FunctionProtoType *FromFunctionType
3286 = FromPointeeType->getAs<FunctionProtoType>();
3287 const FunctionProtoType *ToFunctionType
3288 = ToPointeeType->getAs<FunctionProtoType>();
3289 if (FromFunctionType && ToFunctionType) {
3290 // If the function types are exactly the same, this isn't an
3291 // Objective-C pointer conversion.
3292 if (Context.getCanonicalType(FromPointeeType)
3293 == Context.getCanonicalType(ToPointeeType))
3294 return false;
3295
3296 // Perform the quick checks that will tell us whether these
3297 // function types are obviously different.
3298 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3299 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3300 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3301 return false;
3302
3303 bool HasObjCConversion = false;
3304 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3305 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3306 // Okay, the types match exactly. Nothing to do.
3307 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3308 ToFunctionType->getReturnType(),
3309 ConvertedType, IncompatibleObjC)) {
3310 // Okay, we have an Objective-C pointer conversion.
3311 HasObjCConversion = true;
3312 } else {
3313 // Function types are too different. Abort.
3314 return false;
3315 }
3316
3317 // Check argument types.
3318 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3319 ArgIdx != NumArgs; ++ArgIdx) {
3320 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3321 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3322 if (Context.getCanonicalType(FromArgType)
3323 == Context.getCanonicalType(ToArgType)) {
3324 // Okay, the types match exactly. Nothing to do.
3325 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3326 ConvertedType, IncompatibleObjC)) {
3327 // Okay, we have an Objective-C pointer conversion.
3328 HasObjCConversion = true;
3329 } else {
3330 // Argument types are too different. Abort.
3331 return false;
3332 }
3333 }
3334
3335 if (HasObjCConversion) {
3336 // We had an Objective-C conversion. Allow this pointer
3337 // conversion, but complain about it.
3338 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3339 IncompatibleObjC = true;
3340 return true;
3341 }
3342 }
3343
3344 return false;
3345}
3346
3348 QualType& ConvertedType) {
3349 QualType ToPointeeType;
3350 if (const BlockPointerType *ToBlockPtr =
3351 ToType->getAs<BlockPointerType>())
3352 ToPointeeType = ToBlockPtr->getPointeeType();
3353 else
3354 return false;
3355
3356 QualType FromPointeeType;
3357 if (const BlockPointerType *FromBlockPtr =
3358 FromType->getAs<BlockPointerType>())
3359 FromPointeeType = FromBlockPtr->getPointeeType();
3360 else
3361 return false;
3362 // We have pointer to blocks, check whether the only
3363 // differences in the argument and result types are in Objective-C
3364 // pointer conversions. If so, we permit the conversion.
3365
3366 const FunctionProtoType *FromFunctionType
3367 = FromPointeeType->getAs<FunctionProtoType>();
3368 const FunctionProtoType *ToFunctionType
3369 = ToPointeeType->getAs<FunctionProtoType>();
3370
3371 if (!FromFunctionType || !ToFunctionType)
3372 return false;
3373
3374 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3375 return true;
3376
3377 // Perform the quick checks that will tell us whether these
3378 // function types are obviously different.
3379 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3380 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3381 return false;
3382
3383 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3384 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3385 if (FromEInfo != ToEInfo)
3386 return false;
3387
3388 bool IncompatibleObjC = false;
3389 if (Context.hasSameType(FromFunctionType->getReturnType(),
3390 ToFunctionType->getReturnType())) {
3391 // Okay, the types match exactly. Nothing to do.
3392 } else {
3393 QualType RHS = FromFunctionType->getReturnType();
3394 QualType LHS = ToFunctionType->getReturnType();
3395 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3396 !RHS.hasQualifiers() && LHS.hasQualifiers())
3397 LHS = LHS.getUnqualifiedType();
3398
3399 if (Context.hasSameType(RHS,LHS)) {
3400 // OK exact match.
3401 } else if (isObjCPointerConversion(RHS, LHS,
3402 ConvertedType, IncompatibleObjC)) {
3403 if (IncompatibleObjC)
3404 return false;
3405 // Okay, we have an Objective-C pointer conversion.
3406 }
3407 else
3408 return false;
3409 }
3410
3411 // Check argument types.
3412 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3413 ArgIdx != NumArgs; ++ArgIdx) {
3414 IncompatibleObjC = false;
3415 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3416 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3417 if (Context.hasSameType(FromArgType, ToArgType)) {
3418 // Okay, the types match exactly. Nothing to do.
3419 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3420 ConvertedType, IncompatibleObjC)) {
3421 if (IncompatibleObjC)
3422 return false;
3423 // Okay, we have an Objective-C pointer conversion.
3424 } else
3425 // Argument types are too different. Abort.
3426 return false;
3427 }
3428
3430 bool CanUseToFPT, CanUseFromFPT;
3431 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3432 CanUseToFPT, CanUseFromFPT,
3433 NewParamInfos))
3434 return false;
3435
3436 ConvertedType = ToType;
3437 return true;
3438}
3439
3440enum {
3448};
3449
3450/// Attempts to get the FunctionProtoType from a Type. Handles
3451/// MemberFunctionPointers properly.
3453 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3454 return FPT;
3455
3456 if (auto *MPT = FromType->getAs<MemberPointerType>())
3457 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3458
3459 return nullptr;
3460}
3461
3463 QualType FromType, QualType ToType) {
3464 // If either type is not valid, include no extra info.
3465 if (FromType.isNull() || ToType.isNull()) {
3466 PDiag << ft_default;
3467 return;
3468 }
3469
3470 // Get the function type from the pointers.
3471 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3472 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3473 *ToMember = ToType->castAs<MemberPointerType>();
3474 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3475 ToMember->getMostRecentCXXRecordDecl())) {
3477 if (ToMember->isSugared())
3478 PDiag << Context.getCanonicalTagType(
3479 ToMember->getMostRecentCXXRecordDecl());
3480 else
3481 PDiag << ToMember->getQualifier();
3482 if (FromMember->isSugared())
3483 PDiag << Context.getCanonicalTagType(
3484 FromMember->getMostRecentCXXRecordDecl());
3485 else
3486 PDiag << FromMember->getQualifier();
3487 return;
3488 }
3489 FromType = FromMember->getPointeeType();
3490 ToType = ToMember->getPointeeType();
3491 }
3492
3493 if (FromType->isPointerType())
3494 FromType = FromType->getPointeeType();
3495 if (ToType->isPointerType())
3496 ToType = ToType->getPointeeType();
3497
3498 // Remove references.
3499 FromType = FromType.getNonReferenceType();
3500 ToType = ToType.getNonReferenceType();
3501
3502 // Don't print extra info for non-specialized template functions.
3503 if (FromType->isInstantiationDependentType() &&
3504 !FromType->getAs<TemplateSpecializationType>()) {
3505 PDiag << ft_default;
3506 return;
3507 }
3508
3509 // No extra info for same types.
3510 if (Context.hasSameType(FromType, ToType)) {
3511 PDiag << ft_default;
3512 return;
3513 }
3514
3515 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3516 *ToFunction = tryGetFunctionProtoType(ToType);
3517
3518 // Both types need to be function types.
3519 if (!FromFunction || !ToFunction) {
3520 PDiag << ft_default;
3521 return;
3522 }
3523
3524 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3525 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3526 << FromFunction->getNumParams();
3527 return;
3528 }
3529
3530 // Handle different parameter types.
3531 unsigned ArgPos;
3532 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3533 PDiag << ft_parameter_mismatch << ArgPos + 1
3534 << ToFunction->getParamType(ArgPos)
3535 << FromFunction->getParamType(ArgPos);
3536 return;
3537 }
3538
3539 // Handle different return type.
3540 if (!Context.hasSameType(FromFunction->getReturnType(),
3541 ToFunction->getReturnType())) {
3542 PDiag << ft_return_type << ToFunction->getReturnType()
3543 << FromFunction->getReturnType();
3544 return;
3545 }
3546
3547 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3548 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3549 << FromFunction->getMethodQuals();
3550 return;
3551 }
3552
3553 // Handle exception specification differences on canonical type (in C++17
3554 // onwards).
3556 ->isNothrow() !=
3557 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3558 ->isNothrow()) {
3559 PDiag << ft_noexcept;
3560 return;
3561 }
3562
3563 // Unable to find a difference, so add no extra info.
3564 PDiag << ft_default;
3565}
3566
3568 ArrayRef<QualType> New, unsigned *ArgPos,
3569 bool Reversed) {
3570 assert(llvm::size(Old) == llvm::size(New) &&
3571 "Can't compare parameters of functions with different number of "
3572 "parameters!");
3573
3574 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3575 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3576 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3577
3578 // Ignore address spaces in pointee type. This is to disallow overloading
3579 // on __ptr32/__ptr64 address spaces.
3580 QualType OldType =
3581 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3582 QualType NewType =
3583 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3584
3585 if (!Context.hasSameType(OldType, NewType)) {
3586 if (ArgPos)
3587 *ArgPos = Idx;
3588 return false;
3589 }
3590 }
3591 return true;
3592}
3593
3595 const FunctionProtoType *NewType,
3596 unsigned *ArgPos, bool Reversed) {
3597 return FunctionParamTypesAreEqual(OldType->param_types(),
3598 NewType->param_types(), ArgPos, Reversed);
3599}
3600
3602 const FunctionDecl *NewFunction,
3603 unsigned *ArgPos,
3604 bool Reversed) {
3605
3606 if (OldFunction->getNumNonObjectParams() !=
3607 NewFunction->getNumNonObjectParams())
3608 return false;
3609
3610 unsigned OldIgnore =
3612 unsigned NewIgnore =
3614
3615 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3616 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3617
3618 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3619 NewPT->param_types().slice(NewIgnore),
3620 ArgPos, Reversed);
3621}
3622
3624 CastKind &Kind,
3625 CXXCastPath& BasePath,
3626 bool IgnoreBaseAccess,
3627 bool Diagnose) {
3628 QualType FromType = From->getType();
3629 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3630
3631 Kind = CK_BitCast;
3632
3633 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3636 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3637 DiagRuntimeBehavior(From->getExprLoc(), From,
3638 PDiag(diag::warn_impcast_bool_to_null_pointer)
3639 << ToType << From->getSourceRange());
3640 else if (!isUnevaluatedContext())
3641 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3642 << ToType << From->getSourceRange();
3643 }
3644 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3645 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3646 QualType FromPointeeType = FromPtrType->getPointeeType(),
3647 ToPointeeType = ToPtrType->getPointeeType();
3648
3649 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3650 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3651 // We must have a derived-to-base conversion. Check an
3652 // ambiguous or inaccessible conversion.
3653 unsigned InaccessibleID = 0;
3654 unsigned AmbiguousID = 0;
3655 if (Diagnose) {
3656 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3657 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3658 }
3660 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3661 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3662 &BasePath, IgnoreBaseAccess))
3663 return true;
3664
3665 // The conversion was successful.
3666 Kind = CK_DerivedToBase;
3667 }
3668
3669 if (Diagnose && !IsCStyleOrFunctionalCast &&
3670 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3671 assert(getLangOpts().MSVCCompat &&
3672 "this should only be possible with MSVCCompat!");
3673 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3674 << From->getSourceRange();
3675 }
3676 }
3677 } else if (const ObjCObjectPointerType *ToPtrType =
3678 ToType->getAs<ObjCObjectPointerType>()) {
3679 if (const ObjCObjectPointerType *FromPtrType =
3680 FromType->getAs<ObjCObjectPointerType>()) {
3681 // Objective-C++ conversions are always okay.
3682 // FIXME: We should have a different class of conversions for the
3683 // Objective-C++ implicit conversions.
3684 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3685 return false;
3686 } else if (FromType->isBlockPointerType()) {
3687 Kind = CK_BlockPointerToObjCPointerCast;
3688 } else {
3689 Kind = CK_CPointerToObjCPointerCast;
3690 }
3691 } else if (ToType->isBlockPointerType()) {
3692 if (!FromType->isBlockPointerType())
3693 Kind = CK_AnyPointerToBlockPointerCast;
3694 }
3695
3696 // We shouldn't fall into this case unless it's valid for other
3697 // reasons.
3699 Kind = CK_NullToPointer;
3700
3701 return false;
3702}
3703
3705 QualType ToType,
3706 bool InOverloadResolution,
3707 QualType &ConvertedType) {
3708 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3709 if (!ToTypePtr)
3710 return false;
3711
3712 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3714 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3716 ConvertedType = ToType;
3717 return true;
3718 }
3719
3720 // Otherwise, both types have to be member pointers.
3721 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3722 if (!FromTypePtr)
3723 return false;
3724
3725 // A pointer to member of B can be converted to a pointer to member of D,
3726 // where D is derived from B (C++ 4.11p2).
3727 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3728 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3729
3730 if (!declaresSameEntity(FromClass, ToClass) &&
3731 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3732 ConvertedType = Context.getMemberPointerType(
3733 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3734 return true;
3735 }
3736
3737 return false;
3738}
3739
3741 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3742 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3743 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3744 // Lock down the inheritance model right now in MS ABI, whether or not the
3745 // pointee types are the same.
3746 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3747 (void)isCompleteType(CheckLoc, FromType);
3748 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3749 }
3750
3751 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3752 if (!FromPtrType) {
3753 // This must be a null pointer to member pointer conversion
3754 Kind = CK_NullToMemberPointer;
3756 }
3757
3758 // T == T, modulo cv
3760 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3761 ToPtrType->getPointeeType()))
3763
3764 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3765 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3766
3767 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3768 const CXXRecordDecl *Cls) {
3769 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3770 PD << Qual;
3771 else
3772 PD << Context.getCanonicalTagType(Cls);
3773 };
3774 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3775 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3776 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3777 return PD;
3778 };
3779
3780 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3782 std::swap(Base, Derived);
3783
3784 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3785 /*DetectVirtual=*/true);
3786 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3788
3789 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3790 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3791 PD << int(Direction);
3792 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3793 Diag(CheckLoc, PD);
3795 }
3796
3797 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3798 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3799 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3800 Diag(CheckLoc, PD);
3802 }
3803
3804 // Must be a base to derived member conversion.
3805 BuildBasePathArray(Paths, BasePath);
3807 ? CK_DerivedToBaseMemberPointer
3808 : CK_BaseToDerivedMemberPointer;
3809
3810 if (!IgnoreBaseAccess)
3811 switch (CheckBaseClassAccess(
3812 CheckLoc, Base, Derived, Paths.front(),
3814 ? diag::err_upcast_to_inaccessible_base
3815 : diag::err_downcast_from_inaccessible_base,
3816 [&](PartialDiagnostic &PD) {
3817 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3818 DerivedQual = ToPtrType->getQualifier();
3819 if (Direction == MemberPointerConversionDirection::Upcast)
3820 std::swap(BaseQual, DerivedQual);
3821 DiagCls(PD, DerivedQual, Derived);
3822 DiagCls(PD, BaseQual, Base);
3823 })) {
3825 case Sema::AR_delayed:
3826 case Sema::AR_dependent:
3827 // Optimistically assume that the delayed and dependent cases
3828 // will work out.
3829 break;
3830
3833 }
3834
3836}
3837
3838/// Determine whether the lifetime conversion between the two given
3839/// qualifiers sets is nontrivial.
3841 Qualifiers ToQuals) {
3842 // Converting anything to const __unsafe_unretained is trivial.
3843 if (ToQuals.hasConst() &&
3845 return false;
3846
3847 return true;
3848}
3849
3850/// Perform a single iteration of the loop for checking if a qualification
3851/// conversion is valid.
3852///
3853/// Specifically, check whether any change between the qualifiers of \p
3854/// FromType and \p ToType is permissible, given knowledge about whether every
3855/// outer layer is const-qualified.
3857 bool CStyle, bool IsTopLevel,
3858 bool &PreviousToQualsIncludeConst,
3859 bool &ObjCLifetimeConversion,
3860 const ASTContext &Ctx) {
3861 Qualifiers FromQuals = FromType.getQualifiers();
3862 Qualifiers ToQuals = ToType.getQualifiers();
3863
3864 // Ignore __unaligned qualifier.
3865 FromQuals.removeUnaligned();
3866
3867 // Objective-C ARC:
3868 // Check Objective-C lifetime conversions.
3869 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3870 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3871 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3872 ObjCLifetimeConversion = true;
3873 FromQuals.removeObjCLifetime();
3874 ToQuals.removeObjCLifetime();
3875 } else {
3876 // Qualification conversions cannot cast between different
3877 // Objective-C lifetime qualifiers.
3878 return false;
3879 }
3880 }
3881
3882 // Allow addition/removal of GC attributes but not changing GC attributes.
3883 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3884 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3885 FromQuals.removeObjCGCAttr();
3886 ToQuals.removeObjCGCAttr();
3887 }
3888
3889 // __ptrauth qualifiers must match exactly.
3890 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3891 return false;
3892
3893 // -- for every j > 0, if const is in cv 1,j then const is in cv
3894 // 2,j, and similarly for volatile.
3895 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3896 return false;
3897
3898 // If address spaces mismatch:
3899 // - in top level it is only valid to convert to addr space that is a
3900 // superset in all cases apart from C-style casts where we allow
3901 // conversions between overlapping address spaces.
3902 // - in non-top levels it is not a valid conversion.
3903 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3904 (!IsTopLevel ||
3905 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3906 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3907 return false;
3908
3909 // -- if the cv 1,j and cv 2,j are different, then const is in
3910 // every cv for 0 < k < j.
3911 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3912 !PreviousToQualsIncludeConst)
3913 return false;
3914
3915 // The following wording is from C++20, where the result of the conversion
3916 // is T3, not T2.
3917 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3918 // "array of unknown bound of"
3919 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3920 return false;
3921
3922 // -- if the resulting P3,i is different from P1,i [...], then const is
3923 // added to every cv 3_k for 0 < k < i.
3924 if (!CStyle && FromType->isConstantArrayType() &&
3925 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3926 return false;
3927
3928 // Keep track of whether all prior cv-qualifiers in the "to" type
3929 // include const.
3930 PreviousToQualsIncludeConst =
3931 PreviousToQualsIncludeConst && ToQuals.hasConst();
3932 return true;
3933}
3934
3935bool
3937 bool CStyle, bool &ObjCLifetimeConversion) {
3938 FromType = Context.getCanonicalType(FromType);
3939 ToType = Context.getCanonicalType(ToType);
3940 ObjCLifetimeConversion = false;
3941
3942 // If FromType and ToType are the same type, this is not a
3943 // qualification conversion.
3944 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3945 return false;
3946
3947 // (C++ 4.4p4):
3948 // A conversion can add cv-qualifiers at levels other than the first
3949 // in multi-level pointers, subject to the following rules: [...]
3950 bool PreviousToQualsIncludeConst = true;
3951 bool UnwrappedAnyPointer = false;
3952 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3953 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3954 !UnwrappedAnyPointer,
3955 PreviousToQualsIncludeConst,
3956 ObjCLifetimeConversion, getASTContext()))
3957 return false;
3958 UnwrappedAnyPointer = true;
3959 }
3960
3961 // We are left with FromType and ToType being the pointee types
3962 // after unwrapping the original FromType and ToType the same number
3963 // of times. If we unwrapped any pointers, and if FromType and
3964 // ToType have the same unqualified type (since we checked
3965 // qualifiers above), then this is a qualification conversion.
3966 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3967}
3968
3969/// - Determine whether this is a conversion from a scalar type to an
3970/// atomic type.
3971///
3972/// If successful, updates \c SCS's second and third steps in the conversion
3973/// sequence to finish the conversion.
3974static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3975 bool InOverloadResolution,
3977 bool CStyle) {
3978 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3979 if (!ToAtomic)
3980 return false;
3981
3983 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3984 InOverloadResolution, InnerSCS,
3985 CStyle, /*AllowObjCWritebackConversion=*/false))
3986 return false;
3987
3988 SCS.Second = InnerSCS.Second;
3989 SCS.setToType(1, InnerSCS.getToType(1));
3990 SCS.Third = InnerSCS.Third;
3993 SCS.setToType(2, InnerSCS.getToType(2));
3994 return true;
3995}
3996
3998 QualType ToType,
3999 bool InOverloadResolution,
4001 bool CStyle) {
4002 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4003 if (!ToOBT)
4004 return false;
4005
4006 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4007 QualType FromType = From->getType();
4008 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4009 return false;
4010
4012 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4013 InOverloadResolution, InnerSCS, CStyle,
4014 /*AllowObjCWritebackConversion=*/false))
4015 return false;
4016
4017 SCS.Second = InnerSCS.Second;
4018 SCS.setToType(1, InnerSCS.getToType(1));
4019 SCS.Third = InnerSCS.Third;
4022 SCS.setToType(2, InnerSCS.getToType(2));
4023 return true;
4024}
4025
4028 QualType Type) {
4029 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4030 if (CtorType->getNumParams() > 0) {
4031 QualType FirstArg = CtorType->getParamType(0);
4032 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4033 return true;
4034 }
4035 return false;
4036}
4037
4038static OverloadingResult
4040 CXXRecordDecl *To,
4042 OverloadCandidateSet &CandidateSet,
4043 bool AllowExplicit) {
4045 for (auto *D : S.LookupConstructors(To)) {
4046 auto Info = getConstructorInfo(D);
4047 if (!Info)
4048 continue;
4049
4050 bool Usable = !Info.Constructor->isInvalidDecl() &&
4051 S.isInitListConstructor(Info.Constructor);
4052 if (Usable) {
4053 bool SuppressUserConversions = false;
4054 if (Info.ConstructorTmpl)
4055 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4056 /*ExplicitArgs*/ nullptr, From,
4057 CandidateSet, SuppressUserConversions,
4058 /*PartialOverloading*/ false,
4059 AllowExplicit);
4060 else
4061 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4062 CandidateSet, SuppressUserConversions,
4063 /*PartialOverloading*/ false, AllowExplicit);
4064 }
4065 }
4066
4067 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4068
4070 switch (auto Result =
4071 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4072 case OR_Deleted:
4073 case OR_Success: {
4074 // Record the standard conversion we used and the conversion function.
4076 QualType ThisType = Constructor->getFunctionObjectParameterType();
4077 // Initializer lists don't have conversions as such.
4079 User.HadMultipleCandidates = HadMultipleCandidates;
4081 User.FoundConversionFunction = Best->FoundDecl;
4083 User.After.setFromType(ThisType);
4084 User.After.setAllToTypes(ToType);
4085 return Result;
4086 }
4087
4089 return OR_No_Viable_Function;
4090 case OR_Ambiguous:
4091 return OR_Ambiguous;
4092 }
4093
4094 llvm_unreachable("Invalid OverloadResult!");
4095}
4096
4097/// Determines whether there is a user-defined conversion sequence
4098/// (C++ [over.ics.user]) that converts expression From to the type
4099/// ToType. If such a conversion exists, User will contain the
4100/// user-defined conversion sequence that performs such a conversion
4101/// and this routine will return true. Otherwise, this routine returns
4102/// false and User is unspecified.
4103///
4104/// \param AllowExplicit true if the conversion should consider C++0x
4105/// "explicit" conversion functions as well as non-explicit conversion
4106/// functions (C++0x [class.conv.fct]p2).
4107///
4108/// \param AllowObjCConversionOnExplicit true if the conversion should
4109/// allow an extra Objective-C pointer conversion on uses of explicit
4110/// constructors. Requires \c AllowExplicit to also be set.
4111static OverloadingResult
4114 OverloadCandidateSet &CandidateSet,
4115 AllowedExplicit AllowExplicit,
4116 bool AllowObjCConversionOnExplicit) {
4117 assert(AllowExplicit != AllowedExplicit::None ||
4118 !AllowObjCConversionOnExplicit);
4120
4121 // Whether we will only visit constructors.
4122 bool ConstructorsOnly = false;
4123
4124 // If the type we are conversion to is a class type, enumerate its
4125 // constructors.
4126 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4127 // C++ [over.match.ctor]p1:
4128 // When objects of class type are direct-initialized (8.5), or
4129 // copy-initialized from an expression of the same or a
4130 // derived class type (8.5), overload resolution selects the
4131 // constructor. [...] For copy-initialization, the candidate
4132 // functions are all the converting constructors (12.3.1) of
4133 // that class. The argument list is the expression-list within
4134 // the parentheses of the initializer.
4135 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4136 (From->getType()->isRecordType() &&
4137 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4138 ConstructorsOnly = true;
4139
4140 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4141 // We're not going to find any constructors.
4142 } else if (auto *ToRecordDecl =
4143 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4144 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4145
4146 Expr **Args = &From;
4147 unsigned NumArgs = 1;
4148 bool ListInitializing = false;
4149 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4150 // But first, see if there is an init-list-constructor that will work.
4152 S, From, ToType, ToRecordDecl, User, CandidateSet,
4153 AllowExplicit == AllowedExplicit::All);
4154 if (Result != OR_No_Viable_Function)
4155 return Result;
4156 // Never mind.
4157 CandidateSet.clear(
4159
4160 // If we're list-initializing, we pass the individual elements as
4161 // arguments, not the entire list.
4162 Args = InitList->getInits();
4163 NumArgs = InitList->getNumInits();
4164 ListInitializing = true;
4165 }
4166
4167 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4168 auto Info = getConstructorInfo(D);
4169 if (!Info)
4170 continue;
4171
4172 bool Usable = !Info.Constructor->isInvalidDecl();
4173 if (!ListInitializing)
4174 Usable = Usable && Info.Constructor->isConvertingConstructor(
4175 /*AllowExplicit*/ true);
4176 if (Usable) {
4177 bool SuppressUserConversions = !ConstructorsOnly;
4178 // C++20 [over.best.ics.general]/4.5:
4179 // if the target is the first parameter of a constructor [of class
4180 // X] and the constructor [...] is a candidate by [...] the second
4181 // phase of [over.match.list] when the initializer list has exactly
4182 // one element that is itself an initializer list, [...] and the
4183 // conversion is to X or reference to cv X, user-defined conversion
4184 // sequences are not considered.
4185 if (SuppressUserConversions && ListInitializing) {
4186 SuppressUserConversions =
4187 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4188 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4189 ToType);
4190 }
4191 if (Info.ConstructorTmpl)
4193 Info.ConstructorTmpl, Info.FoundDecl,
4194 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4195 CandidateSet, SuppressUserConversions,
4196 /*PartialOverloading*/ false,
4197 AllowExplicit == AllowedExplicit::All);
4198 else
4199 // Allow one user-defined conversion when user specifies a
4200 // From->ToType conversion via an static cast (c-style, etc).
4201 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4202 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4203 SuppressUserConversions,
4204 /*PartialOverloading*/ false,
4205 AllowExplicit == AllowedExplicit::All);
4206 }
4207 }
4208 }
4209 }
4210
4211 // Enumerate conversion functions, if we're allowed to.
4212 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4213 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4214 // No conversion functions from incomplete types.
4215 } else if (const RecordType *FromRecordType =
4216 From->getType()->getAsCanonical<RecordType>()) {
4217 if (auto *FromRecordDecl =
4218 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4219 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4220 // Add all of the conversion functions as candidates.
4221 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4222 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4223 DeclAccessPair FoundDecl = I.getPair();
4224 NamedDecl *D = FoundDecl.getDecl();
4225 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4226 if (isa<UsingShadowDecl>(D))
4227 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4228
4229 CXXConversionDecl *Conv;
4230 FunctionTemplateDecl *ConvTemplate;
4231 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4232 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4233 else
4234 Conv = cast<CXXConversionDecl>(D);
4235
4236 if (ConvTemplate)
4238 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4239 CandidateSet, AllowObjCConversionOnExplicit,
4240 AllowExplicit != AllowedExplicit::None);
4241 else
4242 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4243 CandidateSet, AllowObjCConversionOnExplicit,
4244 AllowExplicit != AllowedExplicit::None);
4245 }
4246 }
4247 }
4248
4249 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4250
4252 switch (auto Result =
4253 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4254 case OR_Success:
4255 case OR_Deleted:
4256 // Record the standard conversion we used and the conversion function.
4258 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4259 // C++ [over.ics.user]p1:
4260 // If the user-defined conversion is specified by a
4261 // constructor (12.3.1), the initial standard conversion
4262 // sequence converts the source type to the type required by
4263 // the argument of the constructor.
4264 //
4265 if (isa<InitListExpr>(From)) {
4266 // Initializer lists don't have conversions as such.
4268 User.Before.FromBracedInitList = true;
4269 } else {
4270 if (Best->Conversions[0].isEllipsis())
4271 User.EllipsisConversion = true;
4272 else {
4273 User.Before = Best->Conversions[0].Standard;
4274 User.EllipsisConversion = false;
4275 }
4276 }
4277 User.HadMultipleCandidates = HadMultipleCandidates;
4279 User.FoundConversionFunction = Best->FoundDecl;
4281 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4282 User.After.setAllToTypes(ToType);
4283 return Result;
4284 }
4285 if (CXXConversionDecl *Conversion
4286 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4287
4288 assert(Best->HasFinalConversion);
4289
4290 // C++ [over.ics.user]p1:
4291 //
4292 // [...] If the user-defined conversion is specified by a
4293 // conversion function (12.3.2), the initial standard
4294 // conversion sequence converts the source type to the
4295 // implicit object parameter of the conversion function.
4296 User.Before = Best->Conversions[0].Standard;
4297 User.HadMultipleCandidates = HadMultipleCandidates;
4298 User.ConversionFunction = Conversion;
4299 User.FoundConversionFunction = Best->FoundDecl;
4300 User.EllipsisConversion = false;
4301
4302 // C++ [over.ics.user]p2:
4303 // The second standard conversion sequence converts the
4304 // result of the user-defined conversion to the target type
4305 // for the sequence. Since an implicit conversion sequence
4306 // is an initialization, the special rules for
4307 // initialization by user-defined conversion apply when
4308 // selecting the best user-defined conversion for a
4309 // user-defined conversion sequence (see 13.3.3 and
4310 // 13.3.3.1).
4311 User.After = Best->FinalConversion;
4312 return Result;
4313 }
4314 llvm_unreachable("Not a constructor or conversion function?");
4315
4317 return OR_No_Viable_Function;
4318
4319 case OR_Ambiguous:
4320 return OR_Ambiguous;
4321 }
4322
4323 llvm_unreachable("Invalid OverloadResult!");
4324}
4325
4326bool
4329 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4331 OverloadingResult OvResult =
4332 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4333 CandidateSet, AllowedExplicit::None, false);
4334
4335 if (!(OvResult == OR_Ambiguous ||
4336 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4337 return false;
4338
4339 auto Cands = CandidateSet.CompleteCandidates(
4340 *this,
4342 From);
4343 if (OvResult == OR_Ambiguous)
4344 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4345 << From->getType() << ToType << From->getSourceRange();
4346 else { // OR_No_Viable_Function && !CandidateSet.empty()
4347 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4348 diag::err_typecheck_nonviable_condition_incomplete,
4349 From->getType(), From->getSourceRange()))
4350 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4351 << false << From->getType() << From->getSourceRange() << ToType;
4352 }
4353
4354 CandidateSet.NoteCandidates(
4355 *this, From, Cands);
4356 return true;
4357}
4358
4359// Helper for compareConversionFunctions that gets the FunctionType that the
4360// conversion-operator return value 'points' to, or nullptr.
4361static const FunctionType *
4363 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4364 const PointerType *RetPtrTy =
4365 ConvFuncTy->getReturnType()->getAs<PointerType>();
4366
4367 if (!RetPtrTy)
4368 return nullptr;
4369
4370 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4371}
4372
4373/// Compare the user-defined conversion functions or constructors
4374/// of two user-defined conversion sequences to determine whether any ordering
4375/// is possible.
4378 FunctionDecl *Function2) {
4379 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4380 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4381 if (!Conv1 || !Conv2)
4383
4384 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4386
4387 // Objective-C++:
4388 // If both conversion functions are implicitly-declared conversions from
4389 // a lambda closure type to a function pointer and a block pointer,
4390 // respectively, always prefer the conversion to a function pointer,
4391 // because the function pointer is more lightweight and is more likely
4392 // to keep code working.
4393 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4394 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4395 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4396 if (Block1 != Block2)
4397 return Block1 ? ImplicitConversionSequence::Worse
4399 }
4400
4401 // In order to support multiple calling conventions for the lambda conversion
4402 // operator (such as when the free and member function calling convention is
4403 // different), prefer the 'free' mechanism, followed by the calling-convention
4404 // of operator(). The latter is in place to support the MSVC-like solution of
4405 // defining ALL of the possible conversions in regards to calling-convention.
4406 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4407 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4408
4409 if (Conv1FuncRet && Conv2FuncRet &&
4410 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4411 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4412 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4413
4414 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4415 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4416
4417 CallingConv CallOpCC =
4418 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4420 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4422 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4423
4424 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4425 for (CallingConv CC : PrefOrder) {
4426 if (Conv1CC == CC)
4428 if (Conv2CC == CC)
4430 }
4431 }
4432
4434}
4435
4442
4443/// CompareImplicitConversionSequences - Compare two implicit
4444/// conversion sequences to determine whether one is better than the
4445/// other or if they are indistinguishable (C++ 13.3.3.2).
4448 const ImplicitConversionSequence& ICS1,
4449 const ImplicitConversionSequence& ICS2)
4450{
4451 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4452 // conversion sequences (as defined in 13.3.3.1)
4453 // -- a standard conversion sequence (13.3.3.1.1) is a better
4454 // conversion sequence than a user-defined conversion sequence or
4455 // an ellipsis conversion sequence, and
4456 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4457 // conversion sequence than an ellipsis conversion sequence
4458 // (13.3.3.1.3).
4459 //
4460 // C++0x [over.best.ics]p10:
4461 // For the purpose of ranking implicit conversion sequences as
4462 // described in 13.3.3.2, the ambiguous conversion sequence is
4463 // treated as a user-defined sequence that is indistinguishable
4464 // from any other user-defined conversion sequence.
4465
4466 // String literal to 'char *' conversion has been deprecated in C++03. It has
4467 // been removed from C++11. We still accept this conversion, if it happens at
4468 // the best viable function. Otherwise, this conversion is considered worse
4469 // than ellipsis conversion. Consider this as an extension; this is not in the
4470 // standard. For example:
4471 //
4472 // int &f(...); // #1
4473 // void f(char*); // #2
4474 // void g() { int &r = f("foo"); }
4475 //
4476 // In C++03, we pick #2 as the best viable function.
4477 // In C++11, we pick #1 as the best viable function, because ellipsis
4478 // conversion is better than string-literal to char* conversion (since there
4479 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4480 // convert arguments, #2 would be the best viable function in C++11.
4481 // If the best viable function has this conversion, a warning will be issued
4482 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4483
4484 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4487 // Ill-formedness must not differ
4488 ICS1.isBad() == ICS2.isBad())
4492
4493 if (ICS1.getKindRank() < ICS2.getKindRank())
4495 if (ICS2.getKindRank() < ICS1.getKindRank())
4497
4498 // The following checks require both conversion sequences to be of
4499 // the same kind.
4500 if (ICS1.getKind() != ICS2.getKind())
4502
4505
4506 // Two implicit conversion sequences of the same form are
4507 // indistinguishable conversion sequences unless one of the
4508 // following rules apply: (C++ 13.3.3.2p3):
4509
4510 // List-initialization sequence L1 is a better conversion sequence than
4511 // list-initialization sequence L2 if:
4512 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4513 // if not that,
4514 // — L1 and L2 convert to arrays of the same element type, and either the
4515 // number of elements n_1 initialized by L1 is less than the number of
4516 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4517 // an array of unknown bound and L1 does not,
4518 // even if one of the other rules in this paragraph would otherwise apply.
4519 if (!ICS1.isBad()) {
4520 bool StdInit1 = false, StdInit2 = false;
4523 nullptr);
4526 nullptr);
4527 if (StdInit1 != StdInit2)
4528 return StdInit1 ? ImplicitConversionSequence::Better
4530
4533 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4535 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4537 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4538 CAT2->getElementType())) {
4539 // Both to arrays of the same element type
4540 if (CAT1->getSize() != CAT2->getSize())
4541 // Different sized, the smaller wins
4542 return CAT1->getSize().ult(CAT2->getSize())
4547 // One is incomplete, it loses
4551 }
4552 }
4553 }
4554
4555 if (ICS1.isStandard())
4556 // Standard conversion sequence S1 is a better conversion sequence than
4557 // standard conversion sequence S2 if [...]
4558 Result = CompareStandardConversionSequences(S, Loc,
4559 ICS1.Standard, ICS2.Standard);
4560 else if (ICS1.isUserDefined()) {
4561 // With lazy template loading, it is possible to find non-canonical
4562 // FunctionDecls, depending on when redecl chains are completed. Make sure
4563 // to compare the canonical decls of conversion functions. This avoids
4564 // ambiguity problems for templated conversion operators.
4565 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4566 if (ConvFunc1)
4567 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4568 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4569 if (ConvFunc2)
4570 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4571 // User-defined conversion sequence U1 is a better conversion
4572 // sequence than another user-defined conversion sequence U2 if
4573 // they contain the same user-defined conversion function or
4574 // constructor and if the second standard conversion sequence of
4575 // U1 is better than the second standard conversion sequence of
4576 // U2 (C++ 13.3.3.2p3).
4577 if (ConvFunc1 == ConvFunc2)
4578 Result = CompareStandardConversionSequences(S, Loc,
4579 ICS1.UserDefined.After,
4580 ICS2.UserDefined.After);
4581 else
4582 Result = compareConversionFunctions(S,
4585 }
4586
4587 return Result;
4588}
4589
4590// Per 13.3.3.2p3, compare the given standard conversion sequences to
4591// determine if one is a proper subset of the other.
4594 const StandardConversionSequence& SCS1,
4595 const StandardConversionSequence& SCS2) {
4598
4599 // the identity conversion sequence is considered to be a subsequence of
4600 // any non-identity conversion sequence
4601 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4603 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4605
4606 if (SCS1.Second != SCS2.Second) {
4607 if (SCS1.Second == ICK_Identity)
4609 else if (SCS2.Second == ICK_Identity)
4611 else
4613 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4615
4616 if (SCS1.Third == SCS2.Third) {
4617 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4619 }
4620
4621 if (SCS1.Third == ICK_Identity)
4622 return Result == ImplicitConversionSequence::Worse
4625
4626 if (SCS2.Third == ICK_Identity)
4627 return Result == ImplicitConversionSequence::Better
4630
4632}
4633
4634/// Determine whether one of the given reference bindings is better
4635/// than the other based on what kind of bindings they are.
4636static bool
4638 const StandardConversionSequence &SCS2) {
4639 // C++0x [over.ics.rank]p3b4:
4640 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4641 // implicit object parameter of a non-static member function declared
4642 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4643 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4644 // lvalue reference to a function lvalue and S2 binds an rvalue
4645 // reference*.
4646 //
4647 // FIXME: Rvalue references. We're going rogue with the above edits,
4648 // because the semantics in the current C++0x working paper (N3225 at the
4649 // time of this writing) break the standard definition of std::forward
4650 // and std::reference_wrapper when dealing with references to functions.
4651 // Proposed wording changes submitted to CWG for consideration.
4654 return false;
4655
4656 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4657 SCS2.IsLvalueReference) ||
4660}
4661
4667
4668/// Returns kind of fixed enum promotion the \a SCS uses.
4669static FixedEnumPromotion
4671
4672 if (SCS.Second != ICK_Integral_Promotion)
4674
4675 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4676 if (!Enum)
4678
4679 if (!Enum->isFixed())
4681
4682 QualType UnderlyingType = Enum->getIntegerType();
4683 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4685
4687}
4688
4689/// CompareStandardConversionSequences - Compare two standard
4690/// conversion sequences to determine whether one is better than the
4691/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4694 const StandardConversionSequence& SCS1,
4695 const StandardConversionSequence& SCS2)
4696{
4697 // Standard conversion sequence S1 is a better conversion sequence
4698 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4699
4700 // -- S1 is a proper subsequence of S2 (comparing the conversion
4701 // sequences in the canonical form defined by 13.3.3.1.1,
4702 // excluding any Lvalue Transformation; the identity conversion
4703 // sequence is considered to be a subsequence of any
4704 // non-identity conversion sequence) or, if not that,
4707 return CK;
4708
4709 // -- the rank of S1 is better than the rank of S2 (by the rules
4710 // defined below), or, if not that,
4711 ImplicitConversionRank Rank1 = SCS1.getRank();
4712 ImplicitConversionRank Rank2 = SCS2.getRank();
4713 if (Rank1 < Rank2)
4715 else if (Rank2 < Rank1)
4717
4718 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4719 // are indistinguishable unless one of the following rules
4720 // applies:
4721
4722 // A conversion that is not a conversion of a pointer, or
4723 // pointer to member, to bool is better than another conversion
4724 // that is such a conversion.
4726 return SCS2.isPointerConversionToBool()
4729
4730 // C++14 [over.ics.rank]p4b2:
4731 // This is retroactively applied to C++11 by CWG 1601.
4732 //
4733 // A conversion that promotes an enumeration whose underlying type is fixed
4734 // to its underlying type is better than one that promotes to the promoted
4735 // underlying type, if the two are different.
4738 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4739 FEP1 != FEP2)
4743
4744 // C++ [over.ics.rank]p4b2:
4745 //
4746 // If class B is derived directly or indirectly from class A,
4747 // conversion of B* to A* is better than conversion of B* to
4748 // void*, and conversion of A* to void* is better than conversion
4749 // of B* to void*.
4750 bool SCS1ConvertsToVoid
4752 bool SCS2ConvertsToVoid
4754 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4755 // Exactly one of the conversion sequences is a conversion to
4756 // a void pointer; it's the worse conversion.
4757 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4759 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4760 // Neither conversion sequence converts to a void pointer; compare
4761 // their derived-to-base conversions.
4763 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4764 return DerivedCK;
4765 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4766 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4767 // Both conversion sequences are conversions to void
4768 // pointers. Compare the source types to determine if there's an
4769 // inheritance relationship in their sources.
4770 QualType FromType1 = SCS1.getFromType();
4771 QualType FromType2 = SCS2.getFromType();
4772
4773 // Adjust the types we're converting from via the array-to-pointer
4774 // conversion, if we need to.
4775 if (SCS1.First == ICK_Array_To_Pointer)
4776 FromType1 = S.Context.getArrayDecayedType(FromType1);
4777 if (SCS2.First == ICK_Array_To_Pointer)
4778 FromType2 = S.Context.getArrayDecayedType(FromType2);
4779
4780 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4781 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4782
4783 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4785 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4787
4788 // Objective-C++: If one interface is more specific than the
4789 // other, it is the better one.
4790 const ObjCObjectPointerType* FromObjCPtr1
4791 = FromType1->getAs<ObjCObjectPointerType>();
4792 const ObjCObjectPointerType* FromObjCPtr2
4793 = FromType2->getAs<ObjCObjectPointerType>();
4794 if (FromObjCPtr1 && FromObjCPtr2) {
4795 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4796 FromObjCPtr2);
4797 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4798 FromObjCPtr1);
4799 if (AssignLeft != AssignRight) {
4800 return AssignLeft? ImplicitConversionSequence::Better
4802 }
4803 }
4804 }
4805
4806 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4807 // Check for a better reference binding based on the kind of bindings.
4808 if (isBetterReferenceBindingKind(SCS1, SCS2))
4810 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4812 }
4813
4814 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4815 // bullet 3).
4817 = CompareQualificationConversions(S, SCS1, SCS2))
4818 return QualCK;
4819
4822 return ObtCK;
4823
4824 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4825 // C++ [over.ics.rank]p3b4:
4826 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4827 // which the references refer are the same type except for
4828 // top-level cv-qualifiers, and the type to which the reference
4829 // initialized by S2 refers is more cv-qualified than the type
4830 // to which the reference initialized by S1 refers.
4831 QualType T1 = SCS1.getToType(2);
4832 QualType T2 = SCS2.getToType(2);
4833 T1 = S.Context.getCanonicalType(T1);
4834 T2 = S.Context.getCanonicalType(T2);
4835 Qualifiers T1Quals, T2Quals;
4836 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4837 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4838 if (UnqualT1 == UnqualT2) {
4839 // Objective-C++ ARC: If the references refer to objects with different
4840 // lifetimes, prefer bindings that don't change lifetime.
4846 }
4847
4848 // If the type is an array type, promote the element qualifiers to the
4849 // type for comparison.
4850 if (isa<ArrayType>(T1) && T1Quals)
4851 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4852 if (isa<ArrayType>(T2) && T2Quals)
4853 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4854 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4856 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4858 }
4859 }
4860
4861 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4862 // floating-to-integral conversion if the integral conversion
4863 // is between types of the same size.
4864 // For example:
4865 // void f(float);
4866 // void f(int);
4867 // int main {
4868 // long a;
4869 // f(a);
4870 // }
4871 // Here, MSVC will call f(int) instead of generating a compile error
4872 // as clang will do in standard mode.
4873 if (S.getLangOpts().MSVCCompat &&
4876 SCS2.Second == ICK_Floating_Integral &&
4877 S.Context.getTypeSize(SCS1.getFromType()) ==
4878 S.Context.getTypeSize(SCS1.getToType(2)))
4880
4881 // Prefer a compatible vector conversion over a lax vector conversion
4882 // For example:
4883 //
4884 // typedef float __v4sf __attribute__((__vector_size__(16)));
4885 // void f(vector float);
4886 // void f(vector signed int);
4887 // int main() {
4888 // __v4sf a;
4889 // f(a);
4890 // }
4891 // Here, we'd like to choose f(vector float) and not
4892 // report an ambiguous call error
4893 if (SCS1.Second == ICK_Vector_Conversion &&
4894 SCS2.Second == ICK_Vector_Conversion) {
4895 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4896 SCS1.getFromType(), SCS1.getToType(2));
4897 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4898 SCS2.getFromType(), SCS2.getToType(2));
4899
4900 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4901 return SCS1IsCompatibleVectorConversion
4904 }
4905
4906 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4908 bool SCS1IsCompatibleSVEVectorConversion =
4909 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4910 bool SCS2IsCompatibleSVEVectorConversion =
4911 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4912
4913 if (SCS1IsCompatibleSVEVectorConversion !=
4914 SCS2IsCompatibleSVEVectorConversion)
4915 return SCS1IsCompatibleSVEVectorConversion
4918 }
4919
4920 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4922 bool SCS1IsCompatibleRVVVectorConversion =
4924 bool SCS2IsCompatibleRVVVectorConversion =
4926
4927 if (SCS1IsCompatibleRVVVectorConversion !=
4928 SCS2IsCompatibleRVVVectorConversion)
4929 return SCS1IsCompatibleRVVVectorConversion
4932 }
4934}
4935
4936/// CompareOverflowBehaviorConversions - Compares two standard conversion
4937/// sequences to determine whether they can be ranked based on their
4938/// OverflowBehaviorType's underlying type.
4954
4955/// CompareQualificationConversions - Compares two standard conversion
4956/// sequences to determine whether they can be ranked based on their
4957/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4960 const StandardConversionSequence& SCS1,
4961 const StandardConversionSequence& SCS2) {
4962 // C++ [over.ics.rank]p3:
4963 // -- S1 and S2 differ only in their qualification conversion and
4964 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4965 // [C++98]
4966 // [...] and the cv-qualification signature of type T1 is a proper subset
4967 // of the cv-qualification signature of type T2, and S1 is not the
4968 // deprecated string literal array-to-pointer conversion (4.2).
4969 // [C++2a]
4970 // [...] where T1 can be converted to T2 by a qualification conversion.
4971 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4972 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4974
4975 // FIXME: the example in the standard doesn't use a qualification
4976 // conversion (!)
4977 QualType T1 = SCS1.getToType(2);
4978 QualType T2 = SCS2.getToType(2);
4979 T1 = S.Context.getCanonicalType(T1);
4980 T2 = S.Context.getCanonicalType(T2);
4981 assert(!T1->isReferenceType() && !T2->isReferenceType());
4982 Qualifiers T1Quals, T2Quals;
4983 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4984 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4985
4986 // If the types are the same, we won't learn anything by unwrapping
4987 // them.
4988 if (UnqualT1 == UnqualT2)
4990
4991 // Don't ever prefer a standard conversion sequence that uses the deprecated
4992 // string literal array to pointer conversion.
4993 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4994 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4995
4996 // Objective-C++ ARC:
4997 // Prefer qualification conversions not involving a change in lifetime
4998 // to qualification conversions that do change lifetime.
5001 CanPick1 = false;
5004 CanPick2 = false;
5005
5006 bool ObjCLifetimeConversion;
5007 if (CanPick1 &&
5008 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5009 CanPick1 = false;
5010 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5011 // directions, so we can't short-cut this second check in general.
5012 if (CanPick2 &&
5013 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5014 CanPick2 = false;
5015
5016 if (CanPick1 != CanPick2)
5017 return CanPick1 ? ImplicitConversionSequence::Better
5020}
5021
5022/// CompareDerivedToBaseConversions - Compares two standard conversion
5023/// sequences to determine whether they can be ranked based on their
5024/// various kinds of derived-to-base conversions (C++
5025/// [over.ics.rank]p4b3). As part of these checks, we also look at
5026/// conversions between Objective-C interface types.
5029 const StandardConversionSequence& SCS1,
5030 const StandardConversionSequence& SCS2) {
5031 QualType FromType1 = SCS1.getFromType();
5032 QualType ToType1 = SCS1.getToType(1);
5033 QualType FromType2 = SCS2.getFromType();
5034 QualType ToType2 = SCS2.getToType(1);
5035
5036 // Adjust the types we're converting from via the array-to-pointer
5037 // conversion, if we need to.
5038 if (SCS1.First == ICK_Array_To_Pointer)
5039 FromType1 = S.Context.getArrayDecayedType(FromType1);
5040 if (SCS2.First == ICK_Array_To_Pointer)
5041 FromType2 = S.Context.getArrayDecayedType(FromType2);
5042
5043 // Canonicalize all of the types.
5044 FromType1 = S.Context.getCanonicalType(FromType1);
5045 ToType1 = S.Context.getCanonicalType(ToType1);
5046 FromType2 = S.Context.getCanonicalType(FromType2);
5047 ToType2 = S.Context.getCanonicalType(ToType2);
5048
5049 // C++ [over.ics.rank]p4b3:
5050 //
5051 // If class B is derived directly or indirectly from class A and
5052 // class C is derived directly or indirectly from B,
5053 //
5054 // Compare based on pointer conversions.
5055 if (SCS1.Second == ICK_Pointer_Conversion &&
5057 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5058 FromType1->isPointerType() && FromType2->isPointerType() &&
5059 ToType1->isPointerType() && ToType2->isPointerType()) {
5060 QualType FromPointee1 =
5062 QualType ToPointee1 =
5064 QualType FromPointee2 =
5066 QualType ToPointee2 =
5068
5069 // -- conversion of C* to B* is better than conversion of C* to A*,
5070 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5071 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5073 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5075 }
5076
5077 // -- conversion of B* to A* is better than conversion of C* to A*,
5078 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5079 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5081 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5083 }
5084 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5086 const ObjCObjectPointerType *FromPtr1
5087 = FromType1->getAs<ObjCObjectPointerType>();
5088 const ObjCObjectPointerType *FromPtr2
5089 = FromType2->getAs<ObjCObjectPointerType>();
5090 const ObjCObjectPointerType *ToPtr1
5091 = ToType1->getAs<ObjCObjectPointerType>();
5092 const ObjCObjectPointerType *ToPtr2
5093 = ToType2->getAs<ObjCObjectPointerType>();
5094
5095 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5096 // Apply the same conversion ranking rules for Objective-C pointer types
5097 // that we do for C++ pointers to class types. However, we employ the
5098 // Objective-C pseudo-subtyping relationship used for assignment of
5099 // Objective-C pointer types.
5100 bool FromAssignLeft
5101 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5102 bool FromAssignRight
5103 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5104 bool ToAssignLeft
5105 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5106 bool ToAssignRight
5107 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5108
5109 // A conversion to an a non-id object pointer type or qualified 'id'
5110 // type is better than a conversion to 'id'.
5111 if (ToPtr1->isObjCIdType() &&
5112 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5114 if (ToPtr2->isObjCIdType() &&
5115 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5117
5118 // A conversion to a non-id object pointer type is better than a
5119 // conversion to a qualified 'id' type
5120 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5122 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5124
5125 // A conversion to an a non-Class object pointer type or qualified 'Class'
5126 // type is better than a conversion to 'Class'.
5127 if (ToPtr1->isObjCClassType() &&
5128 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5130 if (ToPtr2->isObjCClassType() &&
5131 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5133
5134 // A conversion to a non-Class object pointer type is better than a
5135 // conversion to a qualified 'Class' type.
5136 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5138 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5140
5141 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5142 if (S.Context.hasSameType(FromType1, FromType2) &&
5143 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5144 (ToAssignLeft != ToAssignRight)) {
5145 if (FromPtr1->isSpecialized()) {
5146 // "conversion of B<A> * to B * is better than conversion of B * to
5147 // C *.
5148 bool IsFirstSame =
5149 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5150 bool IsSecondSame =
5151 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5152 if (IsFirstSame) {
5153 if (!IsSecondSame)
5155 } else if (IsSecondSame)
5157 }
5158 return ToAssignLeft? ImplicitConversionSequence::Worse
5160 }
5161
5162 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5163 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5164 (FromAssignLeft != FromAssignRight))
5165 return FromAssignLeft? ImplicitConversionSequence::Better
5167 }
5168 }
5169
5170 // Ranking of member-pointer types.
5171 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5172 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5173 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5174 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5175 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5176 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5177 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5178 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5179 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5180 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5181 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5182 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5183 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5184 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5186 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5188 }
5189 // conversion of B::* to C::* is better than conversion of A::* to C::*
5190 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5191 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5193 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5195 }
5196 }
5197
5198 if (SCS1.Second == ICK_Derived_To_Base) {
5199 // -- conversion of C to B is better than conversion of C to A,
5200 // -- binding of an expression of type C to a reference of type
5201 // B& is better than binding an expression of type C to a
5202 // reference of type A&,
5203 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5204 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5205 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5207 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5209 }
5210
5211 // -- conversion of B to A is better than conversion of C to A.
5212 // -- binding of an expression of type B to a reference of type
5213 // A& is better than binding an expression of type C to a
5214 // reference of type A&,
5215 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5216 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5217 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5219 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5221 }
5222 }
5223
5225}
5226
5228 if (!T.getQualifiers().hasUnaligned())
5229 return T;
5230
5231 Qualifiers Q;
5232 T = Ctx.getUnqualifiedArrayType(T, Q);
5233 Q.removeUnaligned();
5234 return Ctx.getQualifiedType(T, Q);
5235}
5236
5239 QualType OrigT1, QualType OrigT2,
5240 ReferenceConversions *ConvOut) {
5241 assert(!OrigT1->isReferenceType() &&
5242 "T1 must be the pointee type of the reference type");
5243 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5244
5245 QualType T1 = Context.getCanonicalType(OrigT1);
5246 QualType T2 = Context.getCanonicalType(OrigT2);
5247 Qualifiers T1Quals, T2Quals;
5248 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5249 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5250
5251 ReferenceConversions ConvTmp;
5252 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5253 Conv = ReferenceConversions();
5254
5255 // C++2a [dcl.init.ref]p4:
5256 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5257 // reference-related to "cv2 T2" if T1 is similar to T2, or
5258 // T1 is a base class of T2.
5259 // "cv1 T1" is reference-compatible with "cv2 T2" if
5260 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5261 // "pointer to cv1 T1" via a standard conversion sequence.
5262
5263 // Check for standard conversions we can apply to pointers: derived-to-base
5264 // conversions, ObjC pointer conversions, and function pointer conversions.
5265 // (Qualification conversions are checked last.)
5266 if (UnqualT1 == UnqualT2) {
5267 // Nothing to do.
5268 } else if (isCompleteType(Loc, OrigT2) &&
5269 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5270 Conv |= ReferenceConversions::DerivedToBase;
5271 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5272 UnqualT2->isObjCObjectOrInterfaceType() &&
5273 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5274 Conv |= ReferenceConversions::ObjC;
5275 else if (UnqualT2->isFunctionType() &&
5276 IsFunctionConversion(UnqualT2, UnqualT1)) {
5277 Conv |= ReferenceConversions::Function;
5278 // No need to check qualifiers; function types don't have them.
5279 return Ref_Compatible;
5280 }
5281 bool ConvertedReferent = Conv != 0;
5282
5283 // We can have a qualification conversion. Compute whether the types are
5284 // similar at the same time.
5285 bool PreviousToQualsIncludeConst = true;
5286 bool TopLevel = true;
5287 do {
5288 if (T1 == T2)
5289 break;
5290
5291 // We will need a qualification conversion.
5292 Conv |= ReferenceConversions::Qualification;
5293
5294 // Track whether we performed a qualification conversion anywhere other
5295 // than the top level. This matters for ranking reference bindings in
5296 // overload resolution.
5297 if (!TopLevel)
5298 Conv |= ReferenceConversions::NestedQualification;
5299
5300 // MS compiler ignores __unaligned qualifier for references; do the same.
5301 T1 = withoutUnaligned(Context, T1);
5302 T2 = withoutUnaligned(Context, T2);
5303
5304 // If we find a qualifier mismatch, the types are not reference-compatible,
5305 // but are still be reference-related if they're similar.
5306 bool ObjCLifetimeConversion = false;
5307 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5308 PreviousToQualsIncludeConst,
5309 ObjCLifetimeConversion, getASTContext()))
5310 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5311 ? Ref_Related
5313
5314 // FIXME: Should we track this for any level other than the first?
5315 if (ObjCLifetimeConversion)
5316 Conv |= ReferenceConversions::ObjCLifetime;
5317
5318 TopLevel = false;
5319 } while (Context.UnwrapSimilarTypes(T1, T2));
5320
5321 // At this point, if the types are reference-related, we must either have the
5322 // same inner type (ignoring qualifiers), or must have already worked out how
5323 // to convert the referent.
5324 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5327}
5328
5329/// Look for a user-defined conversion to a value reference-compatible
5330/// with DeclType. Return true if something definite is found.
5331static bool
5333 QualType DeclType, SourceLocation DeclLoc,
5334 Expr *Init, QualType T2, bool AllowRvalues,
5335 bool AllowExplicit) {
5336 assert(T2->isRecordType() && "Can only find conversions of record types.");
5337 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5338 OverloadCandidateSet CandidateSet(
5340 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5341 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5342 NamedDecl *D = *I;
5344 if (isa<UsingShadowDecl>(D))
5345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5346
5347 FunctionTemplateDecl *ConvTemplate
5348 = dyn_cast<FunctionTemplateDecl>(D);
5349 CXXConversionDecl *Conv;
5350 if (ConvTemplate)
5351 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5352 else
5353 Conv = cast<CXXConversionDecl>(D);
5354
5355 if (AllowRvalues) {
5356 // If we are initializing an rvalue reference, don't permit conversion
5357 // functions that return lvalues.
5358 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5359 const ReferenceType *RefType
5361 if (RefType && !RefType->getPointeeType()->isFunctionType())
5362 continue;
5363 }
5364
5365 if (!ConvTemplate &&
5367 DeclLoc,
5368 Conv->getConversionType()
5373 continue;
5374 } else {
5375 // If the conversion function doesn't return a reference type,
5376 // it can't be considered for this conversion. An rvalue reference
5377 // is only acceptable if its referencee is a function type.
5378
5379 const ReferenceType *RefType =
5381 if (!RefType ||
5382 (!RefType->isLValueReferenceType() &&
5383 !RefType->getPointeeType()->isFunctionType()))
5384 continue;
5385 }
5386
5387 if (ConvTemplate)
5389 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5390 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5391 else
5393 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5394 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5395 }
5396
5397 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5398
5400 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5401 case OR_Success:
5402
5403 assert(Best->HasFinalConversion);
5404
5405 // C++ [over.ics.ref]p1:
5406 //
5407 // [...] If the parameter binds directly to the result of
5408 // applying a conversion function to the argument
5409 // expression, the implicit conversion sequence is a
5410 // user-defined conversion sequence (13.3.3.1.2), with the
5411 // second standard conversion sequence either an identity
5412 // conversion or, if the conversion function returns an
5413 // entity of a type that is a derived class of the parameter
5414 // type, a derived-to-base Conversion.
5415 if (!Best->FinalConversion.DirectBinding)
5416 return false;
5417
5418 ICS.setUserDefined();
5419 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5420 ICS.UserDefined.After = Best->FinalConversion;
5421 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5422 ICS.UserDefined.ConversionFunction = Best->Function;
5423 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5424 ICS.UserDefined.EllipsisConversion = false;
5425 assert(ICS.UserDefined.After.ReferenceBinding &&
5427 "Expected a direct reference binding!");
5428 return true;
5429
5430 case OR_Ambiguous:
5431 ICS.setAmbiguous();
5432 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5433 Cand != CandidateSet.end(); ++Cand)
5434 if (Cand->Best)
5435 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5436 return true;
5437
5439 case OR_Deleted:
5440 // There was no suitable conversion, or we found a deleted
5441 // conversion; continue with other checks.
5442 return false;
5443 }
5444
5445 llvm_unreachable("Invalid OverloadResult!");
5446}
5447
5448/// Compute an implicit conversion sequence for reference
5449/// initialization.
5450static ImplicitConversionSequence
5452 SourceLocation DeclLoc,
5453 bool SuppressUserConversions,
5454 bool AllowExplicit) {
5455 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5456
5457 // Most paths end in a failed conversion.
5460
5461 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5462 QualType T2 = Init->getType();
5463
5464 // If the initializer is the address of an overloaded function, try
5465 // to resolve the overloaded function. If all goes well, T2 is the
5466 // type of the resulting function.
5467 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5470 false, Found))
5471 T2 = Fn->getType();
5472 }
5473
5474 // Compute some basic properties of the types and the initializer.
5475 bool isRValRef = DeclType->isRValueReferenceType();
5476 Expr::Classification InitCategory = Init->Classify(S.Context);
5477
5479 Sema::ReferenceCompareResult RefRelationship =
5480 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5481
5482 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5483 ICS.setStandard();
5485 // FIXME: A reference binding can be a function conversion too. We should
5486 // consider that when ordering reference-to-function bindings.
5487 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5489 : (RefConv & Sema::ReferenceConversions::ObjC)
5491 : ICK_Identity;
5493 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5494 // a reference binding that performs a non-top-level qualification
5495 // conversion as a qualification conversion, not as an identity conversion.
5496 ICS.Standard.Third = (RefConv &
5497 Sema::ReferenceConversions::NestedQualification)
5499 : ICK_Identity;
5500 ICS.Standard.setFromType(T2);
5501 ICS.Standard.setToType(0, T2);
5502 ICS.Standard.setToType(1, T1);
5503 ICS.Standard.setToType(2, T1);
5504 ICS.Standard.ReferenceBinding = true;
5505 ICS.Standard.DirectBinding = BindsDirectly;
5506 ICS.Standard.IsLvalueReference = !isRValRef;
5508 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5511 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5512 ICS.Standard.FromBracedInitList = false;
5513 ICS.Standard.CopyConstructor = nullptr;
5515 };
5516
5517 // C++0x [dcl.init.ref]p5:
5518 // A reference to type "cv1 T1" is initialized by an expression
5519 // of type "cv2 T2" as follows:
5520
5521 // -- If reference is an lvalue reference and the initializer expression
5522 if (!isRValRef) {
5523 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5524 // reference-compatible with "cv2 T2," or
5525 //
5526 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5527 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5528 // C++ [over.ics.ref]p1:
5529 // When a parameter of reference type binds directly (8.5.3)
5530 // to an argument expression, the implicit conversion sequence
5531 // is the identity conversion, unless the argument expression
5532 // has a type that is a derived class of the parameter type,
5533 // in which case the implicit conversion sequence is a
5534 // derived-to-base Conversion (13.3.3.1).
5535 SetAsReferenceBinding(/*BindsDirectly=*/true);
5536
5537 // Nothing more to do: the inaccessibility/ambiguity check for
5538 // derived-to-base conversions is suppressed when we're
5539 // computing the implicit conversion sequence (C++
5540 // [over.best.ics]p2).
5541 return ICS;
5542 }
5543
5544 // -- has a class type (i.e., T2 is a class type), where T1 is
5545 // not reference-related to T2, and can be implicitly
5546 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5547 // is reference-compatible with "cv3 T3" 92) (this
5548 // conversion is selected by enumerating the applicable
5549 // conversion functions (13.3.1.6) and choosing the best
5550 // one through overload resolution (13.3)),
5551 if (!SuppressUserConversions && T2->isRecordType() &&
5552 S.isCompleteType(DeclLoc, T2) &&
5553 RefRelationship == Sema::Ref_Incompatible) {
5554 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5555 Init, T2, /*AllowRvalues=*/false,
5556 AllowExplicit))
5557 return ICS;
5558 }
5559 }
5560
5561 // -- Otherwise, the reference shall be an lvalue reference to a
5562 // non-volatile const type (i.e., cv1 shall be const), or the reference
5563 // shall be an rvalue reference.
5564 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5565 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5567 return ICS;
5568 }
5569
5570 // -- If the initializer expression
5571 //
5572 // -- is an xvalue, class prvalue, array prvalue or function
5573 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5574 if (RefRelationship == Sema::Ref_Compatible &&
5575 (InitCategory.isXValue() ||
5576 (InitCategory.isPRValue() &&
5577 (T2->isRecordType() || T2->isArrayType())) ||
5578 (InitCategory.isLValue() && T2->isFunctionType()))) {
5579 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5580 // binding unless we're binding to a class prvalue.
5581 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5582 // allow the use of rvalue references in C++98/03 for the benefit of
5583 // standard library implementors; therefore, we need the xvalue check here.
5584 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5585 !(InitCategory.isPRValue() || T2->isRecordType()));
5586 return ICS;
5587 }
5588
5589 // -- has a class type (i.e., T2 is a class type), where T1 is not
5590 // reference-related to T2, and can be implicitly converted to
5591 // an xvalue, class prvalue, or function lvalue of type
5592 // "cv3 T3", where "cv1 T1" is reference-compatible with
5593 // "cv3 T3",
5594 //
5595 // then the reference is bound to the value of the initializer
5596 // expression in the first case and to the result of the conversion
5597 // in the second case (or, in either case, to an appropriate base
5598 // class subobject).
5599 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5600 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5601 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5602 Init, T2, /*AllowRvalues=*/true,
5603 AllowExplicit)) {
5604 // In the second case, if the reference is an rvalue reference
5605 // and the second standard conversion sequence of the
5606 // user-defined conversion sequence includes an lvalue-to-rvalue
5607 // conversion, the program is ill-formed.
5608 if (ICS.isUserDefined() && isRValRef &&
5611
5612 return ICS;
5613 }
5614
5615 // A temporary of function type cannot be created; don't even try.
5616 if (T1->isFunctionType())
5617 return ICS;
5618
5619 // -- Otherwise, a temporary of type "cv1 T1" is created and
5620 // initialized from the initializer expression using the
5621 // rules for a non-reference copy initialization (8.5). The
5622 // reference is then bound to the temporary. If T1 is
5623 // reference-related to T2, cv1 must be the same
5624 // cv-qualification as, or greater cv-qualification than,
5625 // cv2; otherwise, the program is ill-formed.
5626 if (RefRelationship == Sema::Ref_Related) {
5627 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5628 // we would be reference-compatible or reference-compatible with
5629 // added qualification. But that wasn't the case, so the reference
5630 // initialization fails.
5631 //
5632 // Note that we only want to check address spaces and cvr-qualifiers here.
5633 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5634 Qualifiers T1Quals = T1.getQualifiers();
5635 Qualifiers T2Quals = T2.getQualifiers();
5636 T1Quals.removeObjCGCAttr();
5637 T1Quals.removeObjCLifetime();
5638 T2Quals.removeObjCGCAttr();
5639 T2Quals.removeObjCLifetime();
5640 // MS compiler ignores __unaligned qualifier for references; do the same.
5641 T1Quals.removeUnaligned();
5642 T2Quals.removeUnaligned();
5643 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5644 return ICS;
5645 }
5646
5647 // If at least one of the types is a class type, the types are not
5648 // related, and we aren't allowed any user conversions, the
5649 // reference binding fails. This case is important for breaking
5650 // recursion, since TryImplicitConversion below will attempt to
5651 // create a temporary through the use of a copy constructor.
5652 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5653 (T1->isRecordType() || T2->isRecordType()))
5654 return ICS;
5655
5656 // If T1 is reference-related to T2 and the reference is an rvalue
5657 // reference, the initializer expression shall not be an lvalue.
5658 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5659 Init->Classify(S.Context).isLValue()) {
5661 return ICS;
5662 }
5663
5664 // C++ [over.ics.ref]p2:
5665 // When a parameter of reference type is not bound directly to
5666 // an argument expression, the conversion sequence is the one
5667 // required to convert the argument expression to the
5668 // underlying type of the reference according to
5669 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5670 // to copy-initializing a temporary of the underlying type with
5671 // the argument expression. Any difference in top-level
5672 // cv-qualification is subsumed by the initialization itself
5673 // and does not constitute a conversion.
5674 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5675 AllowedExplicit::None,
5676 /*InOverloadResolution=*/false,
5677 /*CStyle=*/false,
5678 /*AllowObjCWritebackConversion=*/false,
5679 /*AllowObjCConversionOnExplicit=*/false);
5680
5681 // Of course, that's still a reference binding.
5682 if (ICS.isStandard()) {
5683 ICS.Standard.ReferenceBinding = true;
5684 ICS.Standard.IsLvalueReference = !isRValRef;
5685 ICS.Standard.BindsToFunctionLvalue = false;
5686 ICS.Standard.BindsToRvalue = true;
5689 } else if (ICS.isUserDefined()) {
5690 const ReferenceType *LValRefType =
5693
5694 // C++ [over.ics.ref]p3:
5695 // Except for an implicit object parameter, for which see 13.3.1, a
5696 // standard conversion sequence cannot be formed if it requires [...]
5697 // binding an rvalue reference to an lvalue other than a function
5698 // lvalue.
5699 // Note that the function case is not possible here.
5700 if (isRValRef && LValRefType) {
5702 return ICS;
5703 }
5704
5706 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5708 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5712 }
5713
5714 return ICS;
5715}
5716
5717static ImplicitConversionSequence
5718TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5719 bool SuppressUserConversions,
5720 bool InOverloadResolution,
5721 bool AllowObjCWritebackConversion,
5722 bool AllowExplicit = false);
5723
5724/// TryListConversion - Try to copy-initialize a value of type ToType from the
5725/// initializer list From.
5726static ImplicitConversionSequence
5728 bool SuppressUserConversions,
5729 bool InOverloadResolution,
5730 bool AllowObjCWritebackConversion) {
5731 // C++11 [over.ics.list]p1:
5732 // When an argument is an initializer list, it is not an expression and
5733 // special rules apply for converting it to a parameter type.
5734
5736 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5737
5738 // We need a complete type for what follows. With one C++20 exception,
5739 // incomplete types can never be initialized from init lists.
5740 QualType InitTy = ToType;
5741 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5742 if (AT && S.getLangOpts().CPlusPlus20)
5743 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5744 // C++20 allows list initialization of an incomplete array type.
5745 InitTy = IAT->getElementType();
5746 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5747 return Result;
5748
5749 // C++20 [over.ics.list]/2:
5750 // If the initializer list is a designated-initializer-list, a conversion
5751 // is only possible if the parameter has an aggregate type
5752 //
5753 // FIXME: The exception for reference initialization here is not part of the
5754 // language rules, but follow other compilers in adding it as a tentative DR
5755 // resolution.
5756 bool IsDesignatedInit = From->hasDesignatedInit();
5757 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5758 IsDesignatedInit)
5759 return Result;
5760
5761 // Per DR1467 and DR2137:
5762 // If the parameter type is an aggregate class X and the initializer list
5763 // has a single element of type cv U, where U is X or a class derived from
5764 // X, the implicit conversion sequence is the one required to convert the
5765 // element to the parameter type.
5766 //
5767 // Otherwise, if the parameter type is a character array [... ]
5768 // and the initializer list has a single element that is an
5769 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5770 // implicit conversion sequence is the identity conversion.
5771 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5772 if (ToType->isRecordType() && ToType->isAggregateType()) {
5773 QualType InitType = From->getInit(0)->getType();
5774 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5775 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5776 return TryCopyInitialization(S, From->getInit(0), ToType,
5777 SuppressUserConversions,
5778 InOverloadResolution,
5779 AllowObjCWritebackConversion);
5780 }
5781
5782 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5783 InitializedEntity Entity =
5785 /*Consumed=*/false);
5786 if (S.CanPerformCopyInitialization(Entity, From)) {
5787 Result.setStandard();
5788 Result.Standard.setAsIdentityConversion();
5789 Result.Standard.setFromType(ToType);
5790 Result.Standard.setAllToTypes(ToType);
5791 return Result;
5792 }
5793 }
5794 }
5795
5796 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5797 // C++11 [over.ics.list]p2:
5798 // If the parameter type is std::initializer_list<X> or "array of X" and
5799 // all the elements can be implicitly converted to X, the implicit
5800 // conversion sequence is the worst conversion necessary to convert an
5801 // element of the list to X.
5802 //
5803 // C++14 [over.ics.list]p3:
5804 // Otherwise, if the parameter type is "array of N X", if the initializer
5805 // list has exactly N elements or if it has fewer than N elements and X is
5806 // default-constructible, and if all the elements of the initializer list
5807 // can be implicitly converted to X, the implicit conversion sequence is
5808 // the worst conversion necessary to convert an element of the list to X.
5809 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5810 unsigned e = From->getNumInits();
5813 QualType());
5814 QualType ContTy = ToType;
5815 bool IsUnbounded = false;
5816 if (AT) {
5817 InitTy = AT->getElementType();
5818 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5819 if (CT->getSize().ult(e)) {
5820 // Too many inits, fatally bad
5822 ToType);
5823 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5824 return Result;
5825 }
5826 if (CT->getSize().ugt(e)) {
5827 // Need an init from empty {}, is there one?
5828 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5829 From->getEndLoc());
5830 EmptyList.setType(S.Context.VoidTy);
5831 DfltElt = TryListConversion(
5832 S, &EmptyList, InitTy, SuppressUserConversions,
5833 InOverloadResolution, AllowObjCWritebackConversion);
5834 if (DfltElt.isBad()) {
5835 // No {} init, fatally bad
5837 ToType);
5838 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5839 return Result;
5840 }
5841 }
5842 } else {
5843 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5844 IsUnbounded = true;
5845 if (!e) {
5846 // Cannot convert to zero-sized.
5848 ToType);
5849 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5850 return Result;
5851 }
5852 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5853 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5855 }
5856 }
5857
5858 Result.setStandard();
5859 Result.Standard.setAsIdentityConversion();
5860 Result.Standard.setFromType(InitTy);
5861 Result.Standard.setAllToTypes(InitTy);
5862 for (unsigned i = 0; i < e; ++i) {
5863 Expr *Init = From->getInit(i);
5865 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5866 AllowObjCWritebackConversion);
5867
5868 // Keep the worse conversion seen so far.
5869 // FIXME: Sequences are not totally ordered, so 'worse' can be
5870 // ambiguous. CWG has been informed.
5872 Result) ==
5874 Result = ICS;
5875 // Bail as soon as we find something unconvertible.
5876 if (Result.isBad()) {
5877 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5878 return Result;
5879 }
5880 }
5881 }
5882
5883 // If we needed any implicit {} initialization, compare that now.
5884 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5885 // has been informed that this might not be the best thing.
5886 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5887 S, From->getEndLoc(), DfltElt, Result) ==
5889 Result = DfltElt;
5890 // Record the type being initialized so that we may compare sequences
5891 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5892 return Result;
5893 }
5894
5895 // C++14 [over.ics.list]p4:
5896 // C++11 [over.ics.list]p3:
5897 // Otherwise, if the parameter is a non-aggregate class X and overload
5898 // resolution chooses a single best constructor [...] the implicit
5899 // conversion sequence is a user-defined conversion sequence. If multiple
5900 // constructors are viable but none is better than the others, the
5901 // implicit conversion sequence is a user-defined conversion sequence.
5902 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5903 // This function can deal with initializer lists.
5904 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5905 AllowedExplicit::None,
5906 InOverloadResolution, /*CStyle=*/false,
5907 AllowObjCWritebackConversion,
5908 /*AllowObjCConversionOnExplicit=*/false);
5909 }
5910
5911 // C++14 [over.ics.list]p5:
5912 // C++11 [over.ics.list]p4:
5913 // Otherwise, if the parameter has an aggregate type which can be
5914 // initialized from the initializer list [...] the implicit conversion
5915 // sequence is a user-defined conversion sequence.
5916 if (ToType->isAggregateType()) {
5917 // Type is an aggregate, argument is an init list. At this point it comes
5918 // down to checking whether the initialization works.
5919 // FIXME: Find out whether this parameter is consumed or not.
5920 InitializedEntity Entity =
5922 /*Consumed=*/false);
5924 From)) {
5925 Result.setUserDefined();
5926 Result.UserDefined.Before.setAsIdentityConversion();
5927 // Initializer lists don't have a type.
5928 Result.UserDefined.Before.setFromType(QualType());
5929 Result.UserDefined.Before.setAllToTypes(QualType());
5930
5931 Result.UserDefined.After.setAsIdentityConversion();
5932 Result.UserDefined.After.setFromType(ToType);
5933 Result.UserDefined.After.setAllToTypes(ToType);
5934 Result.UserDefined.ConversionFunction = nullptr;
5935 }
5936 return Result;
5937 }
5938
5939 // C++14 [over.ics.list]p6:
5940 // C++11 [over.ics.list]p5:
5941 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5942 if (ToType->isReferenceType()) {
5943 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5944 // mention initializer lists in any way. So we go by what list-
5945 // initialization would do and try to extrapolate from that.
5946
5947 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5948
5949 // If the initializer list has a single element that is reference-related
5950 // to the parameter type, we initialize the reference from that.
5951 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5952 Expr *Init = From->getInit(0);
5953
5954 QualType T2 = Init->getType();
5955
5956 // If the initializer is the address of an overloaded function, try
5957 // to resolve the overloaded function. If all goes well, T2 is the
5958 // type of the resulting function.
5959 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5962 Init, ToType, false, Found))
5963 T2 = Fn->getType();
5964 }
5965
5966 // Compute some basic properties of the types and the initializer.
5967 Sema::ReferenceCompareResult RefRelationship =
5968 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5969
5970 if (RefRelationship >= Sema::Ref_Related) {
5971 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5972 SuppressUserConversions,
5973 /*AllowExplicit=*/false);
5974 }
5975 }
5976
5977 // Otherwise, we bind the reference to a temporary created from the
5978 // initializer list.
5979 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5980 InOverloadResolution,
5981 AllowObjCWritebackConversion);
5982 if (Result.isFailure())
5983 return Result;
5984 assert(!Result.isEllipsis() &&
5985 "Sub-initialization cannot result in ellipsis conversion.");
5986
5987 // Can we even bind to a temporary?
5988 if (ToType->isRValueReferenceType() ||
5989 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5990 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5991 Result.UserDefined.After;
5992 SCS.ReferenceBinding = true;
5994 SCS.BindsToRvalue = true;
5995 SCS.BindsToFunctionLvalue = false;
5998 SCS.FromBracedInitList = false;
5999
6000 } else
6002 From, ToType);
6003 return Result;
6004 }
6005
6006 // C++14 [over.ics.list]p7:
6007 // C++11 [over.ics.list]p6:
6008 // Otherwise, if the parameter type is not a class:
6009 if (!ToType->isRecordType()) {
6010 // - if the initializer list has one element that is not itself an
6011 // initializer list, the implicit conversion sequence is the one
6012 // required to convert the element to the parameter type.
6013 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6014 // single integer.
6015 unsigned NumInits = From->getNumInits();
6016 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6017 !isa<EmbedExpr>(From->getInit(0))) {
6018 Result = TryCopyInitialization(
6019 S, From->getInit(0), ToType, SuppressUserConversions,
6020 InOverloadResolution, AllowObjCWritebackConversion);
6021 if (Result.isStandard())
6022 Result.Standard.FromBracedInitList = true;
6023 }
6024 // - if the initializer list has no elements, the implicit conversion
6025 // sequence is the identity conversion.
6026 else if (NumInits == 0) {
6027 Result.setStandard();
6028 Result.Standard.setAsIdentityConversion();
6029 Result.Standard.setFromType(ToType);
6030 Result.Standard.setAllToTypes(ToType);
6031 }
6032 return Result;
6033 }
6034
6035 // C++14 [over.ics.list]p8:
6036 // C++11 [over.ics.list]p7:
6037 // In all cases other than those enumerated above, no conversion is possible
6038 return Result;
6039}
6040
6041/// TryCopyInitialization - Try to copy-initialize a value of type
6042/// ToType from the expression From. Return the implicit conversion
6043/// sequence required to pass this argument, which may be a bad
6044/// conversion sequence (meaning that the argument cannot be passed to
6045/// a parameter of this type). If @p SuppressUserConversions, then we
6046/// do not permit any user-defined conversion sequences.
6047static ImplicitConversionSequence
6049 bool SuppressUserConversions,
6050 bool InOverloadResolution,
6051 bool AllowObjCWritebackConversion,
6052 bool AllowExplicit) {
6053 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6054 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6055 InOverloadResolution,AllowObjCWritebackConversion);
6056
6057 if (ToType->isReferenceType())
6058 return TryReferenceInit(S, From, ToType,
6059 /*FIXME:*/ From->getBeginLoc(),
6060 SuppressUserConversions, AllowExplicit);
6061
6062 return TryImplicitConversion(S, From, ToType,
6063 SuppressUserConversions,
6064 AllowedExplicit::None,
6065 InOverloadResolution,
6066 /*CStyle=*/false,
6067 AllowObjCWritebackConversion,
6068 /*AllowObjCConversionOnExplicit=*/false);
6069}
6070
6071static bool TryCopyInitialization(const CanQualType FromQTy,
6072 const CanQualType ToQTy,
6073 Sema &S,
6074 SourceLocation Loc,
6075 ExprValueKind FromVK) {
6076 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6078 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6079
6080 return !ICS.isBad();
6081}
6082
6083/// TryObjectArgumentInitialization - Try to initialize the object
6084/// parameter of the given member function (@c Method) from the
6085/// expression @p From.
6087 Sema &S, SourceLocation Loc, QualType FromType,
6088 Expr::Classification FromClassification, CXXMethodDecl *Method,
6089 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6090 QualType ExplicitParameterType = QualType(),
6091 bool SuppressUserConversion = false) {
6092
6093 // We need to have an object of class type.
6094 if (const auto *PT = FromType->getAs<PointerType>()) {
6095 FromType = PT->getPointeeType();
6096
6097 // When we had a pointer, it's implicitly dereferenced, so we
6098 // better have an lvalue.
6099 assert(FromClassification.isLValue());
6100 }
6101
6102 auto ValueKindFromClassification = [](Expr::Classification C) {
6103 if (C.isPRValue())
6104 return clang::VK_PRValue;
6105 if (C.isXValue())
6106 return VK_XValue;
6107 return clang::VK_LValue;
6108 };
6109
6110 if (Method->isExplicitObjectMemberFunction()) {
6111 if (ExplicitParameterType.isNull())
6112 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6113 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6114 ValueKindFromClassification(FromClassification));
6116 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6117 /*InOverloadResolution=*/true, false);
6118 if (ICS.isBad())
6119 ICS.Bad.FromExpr = nullptr;
6120 return ICS;
6121 }
6122
6123 assert(FromType->isRecordType());
6124
6125 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6126 // C++98 [class.dtor]p2:
6127 // A destructor can be invoked for a const, volatile or const volatile
6128 // object.
6129 // C++98 [over.match.funcs]p4:
6130 // For static member functions, the implicit object parameter is considered
6131 // to match any object (since if the function is selected, the object is
6132 // discarded).
6133 Qualifiers Quals = Method->getMethodQualifiers();
6134 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6135 Quals.addConst();
6136 Quals.addVolatile();
6137 }
6138
6139 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6140
6141 // Set up the conversion sequence as a "bad" conversion, to allow us
6142 // to exit early.
6144
6145 // C++0x [over.match.funcs]p4:
6146 // For non-static member functions, the type of the implicit object
6147 // parameter is
6148 //
6149 // - "lvalue reference to cv X" for functions declared without a
6150 // ref-qualifier or with the & ref-qualifier
6151 // - "rvalue reference to cv X" for functions declared with the &&
6152 // ref-qualifier
6153 //
6154 // where X is the class of which the function is a member and cv is the
6155 // cv-qualification on the member function declaration.
6156 //
6157 // However, when finding an implicit conversion sequence for the argument, we
6158 // are not allowed to perform user-defined conversions
6159 // (C++ [over.match.funcs]p5). We perform a simplified version of
6160 // reference binding here, that allows class rvalues to bind to
6161 // non-constant references.
6162
6163 // First check the qualifiers.
6164 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6165 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6166 if (ImplicitParamType.getCVRQualifiers() !=
6167 FromTypeCanon.getLocalCVRQualifiers() &&
6168 !ImplicitParamType.isAtLeastAsQualifiedAs(
6169 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6171 FromType, ImplicitParamType);
6172 return ICS;
6173 }
6174
6175 if (FromTypeCanon.hasAddressSpace()) {
6176 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6177 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6178 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6179 S.getASTContext())) {
6181 FromType, ImplicitParamType);
6182 return ICS;
6183 }
6184 }
6185
6186 // Check that we have either the same type or a derived type. It
6187 // affects the conversion rank.
6188 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6189 ImplicitConversionKind SecondKind;
6190 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6191 SecondKind = ICK_Identity;
6192 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6193 SecondKind = ICK_Derived_To_Base;
6194 } else if (!Method->isExplicitObjectMemberFunction()) {
6196 FromType, ImplicitParamType);
6197 return ICS;
6198 }
6199
6200 // Check the ref-qualifier.
6201 switch (Method->getRefQualifier()) {
6202 case RQ_None:
6203 // Do nothing; we don't care about lvalueness or rvalueness.
6204 break;
6205
6206 case RQ_LValue:
6207 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6208 // non-const lvalue reference cannot bind to an rvalue
6210 ImplicitParamType);
6211 return ICS;
6212 }
6213 break;
6214
6215 case RQ_RValue:
6216 if (!FromClassification.isRValue()) {
6217 // rvalue reference cannot bind to an lvalue
6219 ImplicitParamType);
6220 return ICS;
6221 }
6222 break;
6223 }
6224
6225 // Success. Mark this as a reference binding.
6226 ICS.setStandard();
6228 ICS.Standard.Second = SecondKind;
6229 ICS.Standard.setFromType(FromType);
6230 ICS.Standard.setAllToTypes(ImplicitParamType);
6231 ICS.Standard.ReferenceBinding = true;
6232 ICS.Standard.DirectBinding = true;
6233 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6234 ICS.Standard.BindsToFunctionLvalue = false;
6235 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6236 ICS.Standard.FromBracedInitList = false;
6238 = (Method->getRefQualifier() == RQ_None);
6239 return ICS;
6240}
6241
6242/// PerformObjectArgumentInitialization - Perform initialization of
6243/// the implicit object parameter for the given Method with the given
6244/// expression.
6246 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6248 QualType FromRecordType, DestType;
6249 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6250
6251 Expr::Classification FromClassification;
6252 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6253 FromRecordType = PT->getPointeeType();
6254 DestType = Method->getThisType();
6255 FromClassification = Expr::Classification::makeSimpleLValue();
6256 } else {
6257 FromRecordType = From->getType();
6258 DestType = ImplicitParamRecordType;
6259 FromClassification = From->Classify(Context);
6260
6261 // CWG2813 [expr.call]p6:
6262 // If the function is an implicit object member function, the object
6263 // expression of the class member access shall be a glvalue [...]
6264 if (From->isPRValue()) {
6265 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6266 Method->getRefQualifier() !=
6268 }
6269 }
6270
6271 // Note that we always use the true parent context when performing
6272 // the actual argument initialization.
6274 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6275 Method->getParent());
6276 if (ICS.isBad()) {
6277 switch (ICS.Bad.Kind) {
6279 Qualifiers FromQs = FromRecordType.getQualifiers();
6280 Qualifiers ToQs = DestType.getQualifiers();
6281 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6282 if (CVR) {
6283 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6284 << Method->getDeclName() << FromRecordType << (CVR - 1)
6285 << From->getSourceRange();
6286 Diag(Method->getLocation(), diag::note_previous_decl)
6287 << Method->getDeclName();
6288 return ExprError();
6289 }
6290 break;
6291 }
6292
6295 bool IsRValueQualified =
6296 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6297 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6298 << Method->getDeclName() << FromClassification.isRValue()
6299 << IsRValueQualified;
6300 Diag(Method->getLocation(), diag::note_previous_decl)
6301 << Method->getDeclName();
6302 return ExprError();
6303 }
6304
6307 break;
6308
6311 llvm_unreachable("Lists are not objects");
6312 }
6313
6314 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6315 << ImplicitParamRecordType << FromRecordType
6316 << From->getSourceRange();
6317 }
6318
6319 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6320 ExprResult FromRes =
6321 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6322 if (FromRes.isInvalid())
6323 return ExprError();
6324 From = FromRes.get();
6325 }
6326
6327 if (!Context.hasSameType(From->getType(), DestType)) {
6328 CastKind CK;
6329 QualType PteeTy = DestType->getPointeeType();
6330 LangAS DestAS =
6331 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6332 if (FromRecordType.getAddressSpace() != DestAS)
6333 CK = CK_AddressSpaceConversion;
6334 else
6335 CK = CK_NoOp;
6336 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6337 }
6338 return From;
6339}
6340
6341/// TryContextuallyConvertToBool - Attempt to contextually convert the
6342/// expression From to bool (C++0x [conv]p3).
6345 // C++ [dcl.init]/17.8:
6346 // - Otherwise, if the initialization is direct-initialization, the source
6347 // type is std::nullptr_t, and the destination type is bool, the initial
6348 // value of the object being initialized is false.
6349 if (From->getType()->isNullPtrType())
6351 S.Context.BoolTy,
6352 From->isGLValue());
6353
6354 // All other direct-initialization of bool is equivalent to an implicit
6355 // conversion to bool in which explicit conversions are permitted.
6356 return TryImplicitConversion(S, From, S.Context.BoolTy,
6357 /*SuppressUserConversions=*/false,
6358 AllowedExplicit::Conversions,
6359 /*InOverloadResolution=*/false,
6360 /*CStyle=*/false,
6361 /*AllowObjCWritebackConversion=*/false,
6362 /*AllowObjCConversionOnExplicit=*/false);
6363}
6364
6366 if (checkPlaceholderForOverload(*this, From))
6367 return ExprError();
6368
6370 if (!ICS.isBad())
6371 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6373
6375 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6376 << From->getType() << From->getSourceRange();
6377 return ExprError();
6378}
6379
6380/// Check that the specified conversion is permitted in a converted constant
6381/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6382/// is acceptable.
6385 // Since we know that the target type is an integral or unscoped enumeration
6386 // type, most conversion kinds are impossible. All possible First and Third
6387 // conversions are fine.
6388 switch (SCS.Second) {
6389 case ICK_Identity:
6391 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6393 return true;
6394
6396 // Conversion from an integral or unscoped enumeration type to bool is
6397 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6398 // conversion, so we allow it in a converted constant expression.
6399 //
6400 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6401 // a lot of popular code. We should at least add a warning for this
6402 // (non-conforming) extension.
6404 SCS.getToType(2)->isBooleanType();
6405
6407 case ICK_Pointer_Member:
6408 // C++1z: null pointer conversions and null member pointer conversions are
6409 // only permitted if the source type is std::nullptr_t.
6410 return SCS.getFromType()->isNullPtrType();
6411
6424 case ICK_Vector_Splat:
6425 case ICK_Complex_Real:
6435 return false;
6436
6441 llvm_unreachable("found a first conversion kind in Second");
6442
6444 case ICK_Qualification:
6445 llvm_unreachable("found a third conversion kind in Second");
6446
6448 break;
6449 }
6450
6451 llvm_unreachable("unknown conversion kind");
6452}
6453
6454/// BuildConvertedConstantExpression - Check that the expression From is a
6455/// converted constant expression of type T, perform the conversion but
6456/// does not evaluate the expression
6458 QualType T, CCEKind CCE,
6459 NamedDecl *Dest,
6460 APValue &PreNarrowingValue) {
6461 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6463 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6464 "converted constant expression outside C++11 or TTP matching");
6465
6466 if (checkPlaceholderForOverload(S, From))
6467 return ExprError();
6468
6469 if (From->containsErrors()) {
6470 // The expression already has errors, so the correct cast kind can't be
6471 // determined. Use RecoveryExpr to keep the expected type T and mark the
6472 // result as invalid, preventing further cascading errors.
6473 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6474 T);
6475 }
6476
6477 // C++1z [expr.const]p3:
6478 // A converted constant expression of type T is an expression,
6479 // implicitly converted to type T, where the converted
6480 // expression is a constant expression and the implicit conversion
6481 // sequence contains only [... list of conversions ...].
6483 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6485 : TryCopyInitialization(S, From, T,
6486 /*SuppressUserConversions=*/false,
6487 /*InOverloadResolution=*/false,
6488 /*AllowObjCWritebackConversion=*/false,
6489 /*AllowExplicit=*/false);
6490 StandardConversionSequence *SCS = nullptr;
6491 switch (ICS.getKind()) {
6493 SCS = &ICS.Standard;
6494 break;
6496 if (T->isRecordType())
6497 SCS = &ICS.UserDefined.Before;
6498 else
6499 SCS = &ICS.UserDefined.After;
6500 break;
6504 return S.Diag(From->getBeginLoc(),
6505 diag::err_typecheck_converted_constant_expression)
6506 << From->getType() << From->getSourceRange() << T;
6507 return ExprError();
6508
6511 llvm_unreachable("bad conversion in converted constant expression");
6512 }
6513
6514 // Check that we would only use permitted conversions.
6515 if (!CheckConvertedConstantConversions(S, *SCS)) {
6516 return S.Diag(From->getBeginLoc(),
6517 diag::err_typecheck_converted_constant_expression_disallowed)
6518 << From->getType() << From->getSourceRange() << T;
6519 }
6520 // [...] and where the reference binding (if any) binds directly.
6521 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6522 return S.Diag(From->getBeginLoc(),
6523 diag::err_typecheck_converted_constant_expression_indirect)
6524 << From->getType() << From->getSourceRange() << T;
6525 }
6526 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6527 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6528 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6529 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6530 // case explicitly.
6531 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6532 return S.Diag(From->getBeginLoc(),
6533 diag::err_reference_bind_to_bitfield_in_cce)
6534 << From->getSourceRange();
6535 }
6536
6537 // Usually we can simply apply the ImplicitConversionSequence we formed
6538 // earlier, but that's not guaranteed to work when initializing an object of
6539 // class type.
6540 ExprResult Result;
6541 bool IsTemplateArgument =
6543 if (T->isRecordType()) {
6544 assert(IsTemplateArgument &&
6545 "unexpected class type converted constant expr");
6546 Result = S.PerformCopyInitialization(
6549 SourceLocation(), From);
6550 } else {
6551 Result =
6553 }
6554 if (Result.isInvalid())
6555 return Result;
6556
6557 // C++2a [intro.execution]p5:
6558 // A full-expression is [...] a constant-expression [...]
6559 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6560 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6561 IsTemplateArgument);
6562 if (Result.isInvalid())
6563 return Result;
6564
6565 // Check for a narrowing implicit conversion.
6566 bool ReturnPreNarrowingValue = false;
6567 QualType PreNarrowingType;
6568 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6569 PreNarrowingType)) {
6571 // Implicit conversion to a narrower type, and the value is not a constant
6572 // expression. We'll diagnose this in a moment.
6573 case NK_Not_Narrowing:
6574 break;
6575
6577 if (CCE == CCEKind::ArrayBound &&
6578 PreNarrowingType->isIntegralOrEnumerationType() &&
6579 PreNarrowingValue.isInt()) {
6580 // Don't diagnose array bound narrowing here; we produce more precise
6581 // errors by allowing the un-narrowed value through.
6582 ReturnPreNarrowingValue = true;
6583 break;
6584 }
6585 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6586 << CCE << /*Constant*/ 1
6587 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6588 // If this is an SFINAE Context, treat the result as invalid so it stops
6589 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6590 // FIXME: Should do this whenever the above diagnostic is an error, but
6591 // without further changes this would degrade some other diagnostics.
6592 if (S.isSFINAEContext())
6593 return ExprError();
6594 break;
6595
6597 // Implicit conversion to a narrower type, but the expression is
6598 // value-dependent so we can't tell whether it's actually narrowing.
6599 // For matching the parameters of a TTP, the conversion is ill-formed
6600 // if it may narrow.
6601 if (CCE != CCEKind::TempArgStrict)
6602 break;
6603 [[fallthrough]];
6604 case NK_Type_Narrowing:
6605 // FIXME: It would be better to diagnose that the expression is not a
6606 // constant expression.
6607 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6608 << CCE << /*Constant*/ 0 << From->getType() << T;
6609 if (S.isSFINAEContext())
6610 return ExprError();
6611 break;
6612 }
6613 if (!ReturnPreNarrowingValue)
6614 PreNarrowingValue = {};
6615
6616 return Result;
6617}
6618
6619/// CheckConvertedConstantExpression - Check that the expression From is a
6620/// converted constant expression of type T, perform the conversion and produce
6621/// the converted expression, per C++11 [expr.const]p3.
6624 CCEKind CCE, bool RequireInt,
6625 NamedDecl *Dest) {
6626
6627 APValue PreNarrowingValue;
6628 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6629 PreNarrowingValue);
6630 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6631 Value = APValue();
6632 return Result;
6633 }
6634 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6635 RequireInt, PreNarrowingValue);
6636}
6637
6639 CCEKind CCE,
6640 NamedDecl *Dest) {
6641 APValue PreNarrowingValue;
6642 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6643 PreNarrowingValue);
6644}
6645
6647 APValue &Value, CCEKind CCE,
6648 NamedDecl *Dest) {
6649 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6650 Dest);
6651}
6652
6654 llvm::APSInt &Value,
6655 CCEKind CCE) {
6656 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6657
6658 APValue V;
6659 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6660 /*Dest=*/nullptr);
6661 if (!R.isInvalid() && !R.get()->isValueDependent())
6662 Value = V.getInt();
6663 return R;
6664}
6665
6668 CCEKind CCE, bool RequireInt,
6669 const APValue &PreNarrowingValue) {
6670
6671 ExprResult Result = E;
6672 // Check the expression is a constant expression.
6674 Expr::EvalResult Eval;
6675 Eval.Diag = &Notes;
6676
6677 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6678
6679 ConstantExprKind Kind;
6680 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6681 Kind = ConstantExprKind::ClassTemplateArgument;
6682 else if (CCE == CCEKind::TemplateArg)
6683 Kind = ConstantExprKind::NonClassTemplateArgument;
6684 else
6685 Kind = ConstantExprKind::Normal;
6686
6687 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6688 (RequireInt && !Eval.Val.isInt())) {
6689 // The expression can't be folded, so we can't keep it at this position in
6690 // the AST.
6691 Result = ExprError();
6692 } else {
6693 Value = Eval.Val;
6694
6695 if (Notes.empty()) {
6696 // It's a constant expression.
6697 Expr *E = Result.get();
6698 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6699 // We expect a ConstantExpr to have a value associated with it
6700 // by this point.
6701 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6702 "ConstantExpr has no value associated with it");
6703 (void)CE;
6704 } else {
6706 }
6707 if (!PreNarrowingValue.isAbsent())
6708 Value = std::move(PreNarrowingValue);
6709 return E;
6710 }
6711 }
6712
6713 // It's not a constant expression. Produce an appropriate diagnostic.
6714 if (Notes.size() == 1 &&
6715 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6716 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6717 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6718 diag::note_constexpr_invalid_template_arg) {
6719 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6720 for (unsigned I = 0; I < Notes.size(); ++I)
6721 Diag(Notes[I].first, Notes[I].second);
6722 } else {
6723 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6724 << CCE << E->getSourceRange();
6725 for (unsigned I = 0; I < Notes.size(); ++I)
6726 Diag(Notes[I].first, Notes[I].second);
6727 }
6728 return ExprError();
6729}
6730
6731/// dropPointerConversions - If the given standard conversion sequence
6732/// involves any pointer conversions, remove them. This may change
6733/// the result type of the conversion sequence.
6735 if (SCS.Second == ICK_Pointer_Conversion) {
6736 SCS.Second = ICK_Identity;
6737 SCS.Dimension = ICK_Identity;
6738 SCS.Third = ICK_Identity;
6739 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6740 }
6741}
6742
6743/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6744/// convert the expression From to an Objective-C pointer type.
6745static ImplicitConversionSequence
6747 // Do an implicit conversion to 'id'.
6750 = TryImplicitConversion(S, From, Ty,
6751 // FIXME: Are these flags correct?
6752 /*SuppressUserConversions=*/false,
6753 AllowedExplicit::Conversions,
6754 /*InOverloadResolution=*/false,
6755 /*CStyle=*/false,
6756 /*AllowObjCWritebackConversion=*/false,
6757 /*AllowObjCConversionOnExplicit=*/true);
6758
6759 // Strip off any final conversions to 'id'.
6760 switch (ICS.getKind()) {
6765 break;
6766
6769 break;
6770
6773 break;
6774 }
6775
6776 return ICS;
6777}
6778
6780 if (checkPlaceholderForOverload(*this, From))
6781 return ExprError();
6782
6783 QualType Ty = Context.getObjCIdType();
6786 if (!ICS.isBad())
6787 return PerformImplicitConversion(From, Ty, ICS,
6789 return ExprResult();
6790}
6791
6792static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6793 const Expr *Base = nullptr;
6794 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6795 "expected a member expression");
6796
6797 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6798 M && !M->isImplicitAccess())
6799 Base = M->getBase();
6800 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6801 M && !M->isImplicitAccess())
6802 Base = M->getBase();
6803
6804 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6805
6806 if (T->isPointerType())
6807 T = T->getPointeeType();
6808
6809 return T;
6810}
6811
6813 const FunctionDecl *Fun) {
6814 QualType ObjType = Obj->getType();
6815 if (ObjType->isPointerType()) {
6816 ObjType = ObjType->getPointeeType();
6817 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6819 /*CanOverflow=*/false, FPOptionsOverride());
6820 }
6821 return Obj;
6822}
6823
6831
6833 Expr *Object, MultiExprArg &Args,
6834 SmallVectorImpl<Expr *> &NewArgs) {
6835 assert(Method->isExplicitObjectMemberFunction() &&
6836 "Method is not an explicit member function");
6837 assert(NewArgs.empty() && "NewArgs should be empty");
6838
6839 NewArgs.reserve(Args.size() + 1);
6840 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6841 NewArgs.push_back(This);
6842 NewArgs.append(Args.begin(), Args.end());
6843 Args = NewArgs;
6845 Method, Object->getBeginLoc());
6846}
6847
6848/// Determine whether the provided type is an integral type, or an enumeration
6849/// type of a permitted flavor.
6851 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6852 : T->isIntegralOrUnscopedEnumerationType();
6853}
6854
6855static ExprResult
6858 QualType T, UnresolvedSetImpl &ViableConversions) {
6859
6860 if (Converter.Suppress)
6861 return ExprError();
6862
6863 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6864 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6865 CXXConversionDecl *Conv =
6866 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6868 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6869 }
6870 return From;
6871}
6872
6873static bool
6876 QualType T, bool HadMultipleCandidates,
6877 UnresolvedSetImpl &ExplicitConversions) {
6878 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6879 DeclAccessPair Found = ExplicitConversions[0];
6880 CXXConversionDecl *Conversion =
6881 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6882
6883 // The user probably meant to invoke the given explicit
6884 // conversion; use it.
6885 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6886 std::string TypeStr;
6887 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6888
6889 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6891 "static_cast<" + TypeStr + ">(")
6893 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6894 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6895
6896 // If we aren't in a SFINAE context, build a call to the
6897 // explicit conversion function.
6898 if (SemaRef.isSFINAEContext())
6899 return true;
6900
6901 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6902 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6903 HadMultipleCandidates);
6904 if (Result.isInvalid())
6905 return true;
6906
6907 // Replace the conversion with a RecoveryExpr, so we don't try to
6908 // instantiate it later, but can further diagnose here.
6909 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6910 From, Result.get()->getType());
6911 if (Result.isInvalid())
6912 return true;
6913 From = Result.get();
6914 }
6915 return false;
6916}
6917
6918static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6920 QualType T, bool HadMultipleCandidates,
6922 CXXConversionDecl *Conversion =
6923 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6924 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6925
6926 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6927 if (!Converter.SuppressConversion) {
6928 if (SemaRef.isSFINAEContext())
6929 return true;
6930
6931 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6932 << From->getSourceRange();
6933 }
6934
6935 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6936 HadMultipleCandidates);
6937 if (Result.isInvalid())
6938 return true;
6939 // Record usage of conversion in an implicit cast.
6940 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6941 CK_UserDefinedConversion, Result.get(),
6942 nullptr, Result.get()->getValueKind(),
6943 SemaRef.CurFPFeatureOverrides());
6944 return false;
6945}
6946
6948 Sema &SemaRef, SourceLocation Loc, Expr *From,
6950 if (!Converter.match(From->getType()) && !Converter.Suppress)
6951 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6952 << From->getSourceRange();
6953
6954 return SemaRef.DefaultLvalueConversion(From);
6955}
6956
6957static void
6959 UnresolvedSetImpl &ViableConversions,
6960 OverloadCandidateSet &CandidateSet) {
6961 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6962 NamedDecl *D = FoundDecl.getDecl();
6963 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6964 if (isa<UsingShadowDecl>(D))
6965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6966
6967 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6969 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6970 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6971 continue;
6972 }
6974 SemaRef.AddConversionCandidate(
6975 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6976 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6977 }
6978}
6979
6980/// Attempt to convert the given expression to a type which is accepted
6981/// by the given converter.
6982///
6983/// This routine will attempt to convert an expression of class type to a
6984/// type accepted by the specified converter. In C++11 and before, the class
6985/// must have a single non-explicit conversion function converting to a matching
6986/// type. In C++1y, there can be multiple such conversion functions, but only
6987/// one target type.
6988///
6989/// \param Loc The source location of the construct that requires the
6990/// conversion.
6991///
6992/// \param From The expression we're converting from.
6993///
6994/// \param Converter Used to control and diagnose the conversion process.
6995///
6996/// \returns The expression, converted to an integral or enumeration type if
6997/// successful.
6999 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7000 // We can't perform any more checking for type-dependent expressions.
7001 if (From->isTypeDependent())
7002 return From;
7003
7004 // Process placeholders immediately.
7005 if (From->hasPlaceholderType()) {
7006 ExprResult result = CheckPlaceholderExpr(From);
7007 if (result.isInvalid())
7008 return result;
7009 From = result.get();
7010 }
7011
7012 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7013 ExprResult Converted = DefaultLvalueConversion(From);
7014 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7015 // If the expression already has a matching type, we're golden.
7016 if (Converter.match(T))
7017 return Converted;
7018
7019 // FIXME: Check for missing '()' if T is a function type?
7020
7021 // We can only perform contextual implicit conversions on objects of class
7022 // type.
7023 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7024 if (!RecordTy || !getLangOpts().CPlusPlus) {
7025 if (!Converter.Suppress)
7026 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7027 return From;
7028 }
7029
7030 // We must have a complete class type.
7031 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7032 ContextualImplicitConverter &Converter;
7033 Expr *From;
7034
7035 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7036 : Converter(Converter), From(From) {}
7037
7038 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7039 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7040 }
7041 } IncompleteDiagnoser(Converter, From);
7042
7043 if (Converter.Suppress ? !isCompleteType(Loc, T)
7044 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7045 return From;
7046
7047 // Look for a conversion to an integral or enumeration type.
7049 ViableConversions; // These are *potentially* viable in C++1y.
7050 UnresolvedSet<4> ExplicitConversions;
7051 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7052 ->getDefinitionOrSelf()
7053 ->getVisibleConversionFunctions();
7054
7055 bool HadMultipleCandidates =
7056 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7057
7058 // To check that there is only one target type, in C++1y:
7059 QualType ToType;
7060 bool HasUniqueTargetType = true;
7061
7062 // Collect explicit or viable (potentially in C++1y) conversions.
7063 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7064 NamedDecl *D = (*I)->getUnderlyingDecl();
7065 CXXConversionDecl *Conversion;
7066 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7067 if (ConvTemplate) {
7069 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7070 else
7071 continue; // C++11 does not consider conversion operator templates(?).
7072 } else
7073 Conversion = cast<CXXConversionDecl>(D);
7074
7075 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7076 "Conversion operator templates are considered potentially "
7077 "viable in C++1y");
7078
7079 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7080 if (Converter.match(CurToType) || ConvTemplate) {
7081
7082 if (Conversion->isExplicit()) {
7083 // FIXME: For C++1y, do we need this restriction?
7084 // cf. diagnoseNoViableConversion()
7085 if (!ConvTemplate)
7086 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7087 } else {
7088 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7089 if (ToType.isNull())
7090 ToType = CurToType.getUnqualifiedType();
7091 else if (HasUniqueTargetType &&
7092 (CurToType.getUnqualifiedType() != ToType))
7093 HasUniqueTargetType = false;
7094 }
7095 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7096 }
7097 }
7098 }
7099
7100 if (getLangOpts().CPlusPlus14) {
7101 // C++1y [conv]p6:
7102 // ... An expression e of class type E appearing in such a context
7103 // is said to be contextually implicitly converted to a specified
7104 // type T and is well-formed if and only if e can be implicitly
7105 // converted to a type T that is determined as follows: E is searched
7106 // for conversion functions whose return type is cv T or reference to
7107 // cv T such that T is allowed by the context. There shall be
7108 // exactly one such T.
7109
7110 // If no unique T is found:
7111 if (ToType.isNull()) {
7112 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7113 HadMultipleCandidates,
7114 ExplicitConversions))
7115 return ExprError();
7116 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7117 }
7118
7119 // If more than one unique Ts are found:
7120 if (!HasUniqueTargetType)
7121 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7122 ViableConversions);
7123
7124 // If one unique T is found:
7125 // First, build a candidate set from the previously recorded
7126 // potentially viable conversions.
7128 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7129 CandidateSet);
7130
7131 // Then, perform overload resolution over the candidate set.
7133 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7134 case OR_Success: {
7135 // Apply this conversion.
7137 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7138 if (recordConversion(*this, Loc, From, Converter, T,
7139 HadMultipleCandidates, Found))
7140 return ExprError();
7141 break;
7142 }
7143 case OR_Ambiguous:
7144 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7145 ViableConversions);
7147 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7148 HadMultipleCandidates,
7149 ExplicitConversions))
7150 return ExprError();
7151 [[fallthrough]];
7152 case OR_Deleted:
7153 // We'll complain below about a non-integral condition type.
7154 break;
7155 }
7156 } else {
7157 switch (ViableConversions.size()) {
7158 case 0: {
7159 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7160 HadMultipleCandidates,
7161 ExplicitConversions))
7162 return ExprError();
7163
7164 // We'll complain below about a non-integral condition type.
7165 break;
7166 }
7167 case 1: {
7168 // Apply this conversion.
7169 DeclAccessPair Found = ViableConversions[0];
7170 if (recordConversion(*this, Loc, From, Converter, T,
7171 HadMultipleCandidates, Found))
7172 return ExprError();
7173 break;
7174 }
7175 default:
7176 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7177 ViableConversions);
7178 }
7179 }
7180
7181 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7182}
7183
7184/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7185/// an acceptable non-member overloaded operator for a call whose
7186/// arguments have types T1 (and, if non-empty, T2). This routine
7187/// implements the check in C++ [over.match.oper]p3b2 concerning
7188/// enumeration types.
7190 FunctionDecl *Fn,
7191 ArrayRef<Expr *> Args) {
7192 QualType T1 = Args[0]->getType();
7193 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7194
7195 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7196 return true;
7197
7198 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7199 return true;
7200
7201 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7202 if (Proto->getNumParams() < 1)
7203 return false;
7204
7205 if (T1->isEnumeralType()) {
7206 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7207 if (Context.hasSameUnqualifiedType(T1, ArgType))
7208 return true;
7209 }
7210
7211 if (Proto->getNumParams() < 2)
7212 return false;
7213
7214 if (!T2.isNull() && T2->isEnumeralType()) {
7215 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7216 if (Context.hasSameUnqualifiedType(T2, ArgType))
7217 return true;
7218 }
7219
7220 return false;
7221}
7222
7225 return false;
7226
7227 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7228 return FD->isTargetMultiVersion();
7229
7230 if (!FD->isMultiVersion())
7231 return false;
7232
7233 // Among multiple target versions consider either the default,
7234 // or the first non-default in the absence of default version.
7235 unsigned SeenAt = 0;
7236 unsigned I = 0;
7237 bool HasDefault = false;
7239 FD, [&](const FunctionDecl *CurFD) {
7240 if (FD == CurFD)
7241 SeenAt = I;
7242 else if (CurFD->isTargetMultiVersionDefault())
7243 HasDefault = true;
7244 ++I;
7245 });
7246 return HasDefault || SeenAt != 0;
7247}
7248
7251 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7252 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7253 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7254 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7255 bool StrictPackMatch) {
7256 const FunctionProtoType *Proto
7257 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7258 assert(Proto && "Functions without a prototype cannot be overloaded");
7259 assert(!Function->getDescribedFunctionTemplate() &&
7260 "Use AddTemplateOverloadCandidate for function templates");
7261
7262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7264 // If we get here, it's because we're calling a member function
7265 // that is named without a member access expression (e.g.,
7266 // "this->f") that was either written explicitly or created
7267 // implicitly. This can happen with a qualified call to a member
7268 // function, e.g., X::f(). We use an empty type for the implied
7269 // object argument (C++ [over.call.func]p3), and the acting context
7270 // is irrelevant.
7271 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7273 CandidateSet, SuppressUserConversions,
7274 PartialOverloading, EarlyConversions, PO,
7275 StrictPackMatch);
7276 return;
7277 }
7278 // We treat a constructor like a non-member function, since its object
7279 // argument doesn't participate in overload resolution.
7280 }
7281
7282 if (!CandidateSet.isNewCandidate(Function, PO))
7283 return;
7284
7285 // C++11 [class.copy]p11: [DR1402]
7286 // A defaulted move constructor that is defined as deleted is ignored by
7287 // overload resolution.
7288 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7289 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7290 Constructor->isMoveConstructor())
7291 return;
7292
7293 // Overload resolution is always an unevaluated context.
7296
7297 // C++ [over.match.oper]p3:
7298 // if no operand has a class type, only those non-member functions in the
7299 // lookup set that have a first parameter of type T1 or "reference to
7300 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7301 // is a right operand) a second parameter of type T2 or "reference to
7302 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7303 // candidate functions.
7304 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7306 return;
7307
7308 // Add this candidate
7309 OverloadCandidate &Candidate =
7310 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7311 Candidate.FoundDecl = FoundDecl;
7312 Candidate.Function = Function;
7313 Candidate.Viable = true;
7314 Candidate.RewriteKind =
7315 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7316 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7317 Candidate.ExplicitCallArguments = Args.size();
7318 Candidate.StrictPackMatch = StrictPackMatch;
7319
7320 // Explicit functions are not actually candidates at all if we're not
7321 // allowing them in this context, but keep them around so we can point
7322 // to them in diagnostics.
7323 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7324 Candidate.Viable = false;
7325 Candidate.FailureKind = ovl_fail_explicit;
7326 return;
7327 }
7328
7329 // Functions with internal linkage are only viable in the same module unit.
7330 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7331 /// FIXME: Currently, the semantics of linkage in clang is slightly
7332 /// different from the semantics in C++ spec. In C++ spec, only names
7333 /// have linkage. So that all entities of the same should share one
7334 /// linkage. But in clang, different entities of the same could have
7335 /// different linkage.
7336 const NamedDecl *ND = Function;
7337 bool IsImplicitlyInstantiated = false;
7338 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7339 ND = SpecInfo->getTemplate();
7340 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7342 }
7343
7344 /// Don't remove inline functions with internal linkage from the overload
7345 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7346 /// However:
7347 /// - Inline functions with internal linkage are a common pattern in
7348 /// headers to avoid ODR issues.
7349 /// - The global module is meant to be a transition mechanism for C and C++
7350 /// headers, and the current rules as written work against that goal.
7351 const bool IsInlineFunctionInGMF =
7352 Function->isFromGlobalModule() &&
7353 (IsImplicitlyInstantiated || Function->isInlined());
7354
7355 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7356 Candidate.Viable = false;
7358 return;
7359 }
7360 }
7361
7363 Candidate.Viable = false;
7365 return;
7366 }
7367
7368 if (Constructor) {
7369 // C++ [class.copy]p3:
7370 // A member function template is never instantiated to perform the copy
7371 // of a class object to an object of its class type.
7372 CanQualType ClassType =
7373 Context.getCanonicalTagType(Constructor->getParent());
7374 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7375 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7376 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7377 ClassType))) {
7378 Candidate.Viable = false;
7380 return;
7381 }
7382
7383 // C++ [over.match.funcs]p8: (proposed DR resolution)
7384 // A constructor inherited from class type C that has a first parameter
7385 // of type "reference to P" (including such a constructor instantiated
7386 // from a template) is excluded from the set of candidate functions when
7387 // constructing an object of type cv D if the argument list has exactly
7388 // one argument and D is reference-related to P and P is reference-related
7389 // to C.
7390 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7391 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7392 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7393 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7394 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7395 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7396 SourceLocation Loc = Args.front()->getExprLoc();
7397 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7398 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7399 Candidate.Viable = false;
7401 return;
7402 }
7403 }
7404
7405 // Check that the constructor is capable of constructing an object in the
7406 // destination address space.
7408 Constructor->getMethodQualifiers().getAddressSpace(),
7409 CandidateSet.getDestAS(), getASTContext())) {
7410 Candidate.Viable = false;
7412 }
7413 }
7414
7415 unsigned NumParams = Proto->getNumParams();
7416
7417 // (C++ 13.3.2p2): A candidate function having fewer than m
7418 // parameters is viable only if it has an ellipsis in its parameter
7419 // list (8.3.5).
7420 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7421 !Proto->isVariadic() &&
7422 shouldEnforceArgLimit(PartialOverloading, Function)) {
7423 Candidate.Viable = false;
7425 return;
7426 }
7427
7428 // (C++ 13.3.2p2): A candidate function having more than m parameters
7429 // is viable only if the (m+1)st parameter has a default argument
7430 // (8.3.6). For the purposes of overload resolution, the
7431 // parameter list is truncated on the right, so that there are
7432 // exactly m parameters.
7433 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7434 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7435 !PartialOverloading) {
7436 // Not enough arguments.
7437 Candidate.Viable = false;
7439 return;
7440 }
7441
7442 // (CUDA B.1): Check for invalid calls between targets.
7443 if (getLangOpts().CUDA) {
7444 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7445 // Skip the check for callers that are implicit members, because in this
7446 // case we may not yet know what the member's target is; the target is
7447 // inferred for the member automatically, based on the bases and fields of
7448 // the class.
7449 if (!(Caller && Caller->isImplicit()) &&
7450 !CUDA().IsAllowedCall(Caller, Function)) {
7451 Candidate.Viable = false;
7452 Candidate.FailureKind = ovl_fail_bad_target;
7453 return;
7454 }
7455 }
7456
7457 if (Function->getTrailingRequiresClause()) {
7458 ConstraintSatisfaction Satisfaction;
7459 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7460 /*ForOverloadResolution*/ true) ||
7461 !Satisfaction.IsSatisfied) {
7462 Candidate.Viable = false;
7464 return;
7465 }
7466 }
7467
7468 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7469 // Determine the implicit conversion sequences for each of the
7470 // arguments.
7471 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7472 unsigned ConvIdx =
7473 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7474 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7475 // We already formed a conversion sequence for this parameter during
7476 // template argument deduction.
7477 } else if (ArgIdx < NumParams) {
7478 // (C++ 13.3.2p3): for F to be a viable function, there shall
7479 // exist for each argument an implicit conversion sequence
7480 // (13.3.3.1) that converts that argument to the corresponding
7481 // parameter of F.
7482 QualType ParamType = Proto->getParamType(ArgIdx);
7483 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7484 if (ParamABI == ParameterABI::HLSLOut ||
7485 ParamABI == ParameterABI::HLSLInOut) {
7486 ParamType = ParamType.getNonReferenceType();
7487 if (ParamABI == ParameterABI::HLSLInOut &&
7488 Args[ArgIdx]->getType().getAddressSpace() ==
7490 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7491 }
7492 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7493 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7494 /*InOverloadResolution=*/true,
7495 /*AllowObjCWritebackConversion=*/
7496 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7497 if (Candidate.Conversions[ConvIdx].isBad()) {
7498 Candidate.Viable = false;
7500 return;
7501 }
7502 } else {
7503 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7504 // argument for which there is no corresponding parameter is
7505 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7506 Candidate.Conversions[ConvIdx].setEllipsis();
7507 }
7508 }
7509
7510 if (EnableIfAttr *FailedAttr =
7511 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7512 Candidate.Viable = false;
7513 Candidate.FailureKind = ovl_fail_enable_if;
7514 Candidate.DeductionFailure.Data = FailedAttr;
7515 return;
7516 }
7517}
7518
7522 if (Methods.size() <= 1)
7523 return nullptr;
7524
7525 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7526 bool Match = true;
7527 ObjCMethodDecl *Method = Methods[b];
7528 unsigned NumNamedArgs = Sel.getNumArgs();
7529 // Method might have more arguments than selector indicates. This is due
7530 // to addition of c-style arguments in method.
7531 if (Method->param_size() > NumNamedArgs)
7532 NumNamedArgs = Method->param_size();
7533 if (Args.size() < NumNamedArgs)
7534 continue;
7535
7536 for (unsigned i = 0; i < NumNamedArgs; i++) {
7537 // We can't do any type-checking on a type-dependent argument.
7538 if (Args[i]->isTypeDependent()) {
7539 Match = false;
7540 break;
7541 }
7542
7543 ParmVarDecl *param = Method->parameters()[i];
7544 Expr *argExpr = Args[i];
7545 assert(argExpr && "SelectBestMethod(): missing expression");
7546
7547 // Strip the unbridged-cast placeholder expression off unless it's
7548 // a consumed argument.
7549 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7550 !param->hasAttr<CFConsumedAttr>())
7551 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7552
7553 // If the parameter is __unknown_anytype, move on to the next method.
7554 if (param->getType() == Context.UnknownAnyTy) {
7555 Match = false;
7556 break;
7557 }
7558
7559 ImplicitConversionSequence ConversionState
7560 = TryCopyInitialization(*this, argExpr, param->getType(),
7561 /*SuppressUserConversions*/false,
7562 /*InOverloadResolution=*/true,
7563 /*AllowObjCWritebackConversion=*/
7564 getLangOpts().ObjCAutoRefCount,
7565 /*AllowExplicit*/false);
7566 // This function looks for a reasonably-exact match, so we consider
7567 // incompatible pointer conversions to be a failure here.
7568 if (ConversionState.isBad() ||
7569 (ConversionState.isStandard() &&
7570 ConversionState.Standard.Second ==
7572 Match = false;
7573 break;
7574 }
7575 }
7576 // Promote additional arguments to variadic methods.
7577 if (Match && Method->isVariadic()) {
7578 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7579 if (Args[i]->isTypeDependent()) {
7580 Match = false;
7581 break;
7582 }
7584 Args[i], VariadicCallType::Method, nullptr);
7585 if (Arg.isInvalid()) {
7586 Match = false;
7587 break;
7588 }
7589 }
7590 } else {
7591 // Check for extra arguments to non-variadic methods.
7592 if (Args.size() != NumNamedArgs)
7593 Match = false;
7594 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7595 // Special case when selectors have no argument. In this case, select
7596 // one with the most general result type of 'id'.
7597 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7598 QualType ReturnT = Methods[b]->getReturnType();
7599 if (ReturnT->isObjCIdType())
7600 return Methods[b];
7601 }
7602 }
7603 }
7604
7605 if (Match)
7606 return Method;
7607 }
7608 return nullptr;
7609}
7610
7612 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7613 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7614 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7615 if (ThisArg) {
7616 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7617 assert(!isa<CXXConstructorDecl>(Method) &&
7618 "Shouldn't have `this` for ctors!");
7619 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7621 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7622 if (R.isInvalid())
7623 return false;
7624 ConvertedThis = R.get();
7625 } else {
7626 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7627 (void)MD;
7628 assert((MissingImplicitThis || MD->isStatic() ||
7630 "Expected `this` for non-ctor instance methods");
7631 }
7632 ConvertedThis = nullptr;
7633 }
7634
7635 // Ignore any variadic arguments. Converting them is pointless, since the
7636 // user can't refer to them in the function condition.
7637 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7638
7639 // Convert the arguments.
7640 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7641 ExprResult R;
7643 S.Context, Function->getParamDecl(I)),
7644 SourceLocation(), Args[I]);
7645
7646 if (R.isInvalid())
7647 return false;
7648
7649 ConvertedArgs.push_back(R.get());
7650 }
7651
7652 if (Trap.hasErrorOccurred())
7653 return false;
7654
7655 // Push default arguments if needed.
7656 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7657 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7658 ParmVarDecl *P = Function->getParamDecl(i);
7659 if (!P->hasDefaultArg())
7660 return false;
7661 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7662 if (R.isInvalid())
7663 return false;
7664 ConvertedArgs.push_back(R.get());
7665 }
7666
7667 if (Trap.hasErrorOccurred())
7668 return false;
7669 }
7670 return true;
7671}
7672
7674 SourceLocation CallLoc,
7675 ArrayRef<Expr *> Args,
7676 bool MissingImplicitThis) {
7677 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7678 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7679 return nullptr;
7680
7681 SFINAETrap Trap(*this);
7682 // Perform the access checking immediately so any access diagnostics are
7683 // caught by the SFINAE trap.
7684 llvm::scope_exit UndelayDiags(
7685 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7686 DelayedDiagnostics.popUndelayed(CurrentState);
7687 });
7688 SmallVector<Expr *, 16> ConvertedArgs;
7689 // FIXME: We should look into making enable_if late-parsed.
7690 Expr *DiscardedThis;
7692 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7693 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7694 return *EnableIfAttrs.begin();
7695
7696 for (auto *EIA : EnableIfAttrs) {
7698 // FIXME: This doesn't consider value-dependent cases, because doing so is
7699 // very difficult. Ideally, we should handle them more gracefully.
7700 if (EIA->getCond()->isValueDependent() ||
7701 !EIA->getCond()->EvaluateWithSubstitution(
7702 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7703 return EIA;
7704
7705 if (!Result.isInt() || !Result.getInt().getBoolValue())
7706 return EIA;
7707 }
7708 return nullptr;
7709}
7710
7711template <typename CheckFn>
7713 bool ArgDependent, SourceLocation Loc,
7714 CheckFn &&IsSuccessful) {
7716 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7717 if (ArgDependent == DIA->getArgDependent())
7718 Attrs.push_back(DIA);
7719 }
7720
7721 // Common case: No diagnose_if attributes, so we can quit early.
7722 if (Attrs.empty())
7723 return false;
7724
7725 auto WarningBegin = std::stable_partition(
7726 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7727 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7728 DIA->getWarningGroup().empty();
7729 });
7730
7731 // Note that diagnose_if attributes are late-parsed, so they appear in the
7732 // correct order (unlike enable_if attributes).
7733 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7734 IsSuccessful);
7735 if (ErrAttr != WarningBegin) {
7736 const DiagnoseIfAttr *DIA = *ErrAttr;
7737 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7738 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7739 << DIA->getParent() << DIA->getCond()->getSourceRange();
7740 return true;
7741 }
7742
7743 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7744 switch (Sev) {
7745 case DiagnoseIfAttr::DS_warning:
7747 case DiagnoseIfAttr::DS_error:
7748 return diag::Severity::Error;
7749 }
7750 llvm_unreachable("Fully covered switch above!");
7751 };
7752
7753 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7754 if (IsSuccessful(DIA)) {
7755 if (DIA->getWarningGroup().empty() &&
7756 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7757 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7758 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7759 << DIA->getParent() << DIA->getCond()->getSourceRange();
7760 } else {
7761 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7762 DIA->getWarningGroup());
7763 assert(DiagGroup);
7764 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7765 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7766 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7767 S.Diag(Loc, DiagID) << DIA->getMessage();
7768 }
7769 }
7770
7771 return false;
7772}
7773
7775 const Expr *ThisArg,
7777 SourceLocation Loc) {
7779 *this, Function, /*ArgDependent=*/true, Loc,
7780 [&](const DiagnoseIfAttr *DIA) {
7782 // It's sane to use the same Args for any redecl of this function, since
7783 // EvaluateWithSubstitution only cares about the position of each
7784 // argument in the arg list, not the ParmVarDecl* it maps to.
7785 if (!DIA->getCond()->EvaluateWithSubstitution(
7786 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7787 return false;
7788 return Result.isInt() && Result.getInt().getBoolValue();
7789 });
7790}
7791
7793 SourceLocation Loc) {
7795 *this, ND, /*ArgDependent=*/false, Loc,
7796 [&](const DiagnoseIfAttr *DIA) {
7797 bool Result;
7798 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7799 Result;
7800 });
7801}
7802
7804 ArrayRef<Expr *> Args,
7805 OverloadCandidateSet &CandidateSet,
7806 TemplateArgumentListInfo *ExplicitTemplateArgs,
7807 bool SuppressUserConversions,
7808 bool PartialOverloading,
7809 bool FirstArgumentIsBase) {
7810 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7811 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7812 ArrayRef<Expr *> FunctionArgs = Args;
7813
7814 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7815 FunctionDecl *FD =
7816 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7817
7818 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7819 QualType ObjectType;
7820 Expr::Classification ObjectClassification;
7821 if (Args.size() > 0) {
7822 if (Expr *E = Args[0]) {
7823 // Use the explicit base to restrict the lookup:
7824 ObjectType = E->getType();
7825 // Pointers in the object arguments are implicitly dereferenced, so we
7826 // always classify them as l-values.
7827 if (!ObjectType.isNull() && ObjectType->isPointerType())
7828 ObjectClassification = Expr::Classification::makeSimpleLValue();
7829 else
7830 ObjectClassification = E->Classify(Context);
7831 } // .. else there is an implicit base.
7832 FunctionArgs = Args.slice(1);
7833 }
7834 if (FunTmpl) {
7836 FunTmpl, F.getPair(),
7838 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7839 FunctionArgs, CandidateSet, SuppressUserConversions,
7840 PartialOverloading);
7841 } else {
7842 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7843 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7844 ObjectClassification, FunctionArgs, CandidateSet,
7845 SuppressUserConversions, PartialOverloading);
7846 }
7847 } else {
7848 // This branch handles both standalone functions and static methods.
7849
7850 // Slice the first argument (which is the base) when we access
7851 // static method as non-static.
7852 if (Args.size() > 0 &&
7853 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7854 !isa<CXXConstructorDecl>(FD)))) {
7855 assert(cast<CXXMethodDecl>(FD)->isStatic());
7856 FunctionArgs = Args.slice(1);
7857 }
7858 if (FunTmpl) {
7859 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7860 ExplicitTemplateArgs, FunctionArgs,
7861 CandidateSet, SuppressUserConversions,
7862 PartialOverloading);
7863 } else {
7864 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7865 SuppressUserConversions, PartialOverloading);
7866 }
7867 }
7868 }
7869}
7870
7872 Expr::Classification ObjectClassification,
7873 ArrayRef<Expr *> Args,
7874 OverloadCandidateSet &CandidateSet,
7875 bool SuppressUserConversions,
7877 NamedDecl *Decl = FoundDecl.getDecl();
7879
7881 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7882
7883 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7884 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7885 "Expected a member function template");
7886 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7887 /*ExplicitArgs*/ nullptr, ObjectType,
7888 ObjectClassification, Args, CandidateSet,
7889 SuppressUserConversions, false, PO);
7890 } else {
7891 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7892 ObjectType, ObjectClassification, Args, CandidateSet,
7893 SuppressUserConversions, false, {}, PO);
7894 }
7895}
7896
7899 CXXRecordDecl *ActingContext, QualType ObjectType,
7900 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7901 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7902 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7903 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7904 const FunctionProtoType *Proto
7905 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7906 assert(Proto && "Methods without a prototype cannot be overloaded");
7908 "Use AddOverloadCandidate for constructors");
7909
7910 if (!CandidateSet.isNewCandidate(Method, PO))
7911 return;
7912
7913 // C++11 [class.copy]p23: [DR1402]
7914 // A defaulted move assignment operator that is defined as deleted is
7915 // ignored by overload resolution.
7916 if (Method->isDefaulted() && Method->isDeleted() &&
7917 Method->isMoveAssignmentOperator())
7918 return;
7919
7920 // Overload resolution is always an unevaluated context.
7923
7924 bool IgnoreExplicitObject =
7925 (Method->isExplicitObjectMemberFunction() &&
7926 CandidateSet.getKind() ==
7928 bool ImplicitObjectMethodTreatedAsStatic =
7929 CandidateSet.getKind() ==
7931 Method->isImplicitObjectMemberFunction();
7932
7933 unsigned ExplicitOffset =
7934 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7935
7936 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7937 int(ImplicitObjectMethodTreatedAsStatic);
7938
7939 unsigned ExtraArgs =
7941 ? 0
7942 : 1;
7943
7944 // Add this candidate
7945 OverloadCandidate &Candidate =
7946 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7947 Candidate.FoundDecl = FoundDecl;
7948 Candidate.Function = Method;
7949 Candidate.RewriteKind =
7950 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7951 Candidate.TookAddressOfOverload =
7953 Candidate.ExplicitCallArguments = Args.size();
7954 Candidate.StrictPackMatch = StrictPackMatch;
7955
7956 // (C++ 13.3.2p2): A candidate function having fewer than m
7957 // parameters is viable only if it has an ellipsis in its parameter
7958 // list (8.3.5).
7959 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7960 !Proto->isVariadic() &&
7961 shouldEnforceArgLimit(PartialOverloading, Method)) {
7962 Candidate.Viable = false;
7964 return;
7965 }
7966
7967 // (C++ 13.3.2p2): A candidate function having more than m parameters
7968 // is viable only if the (m+1)st parameter has a default argument
7969 // (8.3.6). For the purposes of overload resolution, the
7970 // parameter list is truncated on the right, so that there are
7971 // exactly m parameters.
7972 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7973 ExplicitOffset +
7974 int(ImplicitObjectMethodTreatedAsStatic);
7975
7976 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7977 // Not enough arguments.
7978 Candidate.Viable = false;
7980 return;
7981 }
7982
7983 Candidate.Viable = true;
7984
7985 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7986 if (!IgnoreExplicitObject) {
7987 if (ObjectType.isNull())
7988 Candidate.IgnoreObjectArgument = true;
7989 else if (Method->isStatic()) {
7990 // [over.best.ics.general]p8
7991 // When the parameter is the implicit object parameter of a static member
7992 // function, the implicit conversion sequence is a standard conversion
7993 // sequence that is neither better nor worse than any other standard
7994 // conversion sequence.
7995 //
7996 // This is a rule that was introduced in C++23 to support static lambdas.
7997 // We apply it retroactively because we want to support static lambdas as
7998 // an extension and it doesn't hurt previous code.
7999 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8000 } else {
8001 // Determine the implicit conversion sequence for the object
8002 // parameter.
8003 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8004 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8005 Method, ActingContext, /*InOverloadResolution=*/true);
8006 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8007 Candidate.Viable = false;
8009 return;
8010 }
8011 }
8012 }
8013
8014 // (CUDA B.1): Check for invalid calls between targets.
8015 if (getLangOpts().CUDA)
8016 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8017 Method)) {
8018 Candidate.Viable = false;
8019 Candidate.FailureKind = ovl_fail_bad_target;
8020 return;
8021 }
8022
8023 if (Method->getTrailingRequiresClause()) {
8024 ConstraintSatisfaction Satisfaction;
8025 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8026 /*ForOverloadResolution*/ true) ||
8027 !Satisfaction.IsSatisfied) {
8028 Candidate.Viable = false;
8030 return;
8031 }
8032 }
8033
8034 // Determine the implicit conversion sequences for each of the
8035 // arguments.
8036 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8037 unsigned ConvIdx =
8038 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8039 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8040 // We already formed a conversion sequence for this parameter during
8041 // template argument deduction.
8042 } else if (ArgIdx < NumParams) {
8043 // (C++ 13.3.2p3): for F to be a viable function, there shall
8044 // exist for each argument an implicit conversion sequence
8045 // (13.3.3.1) that converts that argument to the corresponding
8046 // parameter of F.
8047 QualType ParamType;
8048 if (ImplicitObjectMethodTreatedAsStatic) {
8049 ParamType = ArgIdx == 0
8050 ? Method->getFunctionObjectParameterReferenceType()
8051 : Proto->getParamType(ArgIdx - 1);
8052 } else {
8053 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8054 }
8055 Candidate.Conversions[ConvIdx]
8056 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8057 SuppressUserConversions,
8058 /*InOverloadResolution=*/true,
8059 /*AllowObjCWritebackConversion=*/
8060 getLangOpts().ObjCAutoRefCount);
8061 if (Candidate.Conversions[ConvIdx].isBad()) {
8062 Candidate.Viable = false;
8064 return;
8065 }
8066 } else {
8067 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8068 // argument for which there is no corresponding parameter is
8069 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8070 Candidate.Conversions[ConvIdx].setEllipsis();
8071 }
8072 }
8073
8074 if (EnableIfAttr *FailedAttr =
8075 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8076 Candidate.Viable = false;
8077 Candidate.FailureKind = ovl_fail_enable_if;
8078 Candidate.DeductionFailure.Data = FailedAttr;
8079 return;
8080 }
8081
8083 Candidate.Viable = false;
8085 }
8086}
8087
8089 Sema &S, OverloadCandidateSet &CandidateSet,
8090 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8091 CXXRecordDecl *ActingContext,
8092 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8093 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8094 bool SuppressUserConversions, bool PartialOverloading,
8096
8097 // C++ [over.match.funcs]p7:
8098 // In each case where a candidate is a function template, candidate
8099 // function template specializations are generated using template argument
8100 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8101 // candidate functions in the usual way.113) A given name can refer to one
8102 // or more function templates and also to a set of overloaded non-template
8103 // functions. In such a case, the candidate functions generated from each
8104 // function template are combined with the set of non-template candidate
8105 // functions.
8106 TemplateDeductionInfo Info(CandidateSet.getLocation());
8107 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8108 FunctionDecl *Specialization = nullptr;
8109 ConversionSequenceList Conversions;
8111 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8112 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8113 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8114 CandidateSet.getKind() ==
8116 [&](ArrayRef<QualType> ParamTypes,
8117 bool OnlyInitializeNonUserDefinedConversions) {
8118 return S.CheckNonDependentConversions(
8119 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8120 Sema::CheckNonDependentConversionsFlag(
8121 SuppressUserConversions,
8122 OnlyInitializeNonUserDefinedConversions),
8123 ActingContext, ObjectType, ObjectClassification, PO);
8124 });
8126 OverloadCandidate &Candidate =
8127 CandidateSet.addCandidate(Conversions.size(), Conversions);
8128 Candidate.FoundDecl = FoundDecl;
8129 Candidate.Function = Method;
8130 Candidate.Viable = false;
8131 Candidate.RewriteKind =
8132 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8133 Candidate.IsSurrogate = false;
8134 Candidate.TookAddressOfOverload =
8135 CandidateSet.getKind() ==
8137
8138 Candidate.IgnoreObjectArgument =
8139 Method->isStatic() ||
8140 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8141 Candidate.ExplicitCallArguments = Args.size();
8144 else {
8146 Candidate.DeductionFailure =
8147 MakeDeductionFailureInfo(S.Context, Result, Info);
8148 }
8149 return;
8150 }
8151
8152 // Add the function template specialization produced by template argument
8153 // deduction as a candidate.
8154 assert(Specialization && "Missing member function template specialization?");
8156 "Specialization is not a member function?");
8158 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8159 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8160 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8161}
8162
8164 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8165 CXXRecordDecl *ActingContext,
8166 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8167 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8168 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8169 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8170 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8171 return;
8172
8173 if (ExplicitTemplateArgs ||
8176 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8177 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8178 SuppressUserConversions, PartialOverloading, PO);
8179 return;
8180 }
8181
8183 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8184 Args, SuppressUserConversions, PartialOverloading, PO);
8185}
8186
8187/// Determine whether a given function template has a simple explicit specifier
8188/// or a non-value-dependent explicit-specification that evaluates to true.
8192
8197
8199 Sema &S, OverloadCandidateSet &CandidateSet,
8201 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8202 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8204 bool AggregateCandidateDeduction) {
8205
8206 // If the function template has a non-dependent explicit specification,
8207 // exclude it now if appropriate; we are not permitted to perform deduction
8208 // and substitution in this case.
8209 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8210 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8211 Candidate.FoundDecl = FoundDecl;
8212 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8213 Candidate.Viable = false;
8214 Candidate.FailureKind = ovl_fail_explicit;
8215 return;
8216 }
8217
8218 // C++ [over.match.funcs]p7:
8219 // In each case where a candidate is a function template, candidate
8220 // function template specializations are generated using template argument
8221 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8222 // candidate functions in the usual way.113) A given name can refer to one
8223 // or more function templates and also to a set of overloaded non-template
8224 // functions. In such a case, the candidate functions generated from each
8225 // function template are combined with the set of non-template candidate
8226 // functions.
8227 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8228 FunctionTemplate->getTemplateDepth());
8229 FunctionDecl *Specialization = nullptr;
8230 ConversionSequenceList Conversions;
8232 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8233 PartialOverloading, AggregateCandidateDeduction,
8234 /*PartialOrdering=*/false,
8235 /*ObjectType=*/QualType(),
8236 /*ObjectClassification=*/Expr::Classification(),
8237 CandidateSet.getKind() ==
8239 [&](ArrayRef<QualType> ParamTypes,
8240 bool OnlyInitializeNonUserDefinedConversions) {
8241 return S.CheckNonDependentConversions(
8242 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8243 Sema::CheckNonDependentConversionsFlag(
8244 SuppressUserConversions,
8245 OnlyInitializeNonUserDefinedConversions),
8246 nullptr, QualType(), {}, PO);
8247 });
8249 OverloadCandidate &Candidate =
8250 CandidateSet.addCandidate(Conversions.size(), Conversions);
8251 Candidate.FoundDecl = FoundDecl;
8252 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8253 Candidate.Viable = false;
8254 Candidate.RewriteKind =
8255 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8256 Candidate.IsSurrogate = false;
8257 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8258 // Ignore the object argument if there is one, since we don't have an object
8259 // type.
8260 Candidate.TookAddressOfOverload =
8261 CandidateSet.getKind() ==
8263
8264 Candidate.IgnoreObjectArgument =
8265 isa<CXXMethodDecl>(Candidate.Function) &&
8266 !cast<CXXMethodDecl>(Candidate.Function)
8267 ->isExplicitObjectMemberFunction() &&
8269
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 function template specialization?");
8285 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8286 PartialOverloading, AllowExplicit,
8287 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8288 Info.AggregateDeductionCandidateHasMismatchedArity,
8289 Info.hasStrictPackMatch());
8290}
8291
8294 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8295 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8296 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8297 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8298 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8299 return;
8300
8301 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8302
8303 if (ExplicitTemplateArgs ||
8305 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8306 DependentExplicitSpecifier)) {
8307
8309 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8310 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8311 IsADLCandidate, PO, AggregateCandidateDeduction);
8312
8313 if (DependentExplicitSpecifier)
8315 return;
8316 }
8317
8318 CandidateSet.AddDeferredTemplateCandidate(
8319 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8320 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8321 AggregateCandidateDeduction);
8322}
8323
8326 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8328 CheckNonDependentConversionsFlag UserConversionFlag,
8329 CXXRecordDecl *ActingContext, QualType ObjectType,
8330 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8331 // FIXME: The cases in which we allow explicit conversions for constructor
8332 // arguments never consider calling a constructor template. It's not clear
8333 // that is correct.
8334 const bool AllowExplicit = false;
8335
8336 bool ForOverloadSetAddressResolution =
8338 auto *FD = FunctionTemplate->getTemplatedDecl();
8339 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8340 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8342 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8343
8344 if (Conversions.empty())
8345 Conversions =
8346 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8347
8348 // Overload resolution is always an unevaluated context.
8351
8352 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8353 // require that, but this check should never result in a hard error, and
8354 // overload resolution is permitted to sidestep instantiations.
8355 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8356 !ObjectType.isNull()) {
8357 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8358 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8359 !ParamTypes[0]->isDependentType()) {
8361 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8362 Method, ActingContext, /*InOverloadResolution=*/true,
8363 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8364 : QualType());
8365 if (Conversions[ConvIdx].isBad())
8366 return true;
8367 }
8368 }
8369
8370 // A speculative workaround for self-dependent constraint bugs that manifest
8371 // after CWG2369.
8372 // FIXME: Add references to the standard once P3606 is adopted.
8373 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8374 QualType ArgType) {
8375 ParamType = ParamType.getNonReferenceType();
8376 ArgType = ArgType.getNonReferenceType();
8377 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8378 if (PointerConv) {
8379 ParamType = ParamType->getPointeeType();
8380 ArgType = ArgType->getPointeeType();
8381 }
8382
8383 if (auto *RD = ParamType->getAsCXXRecordDecl();
8384 RD && RD->hasDefinition() &&
8385 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8386 auto Info = getConstructorInfo(ND);
8387 if (!Info)
8388 return false;
8389 CXXConstructorDecl *Ctor = Info.Constructor;
8390 /// isConvertingConstructor takes copy/move constructors into
8391 /// account!
8392 return !Ctor->isCopyOrMoveConstructor() &&
8394 /*AllowExplicit=*/true);
8395 }))
8396 return true;
8397 if (auto *RD = ArgType->getAsCXXRecordDecl();
8398 RD && RD->hasDefinition() &&
8399 !RD->getVisibleConversionFunctions().empty())
8400 return true;
8401
8402 return false;
8403 };
8404
8405 unsigned Offset =
8406 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8407 : 0;
8408
8409 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8410 I != N; ++I) {
8411 QualType ParamType = ParamTypes[I + Offset];
8412 if (!ParamType->isDependentType()) {
8413 unsigned ConvIdx;
8415 ConvIdx = Args.size() - 1 - I;
8416 assert(Args.size() + ThisConversions == 2 &&
8417 "number of args (including 'this') must be exactly 2 for "
8418 "reversed order");
8419 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8420 // would also be 0. 'this' got ConvIdx = 1 previously.
8421 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8422 } else {
8423 // For members, 'this' got ConvIdx = 0 previously.
8424 ConvIdx = ThisConversions + I;
8425 }
8426 if (Conversions[ConvIdx].isInitialized())
8427 continue;
8428 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8429 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8430 continue;
8432 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8433 /*InOverloadResolution=*/true,
8434 /*AllowObjCWritebackConversion=*/
8435 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8436 if (Conversions[ConvIdx].isBad())
8437 return true;
8438 }
8439 }
8440
8441 return false;
8442}
8443
8444/// Determine whether this is an allowable conversion from the result
8445/// of an explicit conversion operator to the expected type, per C++
8446/// [over.match.conv]p1 and [over.match.ref]p1.
8447///
8448/// \param ConvType The return type of the conversion function.
8449///
8450/// \param ToType The type we are converting to.
8451///
8452/// \param AllowObjCPointerConversion Allow a conversion from one
8453/// Objective-C pointer to another.
8454///
8455/// \returns true if the conversion is allowable, false otherwise.
8457 QualType ConvType, QualType ToType,
8458 bool AllowObjCPointerConversion) {
8459 QualType ToNonRefType = ToType.getNonReferenceType();
8460
8461 // Easy case: the types are the same.
8462 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8463 return true;
8464
8465 // Allow qualification conversions.
8466 bool ObjCLifetimeConversion;
8467 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8468 ObjCLifetimeConversion))
8469 return true;
8470
8471 // If we're not allowed to consider Objective-C pointer conversions,
8472 // we're done.
8473 if (!AllowObjCPointerConversion)
8474 return false;
8475
8476 // Is this an Objective-C pointer conversion?
8477 bool IncompatibleObjC = false;
8478 QualType ConvertedType;
8479 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8480 IncompatibleObjC);
8481}
8482
8484 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8485 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8486 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8487 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8488 assert(!Conversion->getDescribedFunctionTemplate() &&
8489 "Conversion function templates use AddTemplateConversionCandidate");
8490 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8491 if (!CandidateSet.isNewCandidate(Conversion))
8492 return;
8493
8494 // If the conversion function has an undeduced return type, trigger its
8495 // deduction now.
8496 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8497 if (DeduceReturnType(Conversion, From->getExprLoc()))
8498 return;
8499 ConvType = Conversion->getConversionType().getNonReferenceType();
8500 }
8501
8502 // If we don't allow any conversion of the result type, ignore conversion
8503 // functions that don't convert to exactly (possibly cv-qualified) T.
8504 if (!AllowResultConversion &&
8505 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8506 return;
8507
8508 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8509 // operator is only a candidate if its return type is the target type or
8510 // can be converted to the target type with a qualification conversion.
8511 //
8512 // FIXME: Include such functions in the candidate list and explain why we
8513 // can't select them.
8514 if (Conversion->isExplicit() &&
8515 !isAllowableExplicitConversion(*this, ConvType, ToType,
8516 AllowObjCConversionOnExplicit))
8517 return;
8518
8519 // Overload resolution is always an unevaluated context.
8522
8523 // Add this candidate
8524 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8525 Candidate.FoundDecl = FoundDecl;
8526 Candidate.Function = Conversion;
8528 Candidate.FinalConversion.setFromType(ConvType);
8529 Candidate.FinalConversion.setAllToTypes(ToType);
8530 Candidate.HasFinalConversion = true;
8531 Candidate.Viable = true;
8532 Candidate.ExplicitCallArguments = 1;
8533 Candidate.StrictPackMatch = StrictPackMatch;
8534
8535 // Explicit functions are not actually candidates at all if we're not
8536 // allowing them in this context, but keep them around so we can point
8537 // to them in diagnostics.
8538 if (!AllowExplicit && Conversion->isExplicit()) {
8539 Candidate.Viable = false;
8540 Candidate.FailureKind = ovl_fail_explicit;
8541 return;
8542 }
8543
8544 // C++ [over.match.funcs]p4:
8545 // For conversion functions, the function is considered to be a member of
8546 // the class of the implicit implied object argument for the purpose of
8547 // defining the type of the implicit object parameter.
8548 //
8549 // Determine the implicit conversion sequence for the implicit
8550 // object parameter.
8551 QualType ObjectType = From->getType();
8552 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8553 ObjectType = FromPtrType->getPointeeType();
8554 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8555 // C++23 [over.best.ics.general]
8556 // However, if the target is [...]
8557 // - the object parameter of a user-defined conversion function
8558 // [...] user-defined conversion sequences are not considered.
8560 *this, CandidateSet.getLocation(), From->getType(),
8561 From->Classify(Context), Conversion, ConversionContext,
8562 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8563 /*SuppressUserConversion*/ true);
8564
8565 if (Candidate.Conversions[0].isBad()) {
8566 Candidate.Viable = false;
8568 return;
8569 }
8570
8571 if (Conversion->getTrailingRequiresClause()) {
8572 ConstraintSatisfaction Satisfaction;
8573 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8574 !Satisfaction.IsSatisfied) {
8575 Candidate.Viable = false;
8577 return;
8578 }
8579 }
8580
8581 // We won't go through a user-defined type conversion function to convert a
8582 // derived to base as such conversions are given Conversion Rank. They only
8583 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8584 QualType FromCanon
8585 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8586 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8587 if (FromCanon == ToCanon ||
8588 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8589 Candidate.Viable = false;
8591 return;
8592 }
8593
8594 // To determine what the conversion from the result of calling the
8595 // conversion function to the type we're eventually trying to
8596 // convert to (ToType), we need to synthesize a call to the
8597 // conversion function and attempt copy initialization from it. This
8598 // makes sure that we get the right semantics with respect to
8599 // lvalues/rvalues and the type. Fortunately, we can allocate this
8600 // call on the stack and we don't need its arguments to be
8601 // well-formed.
8602 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8603 VK_LValue, From->getBeginLoc());
8605 Context.getPointerType(Conversion->getType()),
8606 CK_FunctionToPointerDecay, &ConversionRef,
8608
8609 QualType ConversionType = Conversion->getConversionType();
8610 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8611 Candidate.Viable = false;
8613 return;
8614 }
8615
8616 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8617
8618 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8619
8620 // Introduce a temporary expression with the right type and value category
8621 // that we can use for deduction purposes.
8622 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8623
8625 TryCopyInitialization(*this, &FakeCall, ToType,
8626 /*SuppressUserConversions=*/true,
8627 /*InOverloadResolution=*/false,
8628 /*AllowObjCWritebackConversion=*/false);
8629
8630 switch (ICS.getKind()) {
8632 Candidate.FinalConversion = ICS.Standard;
8633 Candidate.HasFinalConversion = true;
8634
8635 // C++ [over.ics.user]p3:
8636 // If the user-defined conversion is specified by a specialization of a
8637 // conversion function template, the second standard conversion sequence
8638 // shall have exact match rank.
8639 if (Conversion->getPrimaryTemplate() &&
8641 Candidate.Viable = false;
8643 return;
8644 }
8645
8646 // C++0x [dcl.init.ref]p5:
8647 // In the second case, if the reference is an rvalue reference and
8648 // the second standard conversion sequence of the user-defined
8649 // conversion sequence includes an lvalue-to-rvalue conversion, the
8650 // program is ill-formed.
8651 if (ToType->isRValueReferenceType() &&
8653 Candidate.Viable = false;
8655 return;
8656 }
8657 break;
8658
8660 Candidate.Viable = false;
8662 return;
8663
8664 default:
8665 llvm_unreachable(
8666 "Can only end up with a standard conversion sequence or failure");
8667 }
8668
8669 if (EnableIfAttr *FailedAttr =
8670 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8671 Candidate.Viable = false;
8672 Candidate.FailureKind = ovl_fail_enable_if;
8673 Candidate.DeductionFailure.Data = FailedAttr;
8674 return;
8675 }
8676
8677 if (isNonViableMultiVersionOverload(Conversion)) {
8678 Candidate.Viable = false;
8680 }
8681}
8682
8684 Sema &S, OverloadCandidateSet &CandidateSet,
8686 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8687 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8688 bool AllowResultConversion) {
8689
8690 // If the function template has a non-dependent explicit specification,
8691 // exclude it now if appropriate; we are not permitted to perform deduction
8692 // and substitution in this case.
8693 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8694 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8695 Candidate.FoundDecl = FoundDecl;
8696 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8697 Candidate.Viable = false;
8698 Candidate.FailureKind = ovl_fail_explicit;
8699 return;
8700 }
8701
8702 QualType ObjectType = From->getType();
8703 Expr::Classification ObjectClassification = From->Classify(S.Context);
8704
8705 TemplateDeductionInfo Info(CandidateSet.getLocation());
8708 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8709 Specialization, Info);
8711 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8712 Candidate.FoundDecl = FoundDecl;
8713 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8714 Candidate.Viable = false;
8716 Candidate.ExplicitCallArguments = 1;
8717 Candidate.DeductionFailure =
8718 MakeDeductionFailureInfo(S.Context, Result, Info);
8719 return;
8720 }
8721
8722 // Add the conversion function template specialization produced by
8723 // template argument deduction as a candidate.
8724 assert(Specialization && "Missing function template specialization?");
8725 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8726 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8727 AllowExplicit, AllowResultConversion,
8728 Info.hasStrictPackMatch());
8729}
8730
8733 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8734 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8735 bool AllowExplicit, bool AllowResultConversion) {
8736 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8737 "Only conversion function templates permitted here");
8738
8739 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8740 return;
8741
8743 CandidateSet.getKind() ==
8747 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8748 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8749 AllowResultConversion);
8750
8752 return;
8753 }
8754
8756 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8757 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8758}
8759
8761 DeclAccessPair FoundDecl,
8762 CXXRecordDecl *ActingContext,
8763 const FunctionProtoType *Proto,
8764 Expr *Object,
8765 ArrayRef<Expr *> Args,
8766 OverloadCandidateSet& CandidateSet) {
8767 if (!CandidateSet.isNewCandidate(Conversion))
8768 return;
8769
8770 // Overload resolution is always an unevaluated context.
8773
8774 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8775 Candidate.FoundDecl = FoundDecl;
8776 Candidate.Function = nullptr;
8777 Candidate.Surrogate = Conversion;
8778 Candidate.IsSurrogate = true;
8779 Candidate.Viable = true;
8780 Candidate.ExplicitCallArguments = Args.size();
8781
8782 // Determine the implicit conversion sequence for the implicit
8783 // object parameter.
8784 ImplicitConversionSequence ObjectInit;
8785 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8786 ObjectInit = TryCopyInitialization(*this, Object,
8787 Conversion->getParamDecl(0)->getType(),
8788 /*SuppressUserConversions=*/false,
8789 /*InOverloadResolution=*/true, false);
8790 } else {
8792 *this, CandidateSet.getLocation(), Object->getType(),
8793 Object->Classify(Context), Conversion, ActingContext);
8794 }
8795
8796 if (ObjectInit.isBad()) {
8797 Candidate.Viable = false;
8799 Candidate.Conversions[0] = ObjectInit;
8800 return;
8801 }
8802
8803 // The first conversion is actually a user-defined conversion whose
8804 // first conversion is ObjectInit's standard conversion (which is
8805 // effectively a reference binding). Record it as such.
8806 Candidate.Conversions[0].setUserDefined();
8807 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8808 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8809 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8810 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8811 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8812 Candidate.Conversions[0].UserDefined.After
8813 = Candidate.Conversions[0].UserDefined.Before;
8814 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8815
8816 // Find the
8817 unsigned NumParams = Proto->getNumParams();
8818
8819 // (C++ 13.3.2p2): A candidate function having fewer than m
8820 // parameters is viable only if it has an ellipsis in its parameter
8821 // list (8.3.5).
8822 if (Args.size() > NumParams && !Proto->isVariadic()) {
8823 Candidate.Viable = false;
8825 return;
8826 }
8827
8828 // Function types don't have any default arguments, so just check if
8829 // we have enough arguments.
8830 if (Args.size() < NumParams) {
8831 // Not enough arguments.
8832 Candidate.Viable = false;
8834 return;
8835 }
8836
8837 // Determine the implicit conversion sequences for each of the
8838 // arguments.
8839 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8840 if (ArgIdx < NumParams) {
8841 // (C++ 13.3.2p3): for F to be a viable function, there shall
8842 // exist for each argument an implicit conversion sequence
8843 // (13.3.3.1) that converts that argument to the corresponding
8844 // parameter of F.
8845 QualType ParamType = Proto->getParamType(ArgIdx);
8846 Candidate.Conversions[ArgIdx + 1]
8847 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8848 /*SuppressUserConversions=*/false,
8849 /*InOverloadResolution=*/false,
8850 /*AllowObjCWritebackConversion=*/
8851 getLangOpts().ObjCAutoRefCount);
8852 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8853 Candidate.Viable = false;
8855 return;
8856 }
8857 } else {
8858 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8859 // argument for which there is no corresponding parameter is
8860 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8861 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8862 }
8863 }
8864
8865 if (Conversion->getTrailingRequiresClause()) {
8866 ConstraintSatisfaction Satisfaction;
8867 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8868 /*ForOverloadResolution*/ true) ||
8869 !Satisfaction.IsSatisfied) {
8870 Candidate.Viable = false;
8872 return;
8873 }
8874 }
8875
8876 if (EnableIfAttr *FailedAttr =
8877 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8878 Candidate.Viable = false;
8879 Candidate.FailureKind = ovl_fail_enable_if;
8880 Candidate.DeductionFailure.Data = FailedAttr;
8881 return;
8882 }
8883}
8884
8886 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8887 OverloadCandidateSet &CandidateSet,
8888 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8889 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8890 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8891 ArrayRef<Expr *> FunctionArgs = Args;
8892
8893 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8894 FunctionDecl *FD =
8895 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8896
8897 // Don't consider rewritten functions if we're not rewriting.
8898 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8899 continue;
8900
8901 assert(!isa<CXXMethodDecl>(FD) &&
8902 "unqualified operator lookup found a member function");
8903
8904 if (FunTmpl) {
8905 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8906 FunctionArgs, CandidateSet);
8907 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8908
8909 // As template candidates are not deduced immediately,
8910 // persist the array in the overload set.
8912 FunctionArgs[1], FunctionArgs[0]);
8913 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8914 Reversed, CandidateSet, false, false, true,
8915 ADLCallKind::NotADL,
8917 }
8918 } else {
8919 if (ExplicitTemplateArgs)
8920 continue;
8921 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8922 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8923 AddOverloadCandidate(FD, F.getPair(),
8924 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8925 false, false, true, false, ADLCallKind::NotADL, {},
8927 }
8928 }
8929}
8930
8932 SourceLocation OpLoc,
8933 ArrayRef<Expr *> Args,
8934 OverloadCandidateSet &CandidateSet,
8936 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8937
8938 // C++ [over.match.oper]p3:
8939 // For a unary operator @ with an operand of a type whose
8940 // cv-unqualified version is T1, and for a binary operator @ with
8941 // a left operand of a type whose cv-unqualified version is T1 and
8942 // a right operand of a type whose cv-unqualified version is T2,
8943 // three sets of candidate functions, designated member
8944 // candidates, non-member candidates and built-in candidates, are
8945 // constructed as follows:
8946 QualType T1 = Args[0]->getType();
8947
8948 // -- If T1 is a complete class type or a class currently being
8949 // defined, the set of member candidates is the result of the
8950 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8951 // the set of member candidates is empty.
8952 if (T1->isRecordType()) {
8953 bool IsComplete = isCompleteType(OpLoc, T1);
8954 auto *T1RD = T1->getAsCXXRecordDecl();
8955 // Complete the type if it can be completed.
8956 // If the type is neither complete nor being defined, bail out now.
8957 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8958 return;
8959
8960 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8961 LookupQualifiedName(Operators, T1RD);
8962 Operators.suppressAccessDiagnostics();
8963
8964 for (LookupResult::iterator Oper = Operators.begin(),
8965 OperEnd = Operators.end();
8966 Oper != OperEnd; ++Oper) {
8967 if (Oper->getAsFunction() &&
8969 !CandidateSet.getRewriteInfo().shouldAddReversed(
8970 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8971 continue;
8972 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8973 Args[0]->Classify(Context), Args.slice(1),
8974 CandidateSet, /*SuppressUserConversion=*/false, PO);
8975 }
8976 }
8977}
8978
8980 OverloadCandidateSet& CandidateSet,
8981 bool IsAssignmentOperator,
8982 unsigned NumContextualBoolArguments) {
8983 // Overload resolution is always an unevaluated context.
8986
8987 // Add this candidate
8988 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8989 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8990 Candidate.Function = nullptr;
8991 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8992
8993 // Determine the implicit conversion sequences for each of the
8994 // arguments.
8995 Candidate.Viable = true;
8996 Candidate.ExplicitCallArguments = Args.size();
8997 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8998 // C++ [over.match.oper]p4:
8999 // For the built-in assignment operators, conversions of the
9000 // left operand are restricted as follows:
9001 // -- no temporaries are introduced to hold the left operand, and
9002 // -- no user-defined conversions are applied to the left
9003 // operand to achieve a type match with the left-most
9004 // parameter of a built-in candidate.
9005 //
9006 // We block these conversions by turning off user-defined
9007 // conversions, since that is the only way that initialization of
9008 // a reference to a non-class type can occur from something that
9009 // is not of the same type.
9010 if (ArgIdx < NumContextualBoolArguments) {
9011 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9012 "Contextual conversion to bool requires bool type");
9013 Candidate.Conversions[ArgIdx]
9014 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9015 } else {
9016 Candidate.Conversions[ArgIdx]
9017 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9018 ArgIdx == 0 && IsAssignmentOperator,
9019 /*InOverloadResolution=*/false,
9020 /*AllowObjCWritebackConversion=*/
9021 getLangOpts().ObjCAutoRefCount);
9022 }
9023 if (Candidate.Conversions[ArgIdx].isBad()) {
9024 Candidate.Viable = false;
9026 break;
9027 }
9028 }
9029}
9030
9031namespace {
9032
9033/// BuiltinCandidateTypeSet - A set of types that will be used for the
9034/// candidate operator functions for built-in operators (C++
9035/// [over.built]). The types are separated into pointer types and
9036/// enumeration types.
9037class BuiltinCandidateTypeSet {
9038 /// TypeSet - A set of types.
9039 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9040
9041 /// PointerTypes - The set of pointer types that will be used in the
9042 /// built-in candidates.
9043 TypeSet PointerTypes;
9044
9045 /// MemberPointerTypes - The set of member pointer types that will be
9046 /// used in the built-in candidates.
9047 TypeSet MemberPointerTypes;
9048
9049 /// EnumerationTypes - The set of enumeration types that will be
9050 /// used in the built-in candidates.
9051 TypeSet EnumerationTypes;
9052
9053 /// The set of vector types that will be used in the built-in
9054 /// candidates.
9055 TypeSet VectorTypes;
9056
9057 /// The set of matrix types that will be used in the built-in
9058 /// candidates.
9059 TypeSet MatrixTypes;
9060
9061 /// The set of _BitInt types that will be used in the built-in candidates.
9062 TypeSet BitIntTypes;
9063
9064 /// A flag indicating non-record types are viable candidates
9065 bool HasNonRecordTypes;
9066
9067 /// A flag indicating whether either arithmetic or enumeration types
9068 /// were present in the candidate set.
9069 bool HasArithmeticOrEnumeralTypes;
9070
9071 /// A flag indicating whether the nullptr type was present in the
9072 /// candidate set.
9073 bool HasNullPtrType;
9074
9075 /// Sema - The semantic analysis instance where we are building the
9076 /// candidate type set.
9077 Sema &SemaRef;
9078
9079 /// Context - The AST context in which we will build the type sets.
9080 ASTContext &Context;
9081
9082 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9083 const Qualifiers &VisibleQuals);
9084 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9085
9086public:
9087 /// iterator - Iterates through the types that are part of the set.
9088 typedef TypeSet::iterator iterator;
9089
9090 BuiltinCandidateTypeSet(Sema &SemaRef)
9091 : HasNonRecordTypes(false),
9092 HasArithmeticOrEnumeralTypes(false),
9093 HasNullPtrType(false),
9094 SemaRef(SemaRef),
9095 Context(SemaRef.Context) { }
9096
9097 void AddTypesConvertedFrom(QualType Ty,
9098 SourceLocation Loc,
9099 bool AllowUserConversions,
9100 bool AllowExplicitConversions,
9101 const Qualifiers &VisibleTypeConversionsQuals);
9102
9103 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9104 llvm::iterator_range<iterator> member_pointer_types() {
9105 return MemberPointerTypes;
9106 }
9107 llvm::iterator_range<iterator> enumeration_types() {
9108 return EnumerationTypes;
9109 }
9110 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9111 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9112 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9113
9114 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9115 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9116 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9117 bool hasNullPtrType() const { return HasNullPtrType; }
9118};
9119
9120} // end anonymous namespace
9121
9122/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9123/// the set of pointer types along with any more-qualified variants of
9124/// that type. For example, if @p Ty is "int const *", this routine
9125/// will add "int const *", "int const volatile *", "int const
9126/// restrict *", and "int const volatile restrict *" to the set of
9127/// pointer types. Returns true if the add of @p Ty itself succeeded,
9128/// false otherwise.
9129///
9130/// FIXME: what to do about extended qualifiers?
9131bool
9132BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9133 const Qualifiers &VisibleQuals) {
9134
9135 // Insert this type.
9136 if (!PointerTypes.insert(Ty))
9137 return false;
9138
9139 QualType PointeeTy;
9140 const PointerType *PointerTy = Ty->getAs<PointerType>();
9141 bool buildObjCPtr = false;
9142 if (!PointerTy) {
9143 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9144 PointeeTy = PTy->getPointeeType();
9145 buildObjCPtr = true;
9146 } else {
9147 PointeeTy = PointerTy->getPointeeType();
9148 }
9149
9150 // Don't add qualified variants of arrays. For one, they're not allowed
9151 // (the qualifier would sink to the element type), and for another, the
9152 // only overload situation where it matters is subscript or pointer +- int,
9153 // and those shouldn't have qualifier variants anyway.
9154 if (PointeeTy->isArrayType())
9155 return true;
9156
9157 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9158 bool hasVolatile = VisibleQuals.hasVolatile();
9159 bool hasRestrict = VisibleQuals.hasRestrict();
9160
9161 // Iterate through all strict supersets of BaseCVR.
9162 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9163 if ((CVR | BaseCVR) != CVR) continue;
9164 // Skip over volatile if no volatile found anywhere in the types.
9165 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9166
9167 // Skip over restrict if no restrict found anywhere in the types, or if
9168 // the type cannot be restrict-qualified.
9169 if ((CVR & Qualifiers::Restrict) &&
9170 (!hasRestrict ||
9171 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9172 continue;
9173
9174 // Build qualified pointee type.
9175 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9176
9177 // Build qualified pointer type.
9178 QualType QPointerTy;
9179 if (!buildObjCPtr)
9180 QPointerTy = Context.getPointerType(QPointeeTy);
9181 else
9182 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9183
9184 // Insert qualified pointer type.
9185 PointerTypes.insert(QPointerTy);
9186 }
9187
9188 return true;
9189}
9190
9191/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9192/// to the set of pointer types along with any more-qualified variants of
9193/// that type. For example, if @p Ty is "int const *", this routine
9194/// will add "int const *", "int const volatile *", "int const
9195/// restrict *", and "int const volatile restrict *" to the set of
9196/// pointer types. Returns true if the add of @p Ty itself succeeded,
9197/// false otherwise.
9198///
9199/// FIXME: what to do about extended qualifiers?
9200bool
9201BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9202 QualType Ty) {
9203 // Insert this type.
9204 if (!MemberPointerTypes.insert(Ty))
9205 return false;
9206
9207 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9208 assert(PointerTy && "type was not a member pointer type!");
9209
9210 QualType PointeeTy = PointerTy->getPointeeType();
9211 // Don't add qualified variants of arrays. For one, they're not allowed
9212 // (the qualifier would sink to the element type), and for another, the
9213 // only overload situation where it matters is subscript or pointer +- int,
9214 // and those shouldn't have qualifier variants anyway.
9215 if (PointeeTy->isArrayType())
9216 return true;
9217 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9218
9219 // Iterate through all strict supersets of the pointee type's CVR
9220 // qualifiers.
9221 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9222 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9223 if ((CVR | BaseCVR) != CVR) continue;
9224
9225 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9226 MemberPointerTypes.insert(Context.getMemberPointerType(
9227 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9228 }
9229
9230 return true;
9231}
9232
9233/// AddTypesConvertedFrom - Add each of the types to which the type @p
9234/// Ty can be implicit converted to the given set of @p Types. We're
9235/// primarily interested in pointer types and enumeration types. We also
9236/// take member pointer types, for the conditional operator.
9237/// AllowUserConversions is true if we should look at the conversion
9238/// functions of a class type, and AllowExplicitConversions if we
9239/// should also include the explicit conversion functions of a class
9240/// type.
9241void
9242BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9243 SourceLocation Loc,
9244 bool AllowUserConversions,
9245 bool AllowExplicitConversions,
9246 const Qualifiers &VisibleQuals) {
9247 // Only deal with canonical types.
9248 Ty = Context.getCanonicalType(Ty);
9249
9250 // Look through reference types; they aren't part of the type of an
9251 // expression for the purposes of conversions.
9252 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9253 Ty = RefTy->getPointeeType();
9254
9255 // If we're dealing with an array type, decay to the pointer.
9256 if (Ty->isArrayType())
9257 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9258
9259 // Otherwise, we don't care about qualifiers on the type.
9260 Ty = Ty.getLocalUnqualifiedType();
9261
9262 // Flag if we ever add a non-record type.
9263 bool TyIsRec = Ty->isRecordType();
9264 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9265
9266 // Flag if we encounter an arithmetic type.
9267 HasArithmeticOrEnumeralTypes =
9268 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9269
9270 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9271 PointerTypes.insert(Ty);
9272 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9273 // Insert our type, and its more-qualified variants, into the set
9274 // of types.
9275 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9276 return;
9277 } else if (Ty->isMemberPointerType()) {
9278 // Member pointers are far easier, since the pointee can't be converted.
9279 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9280 return;
9281 } else if (Ty->isEnumeralType()) {
9282 HasArithmeticOrEnumeralTypes = true;
9283 EnumerationTypes.insert(Ty);
9284 } else if (Ty->isBitIntType()) {
9285 HasArithmeticOrEnumeralTypes = true;
9286 BitIntTypes.insert(Ty);
9287 } else if (Ty->isVectorType()) {
9288 // We treat vector types as arithmetic types in many contexts as an
9289 // extension.
9290 HasArithmeticOrEnumeralTypes = true;
9291 VectorTypes.insert(Ty);
9292 } else if (Ty->isMatrixType()) {
9293 // Similar to vector types, we treat vector types as arithmetic types in
9294 // many contexts as an extension.
9295 HasArithmeticOrEnumeralTypes = true;
9296 MatrixTypes.insert(Ty);
9297 } else if (Ty->isNullPtrType()) {
9298 HasNullPtrType = true;
9299 } else if (AllowUserConversions && TyIsRec) {
9300 // No conversion functions in incomplete types.
9301 if (!SemaRef.isCompleteType(Loc, Ty))
9302 return;
9303
9304 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9305 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9306 if (isa<UsingShadowDecl>(D))
9307 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9308
9309 // Skip conversion function templates; they don't tell us anything
9310 // about which builtin types we can convert to.
9312 continue;
9313
9314 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9315 if (AllowExplicitConversions || !Conv->isExplicit()) {
9316 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9317 VisibleQuals);
9318 }
9319 }
9320 }
9321}
9322/// Helper function for adjusting address spaces for the pointer or reference
9323/// operands of builtin operators depending on the argument.
9328
9329/// Helper function for AddBuiltinOperatorCandidates() that adds
9330/// the volatile- and non-volatile-qualified assignment operators for the
9331/// given type to the candidate set.
9333 QualType T,
9334 ArrayRef<Expr *> Args,
9335 OverloadCandidateSet &CandidateSet) {
9336 QualType ParamTypes[2];
9337
9338 // T& operator=(T&, T)
9339 ParamTypes[0] = S.Context.getLValueReferenceType(
9341 ParamTypes[1] = T;
9342 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9343 /*IsAssignmentOperator=*/true);
9344
9346 // volatile T& operator=(volatile T&, T)
9347 ParamTypes[0] = S.Context.getLValueReferenceType(
9349 Args[0]));
9350 ParamTypes[1] = T;
9351 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9352 /*IsAssignmentOperator=*/true);
9353 }
9354}
9355
9356/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9357/// if any, found in visible type conversion functions found in ArgExpr's type.
9358static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9359 Qualifiers VRQuals;
9360 CXXRecordDecl *ClassDecl;
9361 if (const MemberPointerType *RHSMPType =
9362 ArgExpr->getType()->getAs<MemberPointerType>())
9363 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9364 else
9365 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9366 if (!ClassDecl) {
9367 // Just to be safe, assume the worst case.
9368 VRQuals.addVolatile();
9369 VRQuals.addRestrict();
9370 return VRQuals;
9371 }
9372 if (!ClassDecl->hasDefinition())
9373 return VRQuals;
9374
9375 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9376 if (isa<UsingShadowDecl>(D))
9377 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9378 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9379 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9380 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9381 CanTy = ResTypeRef->getPointeeType();
9382 // Need to go down the pointer/mempointer chain and add qualifiers
9383 // as see them.
9384 bool done = false;
9385 while (!done) {
9386 if (CanTy.isRestrictQualified())
9387 VRQuals.addRestrict();
9388 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9389 CanTy = ResTypePtr->getPointeeType();
9390 else if (const MemberPointerType *ResTypeMPtr =
9391 CanTy->getAs<MemberPointerType>())
9392 CanTy = ResTypeMPtr->getPointeeType();
9393 else
9394 done = true;
9395 if (CanTy.isVolatileQualified())
9396 VRQuals.addVolatile();
9397 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9398 return VRQuals;
9399 }
9400 }
9401 }
9402 return VRQuals;
9403}
9404
9405// Note: We're currently only handling qualifiers that are meaningful for the
9406// LHS of compound assignment overloading.
9408 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9409 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9410 // _Atomic
9411 if (Available.hasAtomic()) {
9412 Available.removeAtomic();
9413 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9414 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9415 return;
9416 }
9417
9418 // volatile
9419 if (Available.hasVolatile()) {
9420 Available.removeVolatile();
9421 assert(!Applied.hasVolatile());
9422 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9423 Callback);
9424 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9425 return;
9426 }
9427
9428 Callback(Applied);
9429}
9430
9432 QualifiersAndAtomic Quals,
9433 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9435 Callback);
9436}
9437
9439 QualifiersAndAtomic Quals,
9440 Sema &S) {
9441 if (Quals.hasAtomic())
9443 if (Quals.hasVolatile())
9446}
9447
9448namespace {
9449
9450/// Helper class to manage the addition of builtin operator overload
9451/// candidates. It provides shared state and utility methods used throughout
9452/// the process, as well as a helper method to add each group of builtin
9453/// operator overloads from the standard to a candidate set.
9454class BuiltinOperatorOverloadBuilder {
9455 // Common instance state available to all overload candidate addition methods.
9456 Sema &S;
9457 ArrayRef<Expr *> Args;
9458 QualifiersAndAtomic VisibleTypeConversionsQuals;
9459 bool HasArithmeticOrEnumeralCandidateType;
9460 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9461 OverloadCandidateSet &CandidateSet;
9462
9463 static constexpr int ArithmeticTypesCap = 26;
9464 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9465
9466 // Define some indices used to iterate over the arithmetic types in
9467 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9468 // types are that preserved by promotion (C++ [over.built]p2).
9469 unsigned FirstIntegralType,
9470 LastIntegralType;
9471 unsigned FirstPromotedIntegralType,
9472 LastPromotedIntegralType;
9473 unsigned FirstPromotedArithmeticType,
9474 LastPromotedArithmeticType;
9475 unsigned NumArithmeticTypes;
9476
9477 void InitArithmeticTypes() {
9478 // Start of promoted types.
9479 FirstPromotedArithmeticType = 0;
9480 ArithmeticTypes.push_back(S.Context.FloatTy);
9481 ArithmeticTypes.push_back(S.Context.DoubleTy);
9482 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9484 ArithmeticTypes.push_back(S.Context.Float128Ty);
9486 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9487
9488 // Start of integral types.
9489 FirstIntegralType = ArithmeticTypes.size();
9490 FirstPromotedIntegralType = ArithmeticTypes.size();
9491 ArithmeticTypes.push_back(S.Context.IntTy);
9492 ArithmeticTypes.push_back(S.Context.LongTy);
9493 ArithmeticTypes.push_back(S.Context.LongLongTy);
9497 ArithmeticTypes.push_back(S.Context.Int128Ty);
9498 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9499 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9500 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9504 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9505
9506 /// We add candidates for the unique, unqualified _BitInt types present in
9507 /// the candidate type set. The candidate set already handled ensuring the
9508 /// type is unqualified and canonical, but because we're adding from N
9509 /// different sets, we need to do some extra work to unique things. Insert
9510 /// the candidates into a unique set, then move from that set into the list
9511 /// of arithmetic types.
9512 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9513 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9514 for (QualType BitTy : Candidate.bitint_types())
9515 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9516 }
9517 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9518 LastPromotedIntegralType = ArithmeticTypes.size();
9519 LastPromotedArithmeticType = ArithmeticTypes.size();
9520 // End of promoted types.
9521
9522 ArithmeticTypes.push_back(S.Context.BoolTy);
9523 ArithmeticTypes.push_back(S.Context.CharTy);
9524 ArithmeticTypes.push_back(S.Context.WCharTy);
9525 if (S.Context.getLangOpts().Char8)
9526 ArithmeticTypes.push_back(S.Context.Char8Ty);
9527 ArithmeticTypes.push_back(S.Context.Char16Ty);
9528 ArithmeticTypes.push_back(S.Context.Char32Ty);
9529 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9530 ArithmeticTypes.push_back(S.Context.ShortTy);
9531 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9532 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9533 LastIntegralType = ArithmeticTypes.size();
9534 NumArithmeticTypes = ArithmeticTypes.size();
9535 // End of integral types.
9536 // FIXME: What about complex? What about half?
9537
9538 // We don't know for sure how many bit-precise candidates were involved, so
9539 // we subtract those from the total when testing whether we're under the
9540 // cap or not.
9541 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9542 ArithmeticTypesCap &&
9543 "Enough inline storage for all arithmetic types.");
9544 }
9545
9546 /// Helper method to factor out the common pattern of adding overloads
9547 /// for '++' and '--' builtin operators.
9548 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9549 bool HasVolatile,
9550 bool HasRestrict) {
9551 QualType ParamTypes[2] = {
9552 S.Context.getLValueReferenceType(CandidateTy),
9553 S.Context.IntTy
9554 };
9555
9556 // Non-volatile version.
9557 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9558
9559 // Use a heuristic to reduce number of builtin candidates in the set:
9560 // add volatile version only if there are conversions to a volatile type.
9561 if (HasVolatile) {
9562 ParamTypes[0] =
9564 S.Context.getVolatileType(CandidateTy));
9565 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9566 }
9567
9568 // Add restrict version only if there are conversions to a restrict type
9569 // and our candidate type is a non-restrict-qualified pointer.
9570 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9571 !CandidateTy.isRestrictQualified()) {
9572 ParamTypes[0]
9575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9576
9577 if (HasVolatile) {
9578 ParamTypes[0]
9580 S.Context.getCVRQualifiedType(CandidateTy,
9583 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9584 }
9585 }
9586
9587 }
9588
9589 /// Helper to add an overload candidate for a binary builtin with types \p L
9590 /// and \p R.
9591 void AddCandidate(QualType L, QualType R) {
9592 QualType LandR[2] = {L, R};
9593 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9594 }
9595
9596public:
9597 BuiltinOperatorOverloadBuilder(
9598 Sema &S, ArrayRef<Expr *> Args,
9599 QualifiersAndAtomic VisibleTypeConversionsQuals,
9600 bool HasArithmeticOrEnumeralCandidateType,
9601 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9602 OverloadCandidateSet &CandidateSet)
9603 : S(S), Args(Args),
9604 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9605 HasArithmeticOrEnumeralCandidateType(
9606 HasArithmeticOrEnumeralCandidateType),
9607 CandidateTypes(CandidateTypes),
9608 CandidateSet(CandidateSet) {
9609
9610 InitArithmeticTypes();
9611 }
9612
9613 // Increment is deprecated for bool since C++17.
9614 //
9615 // C++ [over.built]p3:
9616 //
9617 // For every pair (T, VQ), where T is an arithmetic type other
9618 // than bool, and VQ is either volatile or empty, there exist
9619 // candidate operator functions of the form
9620 //
9621 // VQ T& operator++(VQ T&);
9622 // T operator++(VQ T&, int);
9623 //
9624 // C++ [over.built]p4:
9625 //
9626 // For every pair (T, VQ), where T is an arithmetic type other
9627 // than bool, and VQ is either volatile or empty, there exist
9628 // candidate operator functions of the form
9629 //
9630 // VQ T& operator--(VQ T&);
9631 // T operator--(VQ T&, int);
9632 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9633 if (!HasArithmeticOrEnumeralCandidateType)
9634 return;
9635
9636 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9637 const auto TypeOfT = ArithmeticTypes[Arith];
9638 if (TypeOfT == S.Context.BoolTy) {
9639 if (Op == OO_MinusMinus)
9640 continue;
9641 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9642 continue;
9643 }
9644 addPlusPlusMinusMinusStyleOverloads(
9645 TypeOfT,
9646 VisibleTypeConversionsQuals.hasVolatile(),
9647 VisibleTypeConversionsQuals.hasRestrict());
9648 }
9649 }
9650
9651 // C++ [over.built]p5:
9652 //
9653 // For every pair (T, VQ), where T is a cv-qualified or
9654 // cv-unqualified object type, and VQ is either volatile or
9655 // empty, there exist candidate operator functions of the form
9656 //
9657 // T*VQ& operator++(T*VQ&);
9658 // T*VQ& operator--(T*VQ&);
9659 // T* operator++(T*VQ&, int);
9660 // T* operator--(T*VQ&, int);
9661 void addPlusPlusMinusMinusPointerOverloads() {
9662 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9663 // Skip pointer types that aren't pointers to object types.
9664 if (!PtrTy->getPointeeType()->isObjectType())
9665 continue;
9666
9667 addPlusPlusMinusMinusStyleOverloads(
9668 PtrTy,
9669 (!PtrTy.isVolatileQualified() &&
9670 VisibleTypeConversionsQuals.hasVolatile()),
9671 (!PtrTy.isRestrictQualified() &&
9672 VisibleTypeConversionsQuals.hasRestrict()));
9673 }
9674 }
9675
9676 // C++ [over.built]p6:
9677 // For every cv-qualified or cv-unqualified object type T, there
9678 // exist candidate operator functions of the form
9679 //
9680 // T& operator*(T*);
9681 //
9682 // C++ [over.built]p7:
9683 // For every function type T that does not have cv-qualifiers or a
9684 // ref-qualifier, there exist candidate operator functions of the form
9685 // T& operator*(T*);
9686 void addUnaryStarPointerOverloads() {
9687 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9688 QualType PointeeTy = ParamTy->getPointeeType();
9689 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9690 continue;
9691
9692 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9693 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9694 continue;
9695
9696 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9697 }
9698 }
9699
9700 // C++ [over.built]p9:
9701 // For every promoted arithmetic type T, there exist candidate
9702 // operator functions of the form
9703 //
9704 // T operator+(T);
9705 // T operator-(T);
9706 void addUnaryPlusOrMinusArithmeticOverloads() {
9707 if (!HasArithmeticOrEnumeralCandidateType)
9708 return;
9709
9710 for (unsigned Arith = FirstPromotedArithmeticType;
9711 Arith < LastPromotedArithmeticType; ++Arith) {
9712 QualType ArithTy = ArithmeticTypes[Arith];
9713 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9714 }
9715
9716 // Extension: We also add these operators for vector types.
9717 for (QualType VecTy : CandidateTypes[0].vector_types())
9718 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9719 }
9720
9721 // C++ [over.built]p8:
9722 // For every type T, there exist candidate operator functions of
9723 // the form
9724 //
9725 // T* operator+(T*);
9726 void addUnaryPlusPointerOverloads() {
9727 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9728 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9729 }
9730
9731 // C++ [over.built]p10:
9732 // For every promoted integral type T, there exist candidate
9733 // operator functions of the form
9734 //
9735 // T operator~(T);
9736 void addUnaryTildePromotedIntegralOverloads() {
9737 if (!HasArithmeticOrEnumeralCandidateType)
9738 return;
9739
9740 for (unsigned Int = FirstPromotedIntegralType;
9741 Int < LastPromotedIntegralType; ++Int) {
9742 QualType IntTy = ArithmeticTypes[Int];
9743 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9744 }
9745
9746 // Extension: We also add this operator for vector types.
9747 for (QualType VecTy : CandidateTypes[0].vector_types())
9748 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9749 }
9750
9751 // C++ [over.match.oper]p16:
9752 // For every pointer to member type T or type std::nullptr_t, there
9753 // exist candidate operator functions of the form
9754 //
9755 // bool operator==(T,T);
9756 // bool operator!=(T,T);
9757 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9758 /// Set of (canonical) types that we've already handled.
9759 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9760
9761 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9762 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9763 // Don't add the same builtin candidate twice.
9764 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9765 continue;
9766
9767 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9769 }
9770
9771 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9773 if (AddedTypes.insert(NullPtrTy).second) {
9774 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9775 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9776 }
9777 }
9778 }
9779 }
9780
9781 // C++ [over.built]p15:
9782 //
9783 // For every T, where T is an enumeration type or a pointer type,
9784 // there exist candidate operator functions of the form
9785 //
9786 // bool operator<(T, T);
9787 // bool operator>(T, T);
9788 // bool operator<=(T, T);
9789 // bool operator>=(T, T);
9790 // bool operator==(T, T);
9791 // bool operator!=(T, T);
9792 // R operator<=>(T, T)
9793 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9794 // C++ [over.match.oper]p3:
9795 // [...]the built-in candidates include all of the candidate operator
9796 // functions defined in 13.6 that, compared to the given operator, [...]
9797 // do not have the same parameter-type-list as any non-template non-member
9798 // candidate.
9799 //
9800 // Note that in practice, this only affects enumeration types because there
9801 // aren't any built-in candidates of record type, and a user-defined operator
9802 // must have an operand of record or enumeration type. Also, the only other
9803 // overloaded operator with enumeration arguments, operator=,
9804 // cannot be overloaded for enumeration types, so this is the only place
9805 // where we must suppress candidates like this.
9806 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9807 UserDefinedBinaryOperators;
9808
9809 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9810 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9811 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9812 CEnd = CandidateSet.end();
9813 C != CEnd; ++C) {
9814 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9815 continue;
9816
9817 if (C->Function->isFunctionTemplateSpecialization())
9818 continue;
9819
9820 // We interpret "same parameter-type-list" as applying to the
9821 // "synthesized candidate, with the order of the two parameters
9822 // reversed", not to the original function.
9823 bool Reversed = C->isReversed();
9824 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9825 ->getType()
9826 .getUnqualifiedType();
9827 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9828 ->getType()
9829 .getUnqualifiedType();
9830
9831 // Skip if either parameter isn't of enumeral type.
9832 if (!FirstParamType->isEnumeralType() ||
9833 !SecondParamType->isEnumeralType())
9834 continue;
9835
9836 // Add this operator to the set of known user-defined operators.
9837 UserDefinedBinaryOperators.insert(
9838 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9839 S.Context.getCanonicalType(SecondParamType)));
9840 }
9841 }
9842 }
9843
9844 /// Set of (canonical) types that we've already handled.
9845 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9846
9847 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9848 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9849 // Don't add the same builtin candidate twice.
9850 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9851 continue;
9852 if (IsSpaceship && PtrTy->isFunctionPointerType())
9853 continue;
9854
9855 QualType ParamTypes[2] = {PtrTy, PtrTy};
9856 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9857 }
9858 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9859 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9860
9861 // Don't add the same builtin candidate twice, or if a user defined
9862 // candidate exists.
9863 if (!AddedTypes.insert(CanonType).second ||
9864 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9865 CanonType)))
9866 continue;
9867 QualType ParamTypes[2] = {EnumTy, EnumTy};
9868 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9869 }
9870 }
9871 }
9872
9873 // C++ [over.built]p13:
9874 //
9875 // For every cv-qualified or cv-unqualified object type T
9876 // there exist candidate operator functions of the form
9877 //
9878 // T* operator+(T*, ptrdiff_t);
9879 // T& operator[](T*, ptrdiff_t); [BELOW]
9880 // T* operator-(T*, ptrdiff_t);
9881 // T* operator+(ptrdiff_t, T*);
9882 // T& operator[](ptrdiff_t, T*); [BELOW]
9883 //
9884 // C++ [over.built]p14:
9885 //
9886 // For every T, where T is a pointer to object type, there
9887 // exist candidate operator functions of the form
9888 //
9889 // ptrdiff_t operator-(T, T);
9890 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9891 /// Set of (canonical) types that we've already handled.
9892 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9893
9894 for (int Arg = 0; Arg < 2; ++Arg) {
9895 QualType AsymmetricParamTypes[2] = {
9898 };
9899 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9900 QualType PointeeTy = PtrTy->getPointeeType();
9901 if (!PointeeTy->isObjectType())
9902 continue;
9903
9904 AsymmetricParamTypes[Arg] = PtrTy;
9905 if (Arg == 0 || Op == OO_Plus) {
9906 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9907 // T* operator+(ptrdiff_t, T*);
9908 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9909 }
9910 if (Op == OO_Minus) {
9911 // ptrdiff_t operator-(T, T);
9912 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9913 continue;
9914
9915 QualType ParamTypes[2] = {PtrTy, PtrTy};
9916 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9917 }
9918 }
9919 }
9920 }
9921
9922 // C++ [over.built]p12:
9923 //
9924 // For every pair of promoted arithmetic types L and R, there
9925 // exist candidate operator functions of the form
9926 //
9927 // LR operator*(L, R);
9928 // LR operator/(L, R);
9929 // LR operator+(L, R);
9930 // LR operator-(L, R);
9931 // bool operator<(L, R);
9932 // bool operator>(L, R);
9933 // bool operator<=(L, R);
9934 // bool operator>=(L, R);
9935 // bool operator==(L, R);
9936 // bool operator!=(L, R);
9937 //
9938 // where LR is the result of the usual arithmetic conversions
9939 // between types L and R.
9940 //
9941 // C++ [over.built]p24:
9942 //
9943 // For every pair of promoted arithmetic types L and R, there exist
9944 // candidate operator functions of the form
9945 //
9946 // LR operator?(bool, L, R);
9947 //
9948 // where LR is the result of the usual arithmetic conversions
9949 // between types L and R.
9950 // Our candidates ignore the first parameter.
9951 void addGenericBinaryArithmeticOverloads() {
9952 if (!HasArithmeticOrEnumeralCandidateType)
9953 return;
9954
9955 for (unsigned Left = FirstPromotedArithmeticType;
9956 Left < LastPromotedArithmeticType; ++Left) {
9957 for (unsigned Right = FirstPromotedArithmeticType;
9958 Right < LastPromotedArithmeticType; ++Right) {
9959 QualType LandR[2] = { ArithmeticTypes[Left],
9960 ArithmeticTypes[Right] };
9961 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9962 }
9963 }
9964
9965 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9966 // conditional operator for vector types.
9967 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9968 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9969 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9970 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9971 }
9972 }
9973
9974 /// Add binary operator overloads for each candidate matrix type M1, M2:
9975 /// * (M1, M1) -> M1
9976 /// * (M1, M1.getElementType()) -> M1
9977 /// * (M2.getElementType(), M2) -> M2
9978 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9979 void addMatrixBinaryArithmeticOverloads() {
9980 if (!HasArithmeticOrEnumeralCandidateType)
9981 return;
9982
9983 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9984 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9985 AddCandidate(M1, M1);
9986 }
9987
9988 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9989 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9990 if (!CandidateTypes[0].containsMatrixType(M2))
9991 AddCandidate(M2, M2);
9992 }
9993 }
9994
9995 // C++2a [over.built]p14:
9996 //
9997 // For every integral type T there exists a candidate operator function
9998 // of the form
9999 //
10000 // std::strong_ordering operator<=>(T, T)
10001 //
10002 // C++2a [over.built]p15:
10003 //
10004 // For every pair of floating-point types L and R, there exists a candidate
10005 // operator function of the form
10006 //
10007 // std::partial_ordering operator<=>(L, R);
10008 //
10009 // FIXME: The current specification for integral types doesn't play nice with
10010 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10011 // comparisons. Under the current spec this can lead to ambiguity during
10012 // overload resolution. For example:
10013 //
10014 // enum A : int {a};
10015 // auto x = (a <=> (long)42);
10016 //
10017 // error: call is ambiguous for arguments 'A' and 'long'.
10018 // note: candidate operator<=>(int, int)
10019 // note: candidate operator<=>(long, long)
10020 //
10021 // To avoid this error, this function deviates from the specification and adds
10022 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10023 // arithmetic types (the same as the generic relational overloads).
10024 //
10025 // For now this function acts as a placeholder.
10026 void addThreeWayArithmeticOverloads() {
10027 addGenericBinaryArithmeticOverloads();
10028 }
10029
10030 // C++ [over.built]p17:
10031 //
10032 // For every pair of promoted integral types L and R, there
10033 // exist candidate operator functions of the form
10034 //
10035 // LR operator%(L, R);
10036 // LR operator&(L, R);
10037 // LR operator^(L, R);
10038 // LR operator|(L, R);
10039 // L operator<<(L, R);
10040 // L operator>>(L, R);
10041 //
10042 // where LR is the result of the usual arithmetic conversions
10043 // between types L and R.
10044 void addBinaryBitwiseArithmeticOverloads() {
10045 if (!HasArithmeticOrEnumeralCandidateType)
10046 return;
10047
10048 for (unsigned Left = FirstPromotedIntegralType;
10049 Left < LastPromotedIntegralType; ++Left) {
10050 for (unsigned Right = FirstPromotedIntegralType;
10051 Right < LastPromotedIntegralType; ++Right) {
10052 QualType LandR[2] = { ArithmeticTypes[Left],
10053 ArithmeticTypes[Right] };
10054 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10055 }
10056 }
10057 }
10058
10059 // C++ [over.built]p20:
10060 //
10061 // For every pair (T, VQ), where T is an enumeration or
10062 // pointer to member type and VQ is either volatile or
10063 // empty, there exist candidate operator functions of the form
10064 //
10065 // VQ T& operator=(VQ T&, T);
10066 void addAssignmentMemberPointerOrEnumeralOverloads() {
10067 /// Set of (canonical) types that we've already handled.
10068 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10069
10070 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10071 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10072 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10073 continue;
10074
10075 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10076 }
10077
10078 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10079 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10080 continue;
10081
10082 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10083 }
10084 }
10085 }
10086
10087 // C++ [over.built]p19:
10088 //
10089 // For every pair (T, VQ), where T is any type and VQ is either
10090 // volatile or empty, there exist candidate operator functions
10091 // of the form
10092 //
10093 // T*VQ& operator=(T*VQ&, T*);
10094 //
10095 // C++ [over.built]p21:
10096 //
10097 // For every pair (T, VQ), where T is a cv-qualified or
10098 // cv-unqualified object type and VQ is either volatile or
10099 // empty, there exist candidate operator functions of the form
10100 //
10101 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10102 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10103 void addAssignmentPointerOverloads(bool isEqualOp) {
10104 /// Set of (canonical) types that we've already handled.
10105 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10106
10107 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10108 // If this is operator=, keep track of the builtin candidates we added.
10109 if (isEqualOp)
10110 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10111 else if (!PtrTy->getPointeeType()->isObjectType())
10112 continue;
10113
10114 // non-volatile version
10115 QualType ParamTypes[2] = {
10117 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10118 };
10119 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10120 /*IsAssignmentOperator=*/ isEqualOp);
10121
10122 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10123 VisibleTypeConversionsQuals.hasVolatile();
10124 if (NeedVolatile) {
10125 // volatile version
10126 ParamTypes[0] =
10128 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10129 /*IsAssignmentOperator=*/isEqualOp);
10130 }
10131
10132 if (!PtrTy.isRestrictQualified() &&
10133 VisibleTypeConversionsQuals.hasRestrict()) {
10134 // restrict version
10135 ParamTypes[0] =
10137 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10138 /*IsAssignmentOperator=*/isEqualOp);
10139
10140 if (NeedVolatile) {
10141 // volatile restrict version
10142 ParamTypes[0] =
10145 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10146 /*IsAssignmentOperator=*/isEqualOp);
10147 }
10148 }
10149 }
10150
10151 if (isEqualOp) {
10152 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10153 // Make sure we don't add the same candidate twice.
10154 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10155 continue;
10156
10157 QualType ParamTypes[2] = {
10159 PtrTy,
10160 };
10161
10162 // non-volatile version
10163 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10164 /*IsAssignmentOperator=*/true);
10165
10166 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10167 VisibleTypeConversionsQuals.hasVolatile();
10168 if (NeedVolatile) {
10169 // volatile version
10170 ParamTypes[0] = S.Context.getLValueReferenceType(
10171 S.Context.getVolatileType(PtrTy));
10172 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10173 /*IsAssignmentOperator=*/true);
10174 }
10175
10176 if (!PtrTy.isRestrictQualified() &&
10177 VisibleTypeConversionsQuals.hasRestrict()) {
10178 // restrict version
10179 ParamTypes[0] = S.Context.getLValueReferenceType(
10180 S.Context.getRestrictType(PtrTy));
10181 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10182 /*IsAssignmentOperator=*/true);
10183
10184 if (NeedVolatile) {
10185 // volatile restrict version
10186 ParamTypes[0] =
10189 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10190 /*IsAssignmentOperator=*/true);
10191 }
10192 }
10193 }
10194 }
10195 }
10196
10197 // C++ [over.built]p18:
10198 //
10199 // For every triple (L, VQ, R), where L is an arithmetic type,
10200 // VQ is either volatile or empty, and R is a promoted
10201 // arithmetic type, there exist candidate operator functions of
10202 // the form
10203 //
10204 // VQ L& operator=(VQ L&, R);
10205 // VQ L& operator*=(VQ L&, R);
10206 // VQ L& operator/=(VQ L&, R);
10207 // VQ L& operator+=(VQ L&, R);
10208 // VQ L& operator-=(VQ L&, R);
10209 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10210 if (!HasArithmeticOrEnumeralCandidateType)
10211 return;
10212
10213 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10214 for (unsigned Right = FirstPromotedArithmeticType;
10215 Right < LastPromotedArithmeticType; ++Right) {
10216 QualType ParamTypes[2];
10217 ParamTypes[1] = ArithmeticTypes[Right];
10219 S, ArithmeticTypes[Left], Args[0]);
10220
10222 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10223 ParamTypes[0] =
10224 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10225 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10226 /*IsAssignmentOperator=*/isEqualOp);
10227 });
10228 }
10229 }
10230
10231 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10232 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10233 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10234 QualType ParamTypes[2];
10235 ParamTypes[1] = Vec2Ty;
10236 // Add this built-in operator as a candidate (VQ is empty).
10237 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10238 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10239 /*IsAssignmentOperator=*/isEqualOp);
10240
10241 // Add this built-in operator as a candidate (VQ is 'volatile').
10242 if (VisibleTypeConversionsQuals.hasVolatile()) {
10243 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10244 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10245 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10246 /*IsAssignmentOperator=*/isEqualOp);
10247 }
10248 }
10249 }
10250
10251 // C++ [over.built]p22:
10252 //
10253 // For every triple (L, VQ, R), where L is an integral type, VQ
10254 // is either volatile or empty, and R is a promoted integral
10255 // type, there exist candidate operator functions of the form
10256 //
10257 // VQ L& operator%=(VQ L&, R);
10258 // VQ L& operator<<=(VQ L&, R);
10259 // VQ L& operator>>=(VQ L&, R);
10260 // VQ L& operator&=(VQ L&, R);
10261 // VQ L& operator^=(VQ L&, R);
10262 // VQ L& operator|=(VQ L&, R);
10263 void addAssignmentIntegralOverloads() {
10264 if (!HasArithmeticOrEnumeralCandidateType)
10265 return;
10266
10267 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10268 for (unsigned Right = FirstPromotedIntegralType;
10269 Right < LastPromotedIntegralType; ++Right) {
10270 QualType ParamTypes[2];
10271 ParamTypes[1] = ArithmeticTypes[Right];
10273 S, ArithmeticTypes[Left], Args[0]);
10274
10276 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10277 ParamTypes[0] =
10278 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10279 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10280 });
10281 }
10282 }
10283 }
10284
10285 // C++ [over.operator]p23:
10286 //
10287 // There also exist candidate operator functions of the form
10288 //
10289 // bool operator!(bool);
10290 // bool operator&&(bool, bool);
10291 // bool operator||(bool, bool);
10292 void addExclaimOverload() {
10293 QualType ParamTy = S.Context.BoolTy;
10294 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10295 /*IsAssignmentOperator=*/false,
10296 /*NumContextualBoolArguments=*/1);
10297 }
10298 void addAmpAmpOrPipePipeOverload() {
10299 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10300 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10301 /*IsAssignmentOperator=*/false,
10302 /*NumContextualBoolArguments=*/2);
10303 }
10304
10305 // C++ [over.built]p13:
10306 //
10307 // For every cv-qualified or cv-unqualified object type T there
10308 // exist candidate operator functions of the form
10309 //
10310 // T* operator+(T*, ptrdiff_t); [ABOVE]
10311 // T& operator[](T*, ptrdiff_t);
10312 // T* operator-(T*, ptrdiff_t); [ABOVE]
10313 // T* operator+(ptrdiff_t, T*); [ABOVE]
10314 // T& operator[](ptrdiff_t, T*);
10315 void addSubscriptOverloads() {
10316 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10317 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10318 QualType PointeeType = PtrTy->getPointeeType();
10319 if (!PointeeType->isObjectType())
10320 continue;
10321
10322 // T& operator[](T*, ptrdiff_t)
10323 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10324 }
10325
10326 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10327 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10328 QualType PointeeType = PtrTy->getPointeeType();
10329 if (!PointeeType->isObjectType())
10330 continue;
10331
10332 // T& operator[](ptrdiff_t, T*)
10333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10334 }
10335 }
10336
10337 // C++ [over.built]p11:
10338 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10339 // C1 is the same type as C2 or is a derived class of C2, T is an object
10340 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10341 // there exist candidate operator functions of the form
10342 //
10343 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10344 //
10345 // where CV12 is the union of CV1 and CV2.
10346 void addArrowStarOverloads() {
10347 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10348 QualType C1Ty = PtrTy;
10349 QualType C1;
10350 QualifierCollector Q1;
10351 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10352 if (!isa<RecordType>(C1))
10353 continue;
10354 // heuristic to reduce number of builtin candidates in the set.
10355 // Add volatile/restrict version only if there are conversions to a
10356 // volatile/restrict type.
10357 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10358 continue;
10359 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10360 continue;
10361 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10362 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10363 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10364 *D2 = mptr->getMostRecentCXXRecordDecl();
10365 if (!declaresSameEntity(D1, D2) &&
10366 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10367 break;
10368 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10369 // build CV12 T&
10370 QualType T = mptr->getPointeeType();
10371 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10373 continue;
10374 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10376 continue;
10377 T = Q1.apply(S.Context, T);
10378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10379 }
10380 }
10381 }
10382
10383 // Note that we don't consider the first argument, since it has been
10384 // contextually converted to bool long ago. The candidates below are
10385 // therefore added as binary.
10386 //
10387 // C++ [over.built]p25:
10388 // For every type T, where T is a pointer, pointer-to-member, or scoped
10389 // enumeration type, there exist candidate operator functions of the form
10390 //
10391 // T operator?(bool, T, T);
10392 //
10393 void addConditionalOperatorOverloads() {
10394 /// Set of (canonical) types that we've already handled.
10395 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10396
10397 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10398 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10399 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10400 continue;
10401
10402 QualType ParamTypes[2] = {PtrTy, PtrTy};
10403 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10404 }
10405
10406 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10407 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10408 continue;
10409
10410 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10411 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10412 }
10413
10414 if (S.getLangOpts().CPlusPlus11) {
10415 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10416 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10417 continue;
10418
10419 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10420 continue;
10421
10422 QualType ParamTypes[2] = {EnumTy, EnumTy};
10423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10424 }
10425 }
10426 }
10427 }
10428};
10429
10430} // end anonymous namespace
10431
10433 SourceLocation OpLoc,
10434 ArrayRef<Expr *> Args,
10435 OverloadCandidateSet &CandidateSet) {
10436 // Find all of the types that the arguments can convert to, but only
10437 // if the operator we're looking at has built-in operator candidates
10438 // that make use of these types. Also record whether we encounter non-record
10439 // candidate types or either arithmetic or enumeral candidate types.
10440 QualifiersAndAtomic VisibleTypeConversionsQuals;
10441 VisibleTypeConversionsQuals.addConst();
10442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10443 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10444 if (Args[ArgIdx]->getType()->isAtomicType())
10445 VisibleTypeConversionsQuals.addAtomic();
10446 }
10447
10448 bool HasNonRecordCandidateType = false;
10449 bool HasArithmeticOrEnumeralCandidateType = false;
10451 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10452 CandidateTypes.emplace_back(*this);
10453 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10454 OpLoc,
10455 true,
10456 (Op == OO_Exclaim ||
10457 Op == OO_AmpAmp ||
10458 Op == OO_PipePipe),
10459 VisibleTypeConversionsQuals);
10460 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10461 CandidateTypes[ArgIdx].hasNonRecordTypes();
10462 HasArithmeticOrEnumeralCandidateType =
10463 HasArithmeticOrEnumeralCandidateType ||
10464 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10465 }
10466
10467 // Exit early when no non-record types have been added to the candidate set
10468 // for any of the arguments to the operator.
10469 //
10470 // We can't exit early for !, ||, or &&, since there we have always have
10471 // 'bool' overloads.
10472 if (!HasNonRecordCandidateType &&
10473 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10474 return;
10475
10476 // Setup an object to manage the common state for building overloads.
10477 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10478 VisibleTypeConversionsQuals,
10479 HasArithmeticOrEnumeralCandidateType,
10480 CandidateTypes, CandidateSet);
10481
10482 // Dispatch over the operation to add in only those overloads which apply.
10483 switch (Op) {
10484 case OO_None:
10486 llvm_unreachable("Expected an overloaded operator");
10487
10488 case OO_New:
10489 case OO_Delete:
10490 case OO_Array_New:
10491 case OO_Array_Delete:
10492 case OO_Call:
10493 llvm_unreachable(
10494 "Special operators don't use AddBuiltinOperatorCandidates");
10495
10496 case OO_Comma:
10497 case OO_Arrow:
10498 case OO_Coawait:
10499 // C++ [over.match.oper]p3:
10500 // -- For the operator ',', the unary operator '&', the
10501 // operator '->', or the operator 'co_await', the
10502 // built-in candidates set is empty.
10503 break;
10504
10505 case OO_Plus: // '+' is either unary or binary
10506 if (Args.size() == 1)
10507 OpBuilder.addUnaryPlusPointerOverloads();
10508 [[fallthrough]];
10509
10510 case OO_Minus: // '-' is either unary or binary
10511 if (Args.size() == 1) {
10512 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10513 } else {
10514 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10515 OpBuilder.addGenericBinaryArithmeticOverloads();
10516 OpBuilder.addMatrixBinaryArithmeticOverloads();
10517 }
10518 break;
10519
10520 case OO_Star: // '*' is either unary or binary
10521 if (Args.size() == 1)
10522 OpBuilder.addUnaryStarPointerOverloads();
10523 else {
10524 OpBuilder.addGenericBinaryArithmeticOverloads();
10525 OpBuilder.addMatrixBinaryArithmeticOverloads();
10526 }
10527 break;
10528
10529 case OO_Slash:
10530 OpBuilder.addGenericBinaryArithmeticOverloads();
10531 break;
10532
10533 case OO_PlusPlus:
10534 case OO_MinusMinus:
10535 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10536 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10537 break;
10538
10539 case OO_EqualEqual:
10540 case OO_ExclaimEqual:
10541 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10542 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10543 OpBuilder.addGenericBinaryArithmeticOverloads();
10544 break;
10545
10546 case OO_Less:
10547 case OO_Greater:
10548 case OO_LessEqual:
10549 case OO_GreaterEqual:
10550 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10551 OpBuilder.addGenericBinaryArithmeticOverloads();
10552 break;
10553
10554 case OO_Spaceship:
10555 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10556 OpBuilder.addThreeWayArithmeticOverloads();
10557 break;
10558
10559 case OO_Percent:
10560 case OO_Caret:
10561 case OO_Pipe:
10562 case OO_LessLess:
10563 case OO_GreaterGreater:
10564 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10565 break;
10566
10567 case OO_Amp: // '&' is either unary or binary
10568 if (Args.size() == 1)
10569 // C++ [over.match.oper]p3:
10570 // -- For the operator ',', the unary operator '&', or the
10571 // operator '->', the built-in candidates set is empty.
10572 break;
10573
10574 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10575 break;
10576
10577 case OO_Tilde:
10578 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10579 break;
10580
10581 case OO_Equal:
10582 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10583 [[fallthrough]];
10584
10585 case OO_PlusEqual:
10586 case OO_MinusEqual:
10587 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10588 [[fallthrough]];
10589
10590 case OO_StarEqual:
10591 case OO_SlashEqual:
10592 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10593 break;
10594
10595 case OO_PercentEqual:
10596 case OO_LessLessEqual:
10597 case OO_GreaterGreaterEqual:
10598 case OO_AmpEqual:
10599 case OO_CaretEqual:
10600 case OO_PipeEqual:
10601 OpBuilder.addAssignmentIntegralOverloads();
10602 break;
10603
10604 case OO_Exclaim:
10605 OpBuilder.addExclaimOverload();
10606 break;
10607
10608 case OO_AmpAmp:
10609 case OO_PipePipe:
10610 OpBuilder.addAmpAmpOrPipePipeOverload();
10611 break;
10612
10613 case OO_Subscript:
10614 if (Args.size() == 2)
10615 OpBuilder.addSubscriptOverloads();
10616 break;
10617
10618 case OO_ArrowStar:
10619 OpBuilder.addArrowStarOverloads();
10620 break;
10621
10622 case OO_Conditional:
10623 OpBuilder.addConditionalOperatorOverloads();
10624 OpBuilder.addGenericBinaryArithmeticOverloads();
10625 break;
10626 }
10627}
10628
10629void
10631 SourceLocation Loc,
10632 ArrayRef<Expr *> Args,
10633 TemplateArgumentListInfo *ExplicitTemplateArgs,
10634 OverloadCandidateSet& CandidateSet,
10635 bool PartialOverloading) {
10636 ADLResult Fns;
10637
10638 // FIXME: This approach for uniquing ADL results (and removing
10639 // redundant candidates from the set) relies on pointer-equality,
10640 // which means we need to key off the canonical decl. However,
10641 // always going back to the canonical decl might not get us the
10642 // right set of default arguments. What default arguments are
10643 // we supposed to consider on ADL candidates, anyway?
10644
10645 // FIXME: Pass in the explicit template arguments?
10646 ArgumentDependentLookup(Name, Loc, Args, Fns);
10647
10648 ArrayRef<Expr *> ReversedArgs;
10649
10650 // Erase all of the candidates we already knew about.
10651 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10652 CandEnd = CandidateSet.end();
10653 Cand != CandEnd; ++Cand)
10654 if (Cand->Function) {
10655 FunctionDecl *Fn = Cand->Function;
10656 Fns.erase(Fn);
10657 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10658 Fns.erase(FunTmpl);
10659 }
10660
10661 // For each of the ADL candidates we found, add it to the overload
10662 // set.
10663 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10665
10666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10667 if (ExplicitTemplateArgs)
10668 continue;
10669
10671 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10672 PartialOverloading, /*AllowExplicit=*/true,
10673 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10674 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10676 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10677 /*SuppressUserConversions=*/false, PartialOverloading,
10678 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10679 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10680 }
10681 } else {
10682 auto *FTD = cast<FunctionTemplateDecl>(*I);
10684 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10685 /*SuppressUserConversions=*/false, PartialOverloading,
10686 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10687 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10688 *this, Args, FTD->getTemplatedDecl())) {
10689
10690 // As template candidates are not deduced immediately,
10691 // persist the array in the overload set.
10692 if (ReversedArgs.empty())
10693 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10694
10696 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10697 /*SuppressUserConversions=*/false, PartialOverloading,
10698 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10700 }
10701 }
10702 }
10703}
10704
10705namespace {
10706enum class Comparison { Equal, Better, Worse };
10707}
10708
10709/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10710/// overload resolution.
10711///
10712/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10713/// Cand1's first N enable_if attributes have precisely the same conditions as
10714/// Cand2's first N enable_if attributes (where N = the number of enable_if
10715/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10716///
10717/// Note that you can have a pair of candidates such that Cand1's enable_if
10718/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10719/// worse than Cand1's.
10720static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10721 const FunctionDecl *Cand2) {
10722 // Common case: One (or both) decls don't have enable_if attrs.
10723 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10724 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10725 if (!Cand1Attr || !Cand2Attr) {
10726 if (Cand1Attr == Cand2Attr)
10727 return Comparison::Equal;
10728 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10729 }
10730
10731 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10732 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10733
10734 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10735 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10736 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10737 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10738
10739 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10740 // has fewer enable_if attributes than Cand2, and vice versa.
10741 if (!Cand1A)
10742 return Comparison::Worse;
10743 if (!Cand2A)
10744 return Comparison::Better;
10745
10746 Cand1ID.clear();
10747 Cand2ID.clear();
10748
10749 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10750 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10751 if (Cand1ID != Cand2ID)
10752 return Comparison::Worse;
10753 }
10754
10755 return Comparison::Equal;
10756}
10757
10758static Comparison
10760 const OverloadCandidate &Cand2) {
10761 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10762 !Cand2.Function->isMultiVersion())
10763 return Comparison::Equal;
10764
10765 // If both are invalid, they are equal. If one of them is invalid, the other
10766 // is better.
10767 if (Cand1.Function->isInvalidDecl()) {
10768 if (Cand2.Function->isInvalidDecl())
10769 return Comparison::Equal;
10770 return Comparison::Worse;
10771 }
10772 if (Cand2.Function->isInvalidDecl())
10773 return Comparison::Better;
10774
10775 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10776 // cpu_dispatch, else arbitrarily based on the identifiers.
10777 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10778 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10779 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10780 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10781
10782 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10783 return Comparison::Equal;
10784
10785 if (Cand1CPUDisp && !Cand2CPUDisp)
10786 return Comparison::Better;
10787 if (Cand2CPUDisp && !Cand1CPUDisp)
10788 return Comparison::Worse;
10789
10790 if (Cand1CPUSpec && Cand2CPUSpec) {
10791 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10792 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10793 ? Comparison::Better
10794 : Comparison::Worse;
10795
10796 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10797 FirstDiff = std::mismatch(
10798 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10799 Cand2CPUSpec->cpus_begin(),
10800 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10801 return LHS->getName() == RHS->getName();
10802 });
10803
10804 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10805 "Two different cpu-specific versions should not have the same "
10806 "identifier list, otherwise they'd be the same decl!");
10807 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10808 ? Comparison::Better
10809 : Comparison::Worse;
10810 }
10811 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10812}
10813
10814/// Compute the type of the implicit object parameter for the given function,
10815/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10816/// null QualType if there is a 'matches anything' implicit object parameter.
10817static std::optional<QualType>
10820 return std::nullopt;
10821
10822 auto *M = cast<CXXMethodDecl>(F);
10823 // Static member functions' object parameters match all types.
10824 if (M->isStatic())
10825 return QualType();
10826 return M->getFunctionObjectParameterReferenceType();
10827}
10828
10829// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10830// represent the same entity.
10831static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10832 const FunctionDecl *F2) {
10833 if (declaresSameEntity(F1, F2))
10834 return true;
10835 auto PT1 = F1->getPrimaryTemplate();
10836 auto PT2 = F2->getPrimaryTemplate();
10837 if (PT1 && PT2) {
10838 if (declaresSameEntity(PT1, PT2) ||
10839 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10840 PT2->getInstantiatedFromMemberTemplate()))
10841 return true;
10842 }
10843 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10844 // different functions with same params). Consider removing this (as no test
10845 // fail w/o it).
10846 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10847 if (First) {
10848 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10849 return *T;
10850 }
10851 assert(I < F->getNumParams());
10852 return F->getParamDecl(I++)->getType();
10853 };
10854
10855 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10856 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10857
10858 if (F1NumParams != F2NumParams)
10859 return false;
10860
10861 unsigned I1 = 0, I2 = 0;
10862 for (unsigned I = 0; I != F1NumParams; ++I) {
10863 QualType T1 = NextParam(F1, I1, I == 0);
10864 QualType T2 = NextParam(F2, I2, I == 0);
10865 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10866 if (!Context.hasSameUnqualifiedType(T1, T2))
10867 return false;
10868 }
10869 return true;
10870}
10871
10872/// We're allowed to use constraints partial ordering only if the candidates
10873/// have the same parameter types:
10874/// [over.match.best.general]p2.6
10875/// F1 and F2 are non-template functions with the same
10876/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10878 FunctionDecl *Fn2,
10879 bool IsFn1Reversed,
10880 bool IsFn2Reversed) {
10881 assert(Fn1 && Fn2);
10882 if (Fn1->isVariadic() != Fn2->isVariadic())
10883 return false;
10884
10885 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10886 IsFn1Reversed ^ IsFn2Reversed))
10887 return false;
10888
10889 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10890 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10891 if (Mem1 && Mem2) {
10892 // if they are member functions, both are direct members of the same class,
10893 // and
10894 if (Mem1->getParent() != Mem2->getParent())
10895 return false;
10896 // if both are non-static member functions, they have the same types for
10897 // their object parameters
10898 if (Mem1->isInstance() && Mem2->isInstance() &&
10900 Mem1->getFunctionObjectParameterReferenceType(),
10901 Mem1->getFunctionObjectParameterReferenceType()))
10902 return false;
10903 }
10904 return true;
10905}
10906
10907static FunctionDecl *
10909 bool IsFn1Reversed, bool IsFn2Reversed) {
10910 if (!Fn1 || !Fn2)
10911 return nullptr;
10912
10913 // C++ [temp.constr.order]:
10914 // A non-template function F1 is more partial-ordering-constrained than a
10915 // non-template function F2 if:
10916 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10917 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10918
10919 if (Cand1IsSpecialization || Cand2IsSpecialization)
10920 return nullptr;
10921
10922 // - they have the same non-object-parameter-type-lists, and [...]
10923 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10924 IsFn2Reversed))
10925 return nullptr;
10926
10927 // - the declaration of F1 is more constrained than the declaration of F2.
10928 return S.getMoreConstrainedFunction(Fn1, Fn2);
10929}
10930
10931/// isBetterOverloadCandidate - Determines whether the first overload
10932/// candidate is a better candidate than the second (C++ 13.3.3p1).
10934 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10936 bool PartialOverloading) {
10937 // Define viable functions to be better candidates than non-viable
10938 // functions.
10939 if (!Cand2.Viable)
10940 return Cand1.Viable;
10941 else if (!Cand1.Viable)
10942 return false;
10943
10944 // [CUDA] A function with 'never' preference is marked not viable, therefore
10945 // is never shown up here. The worst preference shown up here is 'wrong side',
10946 // e.g. an H function called by a HD function in device compilation. This is
10947 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10948 // function which is called only by an H function. A deferred diagnostic will
10949 // be triggered if it is emitted. However a wrong-sided function is still
10950 // a viable candidate here.
10951 //
10952 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10953 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10954 // can be emitted, Cand1 is not better than Cand2. This rule should have
10955 // precedence over other rules.
10956 //
10957 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10958 // other rules should be used to determine which is better. This is because
10959 // host/device based overloading resolution is mostly for determining
10960 // viability of a function. If two functions are both viable, other factors
10961 // should take precedence in preference, e.g. the standard-defined preferences
10962 // like argument conversion ranks or enable_if partial-ordering. The
10963 // preference for pass-object-size parameters is probably most similar to a
10964 // type-based-overloading decision and so should take priority.
10965 //
10966 // If other rules cannot determine which is better, CUDA preference will be
10967 // used again to determine which is better.
10968 //
10969 // TODO: Currently IdentifyPreference does not return correct values
10970 // for functions called in global variable initializers due to missing
10971 // correct context about device/host. Therefore we can only enforce this
10972 // rule when there is a caller. We should enforce this rule for functions
10973 // in global variable initializers once proper context is added.
10974 //
10975 // TODO: We can only enable the hostness based overloading resolution when
10976 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10977 // overloading resolution diagnostics.
10978 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10979 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10980 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10981 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10982 bool IsCand1ImplicitHD =
10984 bool IsCand2ImplicitHD =
10986 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10987 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10988 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10989 // The implicit HD function may be a function in a system header which
10990 // is forced by pragma. In device compilation, if we prefer HD candidates
10991 // over wrong-sided candidates, overloading resolution may change, which
10992 // may result in non-deferrable diagnostics. As a workaround, we let
10993 // implicit HD candidates take equal preference as wrong-sided candidates.
10994 // This will preserve the overloading resolution.
10995 // TODO: We still need special handling of implicit HD functions since
10996 // they may incur other diagnostics to be deferred. We should make all
10997 // host/device related diagnostics deferrable and remove special handling
10998 // of implicit HD functions.
10999 auto EmitThreshold =
11000 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11001 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11004 auto Cand1Emittable = P1 > EmitThreshold;
11005 auto Cand2Emittable = P2 > EmitThreshold;
11006 if (Cand1Emittable && !Cand2Emittable)
11007 return true;
11008 if (!Cand1Emittable && Cand2Emittable)
11009 return false;
11010 }
11011 }
11012
11013 // C++ [over.match.best]p1: (Changed in C++23)
11014 //
11015 // -- if F is a static member function, ICS1(F) is defined such
11016 // that ICS1(F) is neither better nor worse than ICS1(G) for
11017 // any function G, and, symmetrically, ICS1(G) is neither
11018 // better nor worse than ICS1(F).
11019 unsigned StartArg = 0;
11020 if (!Cand1.TookAddressOfOverload &&
11022 StartArg = 1;
11023
11024 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11025 // We don't allow incompatible pointer conversions in C++.
11026 if (!S.getLangOpts().CPlusPlus)
11027 return ICS.isStandard() &&
11028 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11029
11030 // The only ill-formed conversion we allow in C++ is the string literal to
11031 // char* conversion, which is only considered ill-formed after C++11.
11032 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11034 };
11035
11036 // Define functions that don't require ill-formed conversions for a given
11037 // argument to be better candidates than functions that do.
11038 unsigned NumArgs = Cand1.Conversions.size();
11039 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11040 bool HasBetterConversion = false;
11041 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11042 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11043 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11044 if (Cand1Bad != Cand2Bad) {
11045 if (Cand1Bad)
11046 return false;
11047 HasBetterConversion = true;
11048 }
11049 }
11050
11051 if (HasBetterConversion)
11052 return true;
11053
11054 // C++ [over.match.best]p1:
11055 // A viable function F1 is defined to be a better function than another
11056 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11057 // conversion sequence than ICSi(F2), and then...
11058 bool HasWorseConversion = false;
11059 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11061 Cand1.Conversions[ArgIdx],
11062 Cand2.Conversions[ArgIdx])) {
11064 // Cand1 has a better conversion sequence.
11065 HasBetterConversion = true;
11066 break;
11067
11069 if (Cand1.Function && Cand2.Function &&
11070 Cand1.isReversed() != Cand2.isReversed() &&
11071 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11072 // Work around large-scale breakage caused by considering reversed
11073 // forms of operator== in C++20:
11074 //
11075 // When comparing a function against a reversed function, if we have a
11076 // better conversion for one argument and a worse conversion for the
11077 // other, the implicit conversion sequences are treated as being equally
11078 // good.
11079 //
11080 // This prevents a comparison function from being considered ambiguous
11081 // with a reversed form that is written in the same way.
11082 //
11083 // We diagnose this as an extension from CreateOverloadedBinOp.
11084 HasWorseConversion = true;
11085 break;
11086 }
11087
11088 // Cand1 can't be better than Cand2.
11089 return false;
11090
11092 // Do nothing.
11093 break;
11094 }
11095 }
11096
11097 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11098 // ICSj(F2), or, if not that,
11099 if (HasBetterConversion && !HasWorseConversion)
11100 return true;
11101
11102 // -- the context is an initialization by user-defined conversion
11103 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11104 // from the return type of F1 to the destination type (i.e.,
11105 // the type of the entity being initialized) is a better
11106 // conversion sequence than the standard conversion sequence
11107 // from the return type of F2 to the destination type.
11109 Cand1.Function && Cand2.Function &&
11112
11113 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11114 // First check whether we prefer one of the conversion functions over the
11115 // other. This only distinguishes the results in non-standard, extension
11116 // cases such as the conversion from a lambda closure type to a function
11117 // pointer or block.
11122 Cand1.FinalConversion,
11123 Cand2.FinalConversion);
11124
11127
11128 // FIXME: Compare kind of reference binding if conversion functions
11129 // convert to a reference type used in direct reference binding, per
11130 // C++14 [over.match.best]p1 section 2 bullet 3.
11131 }
11132
11133 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11134 // as combined with the resolution to CWG issue 243.
11135 //
11136 // When the context is initialization by constructor ([over.match.ctor] or
11137 // either phase of [over.match.list]), a constructor is preferred over
11138 // a conversion function.
11139 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11140 Cand1.Function && Cand2.Function &&
11143 return isa<CXXConstructorDecl>(Cand1.Function);
11144
11145 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11146 return Cand2.StrictPackMatch;
11147
11148 // -- F1 is a non-template function and F2 is a function template
11149 // specialization, or, if not that,
11150 bool Cand1IsSpecialization = Cand1.Function &&
11152 bool Cand2IsSpecialization = Cand2.Function &&
11154 if (Cand1IsSpecialization != Cand2IsSpecialization)
11155 return Cand2IsSpecialization;
11156
11157 // -- F1 and F2 are function template specializations, and the function
11158 // template for F1 is more specialized than the template for F2
11159 // according to the partial ordering rules described in 14.5.5.2, or,
11160 // if not that,
11161 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11162 const auto *Obj1Context =
11163 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11164 const auto *Obj2Context =
11165 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11166 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11168 Cand2.Function->getPrimaryTemplate(), Loc,
11170 : TPOC_Call,
11172 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11173 : QualType{},
11174 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11175 : QualType{},
11176 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11177 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11178 }
11179 }
11180
11181 // -— F1 and F2 are non-template functions and F1 is more
11182 // partial-ordering-constrained than F2 [...],
11184 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11185 Cand2.isReversed());
11186 F && F == Cand1.Function)
11187 return true;
11188
11189 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11190 // class B of D, and for all arguments the corresponding parameters of
11191 // F1 and F2 have the same type.
11192 // FIXME: Implement the "all parameters have the same type" check.
11193 bool Cand1IsInherited =
11194 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11195 bool Cand2IsInherited =
11196 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11197 if (Cand1IsInherited != Cand2IsInherited)
11198 return Cand2IsInherited;
11199 else if (Cand1IsInherited) {
11200 assert(Cand2IsInherited);
11201 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11202 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11203 if (Cand1Class->isDerivedFrom(Cand2Class))
11204 return true;
11205 if (Cand2Class->isDerivedFrom(Cand1Class))
11206 return false;
11207 // Inherited from sibling base classes: still ambiguous.
11208 }
11209
11210 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11211 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11212 // with reversed order of parameters and F1 is not
11213 //
11214 // We rank reversed + different operator as worse than just reversed, but
11215 // that comparison can never happen, because we only consider reversing for
11216 // the maximally-rewritten operator (== or <=>).
11217 if (Cand1.RewriteKind != Cand2.RewriteKind)
11218 return Cand1.RewriteKind < Cand2.RewriteKind;
11219
11220 // Check C++17 tie-breakers for deduction guides.
11221 {
11222 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11223 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11224 if (Guide1 && Guide2) {
11225 // -- F1 is generated from a deduction-guide and F2 is not
11226 if (Guide1->isImplicit() != Guide2->isImplicit())
11227 return Guide2->isImplicit();
11228
11229 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11230 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11231 return true;
11232 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11233 return false;
11234
11235 // --F1 is generated from a non-template constructor and F2 is generated
11236 // from a constructor template
11237 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11238 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11239 if (Constructor1 && Constructor2) {
11240 bool isC1Templated = Constructor1->getTemplatedKind() !=
11242 bool isC2Templated = Constructor2->getTemplatedKind() !=
11244 if (isC1Templated != isC2Templated)
11245 return isC2Templated;
11246 }
11247 }
11248 }
11249
11250 // Check for enable_if value-based overload resolution.
11251 if (Cand1.Function && Cand2.Function) {
11253 if (Cmp != Comparison::Equal)
11254 return Cmp == Comparison::Better;
11255 }
11256
11257 bool HasPS1 = Cand1.Function != nullptr &&
11259 bool HasPS2 = Cand2.Function != nullptr &&
11261 if (HasPS1 != HasPS2 && HasPS1)
11262 return true;
11263
11264 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11265 if (MV == Comparison::Better)
11266 return true;
11267 if (MV == Comparison::Worse)
11268 return false;
11269
11270 // If other rules cannot determine which is better, CUDA preference is used
11271 // to determine which is better.
11272 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11273 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11274 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11275 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11276 }
11277
11278 // General member function overloading is handled above, so this only handles
11279 // constructors with address spaces.
11280 // This only handles address spaces since C++ has no other
11281 // qualifier that can be used with constructors.
11282 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11283 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11284 if (CD1 && CD2) {
11285 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11286 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11287 if (AS1 != AS2) {
11289 return true;
11291 return false;
11292 }
11293 }
11294
11295 return false;
11296}
11297
11298/// Determine whether two declarations are "equivalent" for the purposes of
11299/// name lookup and overload resolution. This applies when the same internal/no
11300/// linkage entity is defined by two modules (probably by textually including
11301/// the same header). In such a case, we don't consider the declarations to
11302/// declare the same entity, but we also don't want lookups with both
11303/// declarations visible to be ambiguous in some cases (this happens when using
11304/// a modularized libstdc++).
11306 const NamedDecl *B) {
11307 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11308 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11309 if (!VA || !VB)
11310 return false;
11311
11312 // The declarations must be declaring the same name as an internal linkage
11313 // entity in different modules.
11314 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11315 VB->getDeclContext()->getRedeclContext()) ||
11316 getOwningModule(VA) == getOwningModule(VB) ||
11317 VA->isExternallyVisible() || VB->isExternallyVisible())
11318 return false;
11319
11320 // Check that the declarations appear to be equivalent.
11321 //
11322 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11323 // For constants and functions, we should check the initializer or body is
11324 // the same. For non-constant variables, we shouldn't allow it at all.
11325 if (Context.hasSameType(VA->getType(), VB->getType()))
11326 return true;
11327
11328 // Enum constants within unnamed enumerations will have different types, but
11329 // may still be similar enough to be interchangeable for our purposes.
11330 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11331 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11332 // Only handle anonymous enums. If the enumerations were named and
11333 // equivalent, they would have been merged to the same type.
11334 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11335 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11336 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11337 !Context.hasSameType(EnumA->getIntegerType(),
11338 EnumB->getIntegerType()))
11339 return false;
11340 // Allow this only if the value is the same for both enumerators.
11341 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11342 }
11343 }
11344
11345 // Nothing else is sufficiently similar.
11346 return false;
11347}
11348
11351 assert(D && "Unknown declaration");
11352 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11353
11354 Module *M = getOwningModule(D);
11355 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11356 << !M << (M ? M->getFullModuleName() : "");
11357
11358 for (auto *E : Equiv) {
11359 Module *M = getOwningModule(E);
11360 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11361 << !M << (M ? M->getFullModuleName() : "");
11362 }
11363}
11364
11367 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11369 static_cast<CNSInfo *>(DeductionFailure.Data)
11370 ->Satisfaction.ContainsErrors;
11371}
11372
11375 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11376 bool PartialOverloading, bool AllowExplicit,
11378 bool AggregateCandidateDeduction) {
11379
11380 auto *C =
11381 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11382
11385 /*AllowObjCConversionOnExplicit=*/false,
11386 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11387 PartialOverloading, AggregateCandidateDeduction},
11389 FoundDecl,
11390 Args,
11391 IsADLCandidate,
11392 PO};
11393
11394 HasDeferredTemplateConstructors |=
11395 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11396}
11397
11399 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11400 CXXRecordDecl *ActingContext, QualType ObjectType,
11401 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11402 bool SuppressUserConversions, bool PartialOverloading,
11404
11405 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11406
11407 auto *C =
11408 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11409
11412 /*AllowObjCConversionOnExplicit=*/false,
11413 /*AllowResultConversion=*/false,
11414 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11415 /*AggregateCandidateDeduction=*/false},
11416 MethodTmpl,
11417 FoundDecl,
11418 Args,
11419 ActingContext,
11420 ObjectClassification,
11421 ObjectType,
11422 PO};
11423}
11424
11427 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11428 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11429 bool AllowResultConversion) {
11430
11431 auto *C =
11432 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11433
11436 AllowObjCConversionOnExplicit, AllowResultConversion,
11437 /*AllowExplicit=*/false,
11438 /*SuppressUserConversions=*/false,
11439 /*PartialOverloading*/ false,
11440 /*AggregateCandidateDeduction=*/false},
11442 FoundDecl,
11443 ActingContext,
11444 From,
11445 ToType};
11446}
11447
11448static void
11451
11453 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11454 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11455 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11456}
11457
11458static void
11462 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11463 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11464 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11465 C.AggregateCandidateDeduction);
11466}
11467
11468static void
11472 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11473 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11474 C.AllowResultConversion);
11475}
11476
11478 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11479 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11480 while (Cand) {
11481 switch (Cand->Kind) {
11484 S, *this,
11485 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11486 break;
11489 S, *this,
11490 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11491 break;
11494 S, *this,
11495 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11496 break;
11497 }
11498 Cand = Cand->Next;
11499 }
11500 FirstDeferredCandidate = nullptr;
11501 DeferredCandidatesCount = 0;
11502}
11503
11505OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11506 Best->Best = true;
11507 if (Best->Function && Best->Function->isDeleted())
11508 return OR_Deleted;
11509 return OR_Success;
11510}
11511
11512void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11514 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11515 // are accepted by both clang and NVCC. However, during a particular
11516 // compilation mode only one call variant is viable. We need to
11517 // exclude non-viable overload candidates from consideration based
11518 // only on their host/device attributes. Specifically, if one
11519 // candidate call is WrongSide and the other is SameSide, we ignore
11520 // the WrongSide candidate.
11521 // We only need to remove wrong-sided candidates here if
11522 // -fgpu-exclude-wrong-side-overloads is off. When
11523 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11524 // uniformly in isBetterOverloadCandidate.
11525 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11526 return;
11527 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11528
11529 bool ContainsSameSideCandidate =
11530 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11531 // Check viable function only.
11532 return Cand->Viable && Cand->Function &&
11533 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11535 });
11536
11537 if (!ContainsSameSideCandidate)
11538 return;
11539
11540 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11541 // Check viable function only to avoid unnecessary data copying/moving.
11542 return Cand->Viable && Cand->Function &&
11543 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11545 };
11546 llvm::erase_if(Candidates, IsWrongSideCandidate);
11547}
11548
11549/// Computes the best viable function (C++ 13.3.3)
11550/// within an overload candidate set.
11551///
11552/// \param Loc The location of the function name (or operator symbol) for
11553/// which overload resolution occurs.
11554///
11555/// \param Best If overload resolution was successful or found a deleted
11556/// function, \p Best points to the candidate function found.
11557///
11558/// \returns The result of overload resolution.
11560 SourceLocation Loc,
11561 iterator &Best) {
11562
11564 DeferredCandidatesCount == 0) &&
11565 "Unexpected deferred template candidates");
11566
11567 bool TwoPhaseResolution =
11568 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11569
11570 if (TwoPhaseResolution) {
11571 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11572 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11573 if (!(HasDeferredTemplateConstructors &&
11574 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11575 return Res;
11576 }
11577 }
11578
11580 return BestViableFunctionImpl(S, Loc, Best);
11581}
11582
11583OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11585
11587 Candidates.reserve(this->Candidates.size());
11588 std::transform(this->Candidates.begin(), this->Candidates.end(),
11589 std::back_inserter(Candidates),
11590 [](OverloadCandidate &Cand) { return &Cand; });
11591
11592 if (S.getLangOpts().CUDA)
11593 CudaExcludeWrongSideCandidates(S, Candidates);
11594
11595 Best = end();
11596 for (auto *Cand : Candidates) {
11597 Cand->Best = false;
11598 if (Cand->Viable) {
11599 if (Best == end() ||
11600 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11601 Best = Cand;
11602 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11603 // This candidate has constraint that we were unable to evaluate because
11604 // it referenced an expression that contained an error. Rather than fall
11605 // back onto a potentially unintended candidate (made worse by
11606 // subsuming constraints), treat this as 'no viable candidate'.
11607 Best = end();
11608 return OR_No_Viable_Function;
11609 }
11610 }
11611
11612 // If we didn't find any viable functions, abort.
11613 if (Best == end())
11614 return OR_No_Viable_Function;
11615
11616 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11617 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11618 PendingBest.push_back(&*Best);
11619 Best->Best = true;
11620
11621 // Make sure that this function is better than every other viable
11622 // function. If not, we have an ambiguity.
11623 while (!PendingBest.empty()) {
11624 auto *Curr = PendingBest.pop_back_val();
11625 for (auto *Cand : Candidates) {
11626 if (Cand->Viable && !Cand->Best &&
11627 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11628 PendingBest.push_back(Cand);
11629 Cand->Best = true;
11630
11632 Curr->Function))
11633 EquivalentCands.push_back(Cand->Function);
11634 else
11635 Best = end();
11636 }
11637 }
11638 }
11639
11640 if (Best == end())
11641 return OR_Ambiguous;
11642
11643 OverloadingResult R = ResultForBestCandidate(Best);
11644
11645 if (!EquivalentCands.empty())
11647 EquivalentCands);
11648 return R;
11649}
11650
11651namespace {
11652
11653enum OverloadCandidateKind {
11654 oc_function,
11655 oc_method,
11656 oc_reversed_binary_operator,
11657 oc_constructor,
11658 oc_implicit_default_constructor,
11659 oc_implicit_copy_constructor,
11660 oc_implicit_move_constructor,
11661 oc_implicit_copy_assignment,
11662 oc_implicit_move_assignment,
11663 oc_implicit_equality_comparison,
11664 oc_inherited_constructor
11665};
11666
11667enum OverloadCandidateSelect {
11668 ocs_non_template,
11669 ocs_template,
11670 ocs_described_template,
11671};
11672
11673static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11674ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11675 const FunctionDecl *Fn,
11677 std::string &Description) {
11678
11679 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11680 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11681 isTemplate = true;
11682 Description = S.getTemplateArgumentBindingsText(
11683 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11684 }
11685
11686 OverloadCandidateSelect Select = [&]() {
11687 if (!Description.empty())
11688 return ocs_described_template;
11689 return isTemplate ? ocs_template : ocs_non_template;
11690 }();
11691
11692 OverloadCandidateKind Kind = [&]() {
11693 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11694 return oc_implicit_equality_comparison;
11695
11696 if (CRK & CRK_Reversed)
11697 return oc_reversed_binary_operator;
11698
11699 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11700 if (!Ctor->isImplicit()) {
11702 return oc_inherited_constructor;
11703 else
11704 return oc_constructor;
11705 }
11706
11707 if (Ctor->isDefaultConstructor())
11708 return oc_implicit_default_constructor;
11709
11710 if (Ctor->isMoveConstructor())
11711 return oc_implicit_move_constructor;
11712
11713 assert(Ctor->isCopyConstructor() &&
11714 "unexpected sort of implicit constructor");
11715 return oc_implicit_copy_constructor;
11716 }
11717
11718 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11719 // This actually gets spelled 'candidate function' for now, but
11720 // it doesn't hurt to split it out.
11721 if (!Meth->isImplicit())
11722 return oc_method;
11723
11724 if (Meth->isMoveAssignmentOperator())
11725 return oc_implicit_move_assignment;
11726
11727 if (Meth->isCopyAssignmentOperator())
11728 return oc_implicit_copy_assignment;
11729
11730 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11731 return oc_method;
11732 }
11733
11734 return oc_function;
11735 }();
11736
11737 return std::make_pair(Kind, Select);
11738}
11739
11740void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11741 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11742 // set.
11743 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11744 S.Diag(FoundDecl->getLocation(),
11745 diag::note_ovl_candidate_inherited_constructor)
11746 << Shadow->getNominatedBaseClass();
11747}
11748
11749} // end anonymous namespace
11750
11752 const FunctionDecl *FD) {
11753 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11754 bool AlwaysTrue;
11755 if (EnableIf->getCond()->isValueDependent() ||
11756 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11757 return false;
11758 if (!AlwaysTrue)
11759 return false;
11760 }
11761 return true;
11762}
11763
11764/// Returns true if we can take the address of the function.
11765///
11766/// \param Complain - If true, we'll emit a diagnostic
11767/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11768/// we in overload resolution?
11769/// \param Loc - The location of the statement we're complaining about. Ignored
11770/// if we're not complaining, or if we're in overload resolution.
11772 bool Complain,
11773 bool InOverloadResolution,
11774 SourceLocation Loc) {
11775 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11776 if (Complain) {
11777 if (InOverloadResolution)
11778 S.Diag(FD->getBeginLoc(),
11779 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11780 else
11781 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11782 }
11783 return false;
11784 }
11785
11786 if (FD->getTrailingRequiresClause()) {
11787 ConstraintSatisfaction Satisfaction;
11788 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11789 return false;
11790 if (!Satisfaction.IsSatisfied) {
11791 if (Complain) {
11792 if (InOverloadResolution) {
11793 SmallString<128> TemplateArgString;
11794 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11795 TemplateArgString += " ";
11796 TemplateArgString += S.getTemplateArgumentBindingsText(
11797 FunTmpl->getTemplateParameters(),
11799 }
11800
11801 S.Diag(FD->getBeginLoc(),
11802 diag::note_ovl_candidate_unsatisfied_constraints)
11803 << TemplateArgString;
11804 } else
11805 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11806 << FD;
11807 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11808 }
11809 return false;
11810 }
11811 }
11812
11813 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11814 return P->hasAttr<PassObjectSizeAttr>();
11815 });
11816 if (I == FD->param_end())
11817 return true;
11818
11819 if (Complain) {
11820 // Add one to ParamNo because it's user-facing
11821 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11822 if (InOverloadResolution)
11823 S.Diag(FD->getLocation(),
11824 diag::note_ovl_candidate_has_pass_object_size_params)
11825 << ParamNo;
11826 else
11827 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11828 << FD << ParamNo;
11829 }
11830 return false;
11831}
11832
11834 const FunctionDecl *FD) {
11835 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11836 /*InOverloadResolution=*/true,
11837 /*Loc=*/SourceLocation());
11838}
11839
11841 bool Complain,
11842 SourceLocation Loc) {
11843 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11844 /*InOverloadResolution=*/false,
11845 Loc);
11846}
11847
11848// Don't print candidates other than the one that matches the calling
11849// convention of the call operator, since that is guaranteed to exist.
11851 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11852
11853 if (!ConvD)
11854 return false;
11855 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11856 if (!RD->isLambda())
11857 return false;
11858
11859 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11860 CallingConv CallOpCC =
11861 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11862 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11863 CallingConv ConvToCC =
11864 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11865
11866 return ConvToCC != CallOpCC;
11867}
11868
11869// Notes the location of an overload candidate.
11871 OverloadCandidateRewriteKind RewriteKind,
11872 QualType DestType, bool TakingAddress) {
11873 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11874 return;
11875 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11876 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11877 return;
11878 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11879 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11880 return;
11882 return;
11883
11884 std::string FnDesc;
11885 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11886 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11887 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11888 << (unsigned)KSPair.first << (unsigned)KSPair.second
11889 << Fn << FnDesc;
11890
11891 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11892 Diag(Fn->getLocation(), PD);
11893 MaybeEmitInheritedConstructorNote(*this, Found);
11894}
11895
11896static void
11898 // Perhaps the ambiguity was caused by two atomic constraints that are
11899 // 'identical' but not equivalent:
11900 //
11901 // void foo() requires (sizeof(T) > 4) { } // #1
11902 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11903 //
11904 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11905 // #2 to subsume #1, but these constraint are not considered equivalent
11906 // according to the subsumption rules because they are not the same
11907 // source-level construct. This behavior is quite confusing and we should try
11908 // to help the user figure out what happened.
11909
11910 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11911 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11912 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11913 if (!I->Function)
11914 continue;
11916 if (auto *Template = I->Function->getPrimaryTemplate())
11917 Template->getAssociatedConstraints(AC);
11918 else
11919 I->Function->getAssociatedConstraints(AC);
11920 if (AC.empty())
11921 continue;
11922 if (FirstCand == nullptr) {
11923 FirstCand = I->Function;
11924 FirstAC = AC;
11925 } else if (SecondCand == nullptr) {
11926 SecondCand = I->Function;
11927 SecondAC = AC;
11928 } else {
11929 // We have more than one pair of constrained functions - this check is
11930 // expensive and we'd rather not try to diagnose it.
11931 return;
11932 }
11933 }
11934 if (!SecondCand)
11935 return;
11936 // The diagnostic can only happen if there are associated constraints on
11937 // both sides (there needs to be some identical atomic constraint).
11938 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11939 SecondCand, SecondAC))
11940 // Just show the user one diagnostic, they'll probably figure it out
11941 // from here.
11942 return;
11943}
11944
11945// Notes the location of all overload candidates designated through
11946// OverloadedExpr
11947void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11948 bool TakingAddress) {
11949 assert(OverloadedExpr->getType() == Context.OverloadTy);
11950
11951 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11952 OverloadExpr *OvlExpr = Ovl.Expression;
11953
11954 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11955 IEnd = OvlExpr->decls_end();
11956 I != IEnd; ++I) {
11957 if (FunctionTemplateDecl *FunTmpl =
11958 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11959 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11960 TakingAddress);
11961 } else if (FunctionDecl *Fun
11962 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11963 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11964 }
11965 }
11966}
11967
11968/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11969/// "lead" diagnostic; it will be given two arguments, the source and
11970/// target types of the conversion.
11972 Sema &S,
11973 SourceLocation CaretLoc,
11974 const PartialDiagnostic &PDiag) const {
11975 S.Diag(CaretLoc, PDiag)
11976 << Ambiguous.getFromType() << Ambiguous.getToType();
11977 unsigned CandsShown = 0;
11979 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11980 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11981 break;
11982 ++CandsShown;
11983 S.NoteOverloadCandidate(I->first, I->second);
11984 }
11985 S.Diags.overloadCandidatesShown(CandsShown);
11986 if (I != E)
11987 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11988}
11989
11991 unsigned I, bool TakingCandidateAddress) {
11992 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11993 assert(Conv.isBad());
11994 assert(Cand->Function && "for now, candidate must be a function");
11995 FunctionDecl *Fn = Cand->Function;
11996
11997 // There's a conversion slot for the object argument if this is a
11998 // non-constructor method. Note that 'I' corresponds the
11999 // conversion-slot index.
12000 bool isObjectArgument = false;
12001 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12003 if (I == 0)
12004 isObjectArgument = true;
12005 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12006 I--;
12007 }
12008
12009 std::string FnDesc;
12010 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12011 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12012 FnDesc);
12013
12014 Expr *FromExpr = Conv.Bad.FromExpr;
12015 QualType FromTy = Conv.Bad.getFromType();
12016 QualType ToTy = Conv.Bad.getToType();
12017 SourceRange ToParamRange;
12018
12019 // FIXME: In presence of parameter packs we can't determine parameter range
12020 // reliably, as we don't have access to instantiation.
12021 bool HasParamPack =
12022 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12023 return Parm->isParameterPack();
12024 });
12025 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12026 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12027
12028 if (FromTy == S.Context.OverloadTy) {
12029 assert(FromExpr && "overload set argument came from implicit argument?");
12030 Expr *E = FromExpr->IgnoreParens();
12031 if (isa<UnaryOperator>(E))
12032 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12033 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12034
12035 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12036 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12037 << ToParamRange << ToTy << Name << I + 1;
12038 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12039 return;
12040 }
12041
12042 // Do some hand-waving analysis to see if the non-viability is due
12043 // to a qualifier mismatch.
12044 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12045 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12046 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12047 CToTy = RT->getPointeeType();
12048 else {
12049 // TODO: detect and diagnose the full richness of const mismatches.
12050 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12051 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12052 CFromTy = FromPT->getPointeeType();
12053 CToTy = ToPT->getPointeeType();
12054 }
12055 }
12056
12057 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12058 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12059 Qualifiers FromQs = CFromTy.getQualifiers();
12060 Qualifiers ToQs = CToTy.getQualifiers();
12061
12062 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12063 if (isObjectArgument)
12064 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12065 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12066 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12067 else
12068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12069 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12070 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12071 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12072 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12073 return;
12074 }
12075
12076 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12077 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12078 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12079 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12080 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12081 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12082 return;
12083 }
12084
12085 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12087 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12088 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12089 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12090 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12091 return;
12092 }
12093
12094 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12095 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12096 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12097 << FromTy << !!FromQs.getPointerAuth()
12098 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12099 << ToQs.getPointerAuth().getAsString() << I + 1
12100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12101 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12102 return;
12103 }
12104
12105 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12106 assert(CVR && "expected qualifiers mismatch");
12107
12108 if (isObjectArgument) {
12109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12110 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12111 << FromTy << (CVR - 1);
12112 } else {
12113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12114 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12115 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12116 }
12117 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12118 return;
12119 }
12120
12123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12124 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12125 << (unsigned)isObjectArgument << I + 1
12127 << ToParamRange;
12128 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12129 return;
12130 }
12131
12132 // Special diagnostic for failure to convert an initializer list, since
12133 // telling the user that it has type void is not useful.
12134 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12136 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12137 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12140 ? 2
12141 : 0);
12142 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12143 return;
12144 }
12145
12146 // Diagnose references or pointers to incomplete types differently,
12147 // since it's far from impossible that the incompleteness triggered
12148 // the failure.
12149 QualType TempFromTy = FromTy.getNonReferenceType();
12150 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12151 TempFromTy = PTy->getPointeeType();
12152 if (TempFromTy->isIncompleteType()) {
12153 // Emit the generic diagnostic and, optionally, add the hints to it.
12154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12155 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12156 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12157 << (unsigned)(Cand->Fix.Kind);
12158
12159 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12160 return;
12161 }
12162
12163 // Diagnose base -> derived pointer conversions.
12164 unsigned BaseToDerivedConversion = 0;
12165 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12166 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12167 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12168 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12169 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12170 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12171 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12172 FromPtrTy->getPointeeType()))
12173 BaseToDerivedConversion = 1;
12174 }
12175 } else if (const ObjCObjectPointerType *FromPtrTy
12176 = FromTy->getAs<ObjCObjectPointerType>()) {
12177 if (const ObjCObjectPointerType *ToPtrTy
12178 = ToTy->getAs<ObjCObjectPointerType>())
12179 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12180 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12181 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12182 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12183 FromIface->isSuperClassOf(ToIface))
12184 BaseToDerivedConversion = 2;
12185 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12186 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12187 S.getASTContext()) &&
12188 !FromTy->isIncompleteType() &&
12189 !ToRefTy->getPointeeType()->isIncompleteType() &&
12190 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12191 BaseToDerivedConversion = 3;
12192 }
12193 }
12194
12195 if (BaseToDerivedConversion) {
12196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12197 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12198 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12199 << I + 1;
12200 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12201 return;
12202 }
12203
12204 if (isa<ObjCObjectPointerType>(CFromTy) &&
12205 isa<PointerType>(CToTy)) {
12206 Qualifiers FromQs = CFromTy.getQualifiers();
12207 Qualifiers ToQs = CToTy.getQualifiers();
12208 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12209 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12210 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12211 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12212 << I + 1;
12213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12214 return;
12215 }
12216 }
12217
12218 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12219 return;
12220
12221 // Emit the generic diagnostic and, optionally, add the hints to it.
12222 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12223 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12224 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12225 << (unsigned)(Cand->Fix.Kind);
12226
12227 // Check that location of Fn is not in system header.
12228 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12229 // If we can fix the conversion, suggest the FixIts.
12230 for (const FixItHint &HI : Cand->Fix.Hints)
12231 FDiag << HI;
12232 }
12233
12234 S.Diag(Fn->getLocation(), FDiag);
12235
12236 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12237}
12238
12239/// Additional arity mismatch diagnosis specific to a function overload
12240/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12241/// over a candidate in any candidate set.
12243 unsigned NumArgs, bool IsAddressOf = false) {
12244 assert(Cand->Function && "Candidate is required to be a function.");
12245 FunctionDecl *Fn = Cand->Function;
12246 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12247 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12248
12249 // With invalid overloaded operators, it's possible that we think we
12250 // have an arity mismatch when in fact it looks like we have the
12251 // right number of arguments, because only overloaded operators have
12252 // the weird behavior of overloading member and non-member functions.
12253 // Just don't report anything.
12254 if (Fn->isInvalidDecl() &&
12255 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12256 return true;
12257
12258 if (NumArgs < MinParams) {
12259 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12261 Cand->DeductionFailure.getResult() ==
12263 } else {
12264 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12266 Cand->DeductionFailure.getResult() ==
12268 }
12269
12270 return false;
12271}
12272
12273/// General arity mismatch diagnosis over a candidate in a candidate set.
12275 unsigned NumFormalArgs,
12276 bool IsAddressOf = false) {
12277 assert(isa<FunctionDecl>(D) &&
12278 "The templated declaration should at least be a function"
12279 " when diagnosing bad template argument deduction due to too many"
12280 " or too few arguments");
12281
12283
12284 // TODO: treat calls to a missing default constructor as a special case
12285 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12286 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12287 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12288
12289 // at least / at most / exactly
12290 bool HasExplicitObjectParam =
12291 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12292
12293 unsigned ParamCount =
12294 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12295 unsigned mode, modeCount;
12296
12297 if (NumFormalArgs < MinParams) {
12298 if (MinParams != ParamCount || FnTy->isVariadic() ||
12299 FnTy->isTemplateVariadic())
12300 mode = 0; // "at least"
12301 else
12302 mode = 2; // "exactly"
12303 modeCount = MinParams;
12304 } else {
12305 if (MinParams != ParamCount)
12306 mode = 1; // "at most"
12307 else
12308 mode = 2; // "exactly"
12309 modeCount = ParamCount;
12310 }
12311
12312 std::string Description;
12313 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12314 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12315
12316 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12317 if (modeCount == 1 && !IsAddressOf &&
12318 FirstNonObjectParamIdx < Fn->getNumParams() &&
12319 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12320 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12321 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12322 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12323 << NumFormalArgs << HasExplicitObjectParam
12324 << Fn->getParametersSourceRange();
12325 else
12326 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12327 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12328 << Description << mode << modeCount << NumFormalArgs
12329 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12330
12331 MaybeEmitInheritedConstructorNote(S, Found);
12332}
12333
12334/// Arity mismatch diagnosis specific to a function overload candidate.
12336 unsigned NumFormalArgs) {
12337 assert(Cand->Function && "Candidate must be a function");
12338 FunctionDecl *Fn = Cand->Function;
12339 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12340 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12341 Cand->TookAddressOfOverload);
12342}
12343
12345 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12346 return TD;
12347 llvm_unreachable("Unsupported: Getting the described template declaration"
12348 " for bad deduction diagnosis");
12349}
12350
12351/// Diagnose a failed template-argument deduction.
12352static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12353 DeductionFailureInfo &DeductionFailure,
12354 unsigned NumArgs,
12355 bool TakingCandidateAddress) {
12356 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12357 NamedDecl *ParamD;
12358 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12359 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12360 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12361 switch (DeductionFailure.getResult()) {
12363 llvm_unreachable(
12364 "TemplateDeductionResult::Success while diagnosing bad deduction");
12366 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12367 "while diagnosing bad deduction");
12370 return;
12371
12373 assert(ParamD && "no parameter found for incomplete deduction result");
12374 S.Diag(Templated->getLocation(),
12375 diag::note_ovl_candidate_incomplete_deduction)
12376 << ParamD->getDeclName();
12377 MaybeEmitInheritedConstructorNote(S, Found);
12378 return;
12379 }
12380
12382 assert(ParamD && "no parameter found for incomplete deduction result");
12383 S.Diag(Templated->getLocation(),
12384 diag::note_ovl_candidate_incomplete_deduction_pack)
12385 << ParamD->getDeclName()
12386 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12387 << *DeductionFailure.getFirstArg();
12388 MaybeEmitInheritedConstructorNote(S, Found);
12389 return;
12390 }
12391
12393 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12395
12396 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12397
12398 // Param will have been canonicalized, but it should just be a
12399 // qualified version of ParamD, so move the qualifiers to that.
12401 Qs.strip(Param);
12402 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12403 assert(S.Context.hasSameType(Param, NonCanonParam));
12404
12405 // Arg has also been canonicalized, but there's nothing we can do
12406 // about that. It also doesn't matter as much, because it won't
12407 // have any template parameters in it (because deduction isn't
12408 // done on dependent types).
12409 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12410
12411 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12412 << ParamD->getDeclName() << Arg << NonCanonParam;
12413 MaybeEmitInheritedConstructorNote(S, Found);
12414 return;
12415 }
12416
12418 assert(ParamD && "no parameter found for inconsistent deduction result");
12419 int which = 0;
12420 if (isa<TemplateTypeParmDecl>(ParamD))
12421 which = 0;
12422 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12423 // Deduction might have failed because we deduced arguments of two
12424 // different types for a non-type template parameter.
12425 // FIXME: Use a different TDK value for this.
12426 QualType T1 =
12427 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12428 QualType T2 =
12429 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12430 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12431 S.Diag(Templated->getLocation(),
12432 diag::note_ovl_candidate_inconsistent_deduction_types)
12433 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12434 << *DeductionFailure.getSecondArg() << T2;
12435 MaybeEmitInheritedConstructorNote(S, Found);
12436 return;
12437 }
12438
12439 which = 1;
12440 } else {
12441 which = 2;
12442 }
12443
12444 // Tweak the diagnostic if the problem is that we deduced packs of
12445 // different arities. We'll print the actual packs anyway in case that
12446 // includes additional useful information.
12447 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12448 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12449 DeductionFailure.getFirstArg()->pack_size() !=
12450 DeductionFailure.getSecondArg()->pack_size()) {
12451 which = 3;
12452 }
12453
12454 S.Diag(Templated->getLocation(),
12455 diag::note_ovl_candidate_inconsistent_deduction)
12456 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12457 << *DeductionFailure.getSecondArg();
12458 MaybeEmitInheritedConstructorNote(S, Found);
12459 return;
12460 }
12461
12463 assert(ParamD && "no parameter found for invalid explicit arguments");
12464 if (ParamD->getDeclName())
12465 S.Diag(Templated->getLocation(),
12466 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12467 << ParamD->getDeclName();
12468 else {
12469 int index = 0;
12470 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12471 index = TTP->getIndex();
12472 else if (NonTypeTemplateParmDecl *NTTP
12473 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12474 index = NTTP->getIndex();
12475 else
12476 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12477 S.Diag(Templated->getLocation(),
12478 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12479 << (index + 1);
12480 }
12481 MaybeEmitInheritedConstructorNote(S, Found);
12482 return;
12483
12485 // Format the template argument list into the argument string.
12486 SmallString<128> TemplateArgString;
12487 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12488 TemplateArgString = " ";
12489 TemplateArgString += S.getTemplateArgumentBindingsText(
12490 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12491 if (TemplateArgString.size() == 1)
12492 TemplateArgString.clear();
12493 S.Diag(Templated->getLocation(),
12494 diag::note_ovl_candidate_unsatisfied_constraints)
12495 << TemplateArgString;
12496
12498 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12499 return;
12500 }
12503 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12504 return;
12505
12507 S.Diag(Templated->getLocation(),
12508 diag::note_ovl_candidate_instantiation_depth);
12509 MaybeEmitInheritedConstructorNote(S, Found);
12510 return;
12511
12513 // Format the template argument list into the argument string.
12514 SmallString<128> TemplateArgString;
12515 if (TemplateArgumentList *Args =
12516 DeductionFailure.getTemplateArgumentList()) {
12517 TemplateArgString = " ";
12518 TemplateArgString += S.getTemplateArgumentBindingsText(
12519 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12520 if (TemplateArgString.size() == 1)
12521 TemplateArgString.clear();
12522 }
12523
12524 // If this candidate was disabled by enable_if, say so.
12525 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12526 if (PDiag && PDiag->second.getDiagID() ==
12527 diag::err_typename_nested_not_found_enable_if) {
12528 // FIXME: Use the source range of the condition, and the fully-qualified
12529 // name of the enable_if template. These are both present in PDiag.
12530 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12531 << "'enable_if'" << TemplateArgString;
12532 return;
12533 }
12534
12535 // We found a specific requirement that disabled the enable_if.
12536 if (PDiag && PDiag->second.getDiagID() ==
12537 diag::err_typename_nested_not_found_requirement) {
12538 S.Diag(Templated->getLocation(),
12539 diag::note_ovl_candidate_disabled_by_requirement)
12540 << PDiag->second.getStringArg(0) << TemplateArgString;
12541 return;
12542 }
12543
12544 // Format the SFINAE diagnostic into the argument string.
12545 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12546 // formatted message in another diagnostic.
12547 SmallString<128> SFINAEArgString;
12548 SourceRange R;
12549 if (PDiag) {
12550 SFINAEArgString = ": ";
12551 R = SourceRange(PDiag->first, PDiag->first);
12552 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12553 }
12554
12555 S.Diag(Templated->getLocation(),
12556 diag::note_ovl_candidate_substitution_failure)
12557 << TemplateArgString << SFINAEArgString << R;
12558 MaybeEmitInheritedConstructorNote(S, Found);
12559 return;
12560 }
12561
12564 // Format the template argument list into the argument string.
12565 SmallString<128> TemplateArgString;
12566 if (TemplateArgumentList *Args =
12567 DeductionFailure.getTemplateArgumentList()) {
12568 TemplateArgString = " ";
12569 TemplateArgString += S.getTemplateArgumentBindingsText(
12570 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12571 if (TemplateArgString.size() == 1)
12572 TemplateArgString.clear();
12573 }
12574
12575 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12576 << (*DeductionFailure.getCallArgIndex() + 1)
12577 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12578 << TemplateArgString
12579 << (DeductionFailure.getResult() ==
12581 break;
12582 }
12583
12585 // FIXME: Provide a source location to indicate what we couldn't match.
12586 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12587 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12588 if (FirstTA.getKind() == TemplateArgument::Template &&
12589 SecondTA.getKind() == TemplateArgument::Template) {
12590 TemplateName FirstTN = FirstTA.getAsTemplate();
12591 TemplateName SecondTN = SecondTA.getAsTemplate();
12592 if (FirstTN.getKind() == TemplateName::Template &&
12593 SecondTN.getKind() == TemplateName::Template) {
12594 if (FirstTN.getAsTemplateDecl()->getName() ==
12595 SecondTN.getAsTemplateDecl()->getName()) {
12596 // FIXME: This fixes a bad diagnostic where both templates are named
12597 // the same. This particular case is a bit difficult since:
12598 // 1) It is passed as a string to the diagnostic printer.
12599 // 2) The diagnostic printer only attempts to find a better
12600 // name for types, not decls.
12601 // Ideally, this should folded into the diagnostic printer.
12602 S.Diag(Templated->getLocation(),
12603 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12604 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12605 return;
12606 }
12607 }
12608 }
12609
12610 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12612 return;
12613
12614 // FIXME: For generic lambda parameters, check if the function is a lambda
12615 // call operator, and if so, emit a prettier and more informative
12616 // diagnostic that mentions 'auto' and lambda in addition to
12617 // (or instead of?) the canonical template type parameters.
12618 S.Diag(Templated->getLocation(),
12619 diag::note_ovl_candidate_non_deduced_mismatch)
12620 << FirstTA << SecondTA;
12621 return;
12622 }
12623 // TODO: diagnose these individually, then kill off
12624 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12626 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12627 MaybeEmitInheritedConstructorNote(S, Found);
12628 return;
12630 S.Diag(Templated->getLocation(),
12631 diag::note_cuda_ovl_candidate_target_mismatch);
12632 return;
12633 }
12634}
12635
12636/// Diagnose a failed template-argument deduction, for function calls.
12638 unsigned NumArgs,
12639 bool TakingCandidateAddress) {
12640 assert(Cand->Function && "Candidate must be a function");
12641 FunctionDecl *Fn = Cand->Function;
12645 if (CheckArityMismatch(S, Cand, NumArgs))
12646 return;
12647 }
12648 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12649 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12650}
12651
12652/// CUDA: diagnose an invalid call across targets.
12654 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12655 assert(Cand->Function && "Candidate must be a Function.");
12656 FunctionDecl *Callee = Cand->Function;
12657
12658 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12659 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12660
12661 std::string FnDesc;
12662 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12663 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12664 Cand->getRewriteKind(), FnDesc);
12665
12666 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12667 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12668 << FnDesc /* Ignored */
12669 << CalleeTarget << CallerTarget;
12670
12671 // This could be an implicit constructor for which we could not infer the
12672 // target due to a collsion. Diagnose that case.
12673 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12674 if (Meth != nullptr && Meth->isImplicit()) {
12675 CXXRecordDecl *ParentClass = Meth->getParent();
12677
12678 switch (FnKindPair.first) {
12679 default:
12680 return;
12681 case oc_implicit_default_constructor:
12683 break;
12684 case oc_implicit_copy_constructor:
12686 break;
12687 case oc_implicit_move_constructor:
12689 break;
12690 case oc_implicit_copy_assignment:
12692 break;
12693 case oc_implicit_move_assignment:
12695 break;
12696 };
12697
12698 bool ConstRHS = false;
12699 if (Meth->getNumParams()) {
12700 if (const ReferenceType *RT =
12701 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12702 ConstRHS = RT->getPointeeType().isConstQualified();
12703 }
12704 }
12705
12706 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12707 /* ConstRHS */ ConstRHS,
12708 /* Diagnose */ true);
12709 }
12710}
12711
12713 assert(Cand->Function && "Candidate must be a function");
12714 FunctionDecl *Callee = Cand->Function;
12715 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12716
12717 S.Diag(Callee->getLocation(),
12718 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12719 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12720}
12721
12723 assert(Cand->Function && "Candidate must be a function");
12724 FunctionDecl *Fn = Cand->Function;
12726 assert(ES.isExplicit() && "not an explicit candidate");
12727
12728 unsigned Kind;
12729 switch (Fn->getDeclKind()) {
12730 case Decl::Kind::CXXConstructor:
12731 Kind = 0;
12732 break;
12733 case Decl::Kind::CXXConversion:
12734 Kind = 1;
12735 break;
12736 case Decl::Kind::CXXDeductionGuide:
12737 Kind = Fn->isImplicit() ? 0 : 2;
12738 break;
12739 default:
12740 llvm_unreachable("invalid Decl");
12741 }
12742
12743 // Note the location of the first (in-class) declaration; a redeclaration
12744 // (particularly an out-of-class definition) will typically lack the
12745 // 'explicit' specifier.
12746 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12747 FunctionDecl *First = Fn->getFirstDecl();
12748 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12749 First = Pattern->getFirstDecl();
12750
12751 S.Diag(First->getLocation(),
12752 diag::note_ovl_candidate_explicit)
12753 << Kind << (ES.getExpr() ? 1 : 0)
12754 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12755}
12756
12758 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12759 if (!DG)
12760 return;
12761 TemplateDecl *OriginTemplate =
12763 // We want to always print synthesized deduction guides for type aliases.
12764 // They would retain the explicit bit of the corresponding constructor.
12765 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12766 return;
12767 std::string FunctionProto;
12768 llvm::raw_string_ostream OS(FunctionProto);
12769 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12770 if (!Template) {
12771 // This also could be an instantiation. Find out the primary template.
12772 FunctionDecl *Pattern =
12773 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12774 if (!Pattern) {
12775 // The implicit deduction guide is built on an explicit non-template
12776 // deduction guide. Currently, this might be the case only for type
12777 // aliases.
12778 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12779 // gets merged.
12780 assert(OriginTemplate->isTypeAlias() &&
12781 "Non-template implicit deduction guides are only possible for "
12782 "type aliases");
12783 DG->print(OS);
12784 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12785 << FunctionProto;
12786 return;
12787 }
12789 assert(Template && "Cannot find the associated function template of "
12790 "CXXDeductionGuideDecl?");
12791 }
12792 Template->print(OS);
12793 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12794 << FunctionProto;
12795}
12796
12797/// Generates a 'note' diagnostic for an overload candidate. We've
12798/// already generated a primary error at the call site.
12799///
12800/// It really does need to be a single diagnostic with its caret
12801/// pointed at the candidate declaration. Yes, this creates some
12802/// major challenges of technical writing. Yes, this makes pointing
12803/// out problems with specific arguments quite awkward. It's still
12804/// better than generating twenty screens of text for every failed
12805/// overload.
12806///
12807/// It would be great to be able to express per-candidate problems
12808/// more richly for those diagnostic clients that cared, but we'd
12809/// still have to be just as careful with the default diagnostics.
12810/// \param CtorDestAS Addr space of object being constructed (for ctor
12811/// candidates only).
12813 unsigned NumArgs,
12814 bool TakingCandidateAddress,
12815 LangAS CtorDestAS = LangAS::Default) {
12816 assert(Cand->Function && "Candidate must be a function");
12817 FunctionDecl *Fn = Cand->Function;
12819 return;
12820
12821 // There is no physical candidate declaration to point to for OpenCL builtins.
12822 // Except for failed conversions, the notes are identical for each candidate,
12823 // so do not generate such notes.
12824 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12826 return;
12827
12828 // Skip implicit member functions when trying to resolve
12829 // the address of a an overload set for a function pointer.
12830 if (Cand->TookAddressOfOverload &&
12831 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12832 return;
12833
12834 // Note deleted candidates, but only if they're viable.
12835 if (Cand->Viable) {
12836 if (Fn->isDeleted()) {
12837 std::string FnDesc;
12838 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12839 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12840 Cand->getRewriteKind(), FnDesc);
12841
12842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12843 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12844 << (Fn->isDeleted()
12845 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12846 : 0);
12847 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12848 return;
12849 }
12850
12851 // We don't really have anything else to say about viable candidates.
12852 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12853 return;
12854 }
12855
12856 // If this is a synthesized deduction guide we're deducing against, add a note
12857 // for it. These deduction guides are not explicitly spelled in the source
12858 // code, so simply printing a deduction failure note mentioning synthesized
12859 // template parameters or pointing to the header of the surrounding RecordDecl
12860 // would be confusing.
12861 //
12862 // We prefer adding such notes at the end of the deduction failure because
12863 // duplicate code snippets appearing in the diagnostic would likely become
12864 // noisy.
12865 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12866
12867 switch (Cand->FailureKind) {
12870 return DiagnoseArityMismatch(S, Cand, NumArgs);
12871
12873 return DiagnoseBadDeduction(S, Cand, NumArgs,
12874 TakingCandidateAddress);
12875
12877 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12878 << (Fn->getPrimaryTemplate() ? 1 : 0);
12879 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12880 return;
12881 }
12882
12884 Qualifiers QualsForPrinting;
12885 QualsForPrinting.setAddressSpace(CtorDestAS);
12886 S.Diag(Fn->getLocation(),
12887 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12888 << QualsForPrinting;
12889 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12890 return;
12891 }
12892
12896 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12897
12899 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12900 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12901 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12902 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12903
12904 // FIXME: this currently happens when we're called from SemaInit
12905 // when user-conversion overload fails. Figure out how to handle
12906 // those conditions and diagnose them well.
12907 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12908 }
12909
12911 return DiagnoseBadTarget(S, Cand);
12912
12913 case ovl_fail_enable_if:
12914 return DiagnoseFailedEnableIfAttr(S, Cand);
12915
12916 case ovl_fail_explicit:
12917 return DiagnoseFailedExplicitSpec(S, Cand);
12918
12920 // It's generally not interesting to note copy/move constructors here.
12921 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12922 return;
12923 S.Diag(Fn->getLocation(),
12924 diag::note_ovl_candidate_inherited_constructor_slice)
12925 << (Fn->getPrimaryTemplate() ? 1 : 0)
12926 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12927 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12928 return;
12929
12931 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12932 (void)Available;
12933 assert(!Available);
12934 break;
12935 }
12937 // Do nothing, these should simply be ignored.
12938 break;
12939
12941 std::string FnDesc;
12942 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12943 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12944 Cand->getRewriteKind(), FnDesc);
12945
12946 S.Diag(Fn->getLocation(),
12947 diag::note_ovl_candidate_constraints_not_satisfied)
12948 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12949 << FnDesc /* Ignored */;
12950 ConstraintSatisfaction Satisfaction;
12951 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12952 /*ForOverloadResolution=*/true))
12953 break;
12954 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12955 }
12956 }
12957}
12958
12961 return;
12962
12963 // Desugar the type of the surrogate down to a function type,
12964 // retaining as many typedefs as possible while still showing
12965 // the function type (and, therefore, its parameter types).
12966 QualType FnType = Cand->Surrogate->getConversionType();
12967 bool isLValueReference = false;
12968 bool isRValueReference = false;
12969 bool isPointer = false;
12970 if (const LValueReferenceType *FnTypeRef =
12971 FnType->getAs<LValueReferenceType>()) {
12972 FnType = FnTypeRef->getPointeeType();
12973 isLValueReference = true;
12974 } else if (const RValueReferenceType *FnTypeRef =
12975 FnType->getAs<RValueReferenceType>()) {
12976 FnType = FnTypeRef->getPointeeType();
12977 isRValueReference = true;
12978 }
12979 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12980 FnType = FnTypePtr->getPointeeType();
12981 isPointer = true;
12982 }
12983 // Desugar down to a function type.
12984 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12985 // Reconstruct the pointer/reference as appropriate.
12986 if (isPointer) FnType = S.Context.getPointerType(FnType);
12987 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12988 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12989
12990 if (!Cand->Viable &&
12992 S.Diag(Cand->Surrogate->getLocation(),
12993 diag::note_ovl_surrogate_constraints_not_satisfied)
12994 << Cand->Surrogate;
12995 ConstraintSatisfaction Satisfaction;
12996 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12997 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12998 } else {
12999 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13000 << FnType;
13001 }
13002}
13003
13004static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13005 SourceLocation OpLoc,
13006 OverloadCandidate *Cand) {
13007 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13008 std::string TypeStr("operator");
13009 TypeStr += Opc;
13010 TypeStr += "(";
13011 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13012 if (Cand->Conversions.size() == 1) {
13013 TypeStr += ")";
13014 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13015 } else {
13016 TypeStr += ", ";
13017 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13018 TypeStr += ")";
13019 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13020 }
13021}
13022
13024 OverloadCandidate *Cand) {
13025 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13026 if (ICS.isBad()) break; // all meaningless after first invalid
13027 if (!ICS.isAmbiguous()) continue;
13028
13030 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13031 }
13032}
13033
13035 if (Cand->Function)
13036 return Cand->Function->getLocation();
13037 if (Cand->IsSurrogate)
13038 return Cand->Surrogate->getLocation();
13039 return SourceLocation();
13040}
13041
13042static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13043 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13047 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13048
13052 return 1;
13053
13056 return 2;
13057
13065 return 3;
13066
13068 return 4;
13069
13071 return 5;
13072
13075 return 6;
13076 }
13077 llvm_unreachable("Unhandled deduction result");
13078}
13079
13080namespace {
13081
13082struct CompareOverloadCandidatesForDisplay {
13083 Sema &S;
13084 SourceLocation Loc;
13085 size_t NumArgs;
13087
13088 CompareOverloadCandidatesForDisplay(
13089 Sema &S, SourceLocation Loc, size_t NArgs,
13091 : S(S), NumArgs(NArgs), CSK(CSK) {}
13092
13093 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13094 // If there are too many or too few arguments, that's the high-order bit we
13095 // want to sort by, even if the immediate failure kind was something else.
13096 if (C->FailureKind == ovl_fail_too_many_arguments ||
13097 C->FailureKind == ovl_fail_too_few_arguments)
13098 return static_cast<OverloadFailureKind>(C->FailureKind);
13099
13100 if (C->Function) {
13101 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13103 if (NumArgs < C->Function->getMinRequiredArguments())
13105 }
13106
13107 return static_cast<OverloadFailureKind>(C->FailureKind);
13108 }
13109
13110 bool operator()(const OverloadCandidate *L,
13111 const OverloadCandidate *R) {
13112 // Fast-path this check.
13113 if (L == R) return false;
13114
13115 // Order first by viability.
13116 if (L->Viable) {
13117 if (!R->Viable) return true;
13118
13119 if (int Ord = CompareConversions(*L, *R))
13120 return Ord < 0;
13121 // Use other tie breakers.
13122 } else if (R->Viable)
13123 return false;
13124
13125 assert(L->Viable == R->Viable);
13126
13127 // Criteria by which we can sort non-viable candidates:
13128 if (!L->Viable) {
13129 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13130 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13131
13132 // 1. Arity mismatches come after other candidates.
13133 if (LFailureKind == ovl_fail_too_many_arguments ||
13134 LFailureKind == ovl_fail_too_few_arguments) {
13135 if (RFailureKind == ovl_fail_too_many_arguments ||
13136 RFailureKind == ovl_fail_too_few_arguments) {
13137 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13138 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13139 if (LDist == RDist) {
13140 if (LFailureKind == RFailureKind)
13141 // Sort non-surrogates before surrogates.
13142 return !L->IsSurrogate && R->IsSurrogate;
13143 // Sort candidates requiring fewer parameters than there were
13144 // arguments given after candidates requiring more parameters
13145 // than there were arguments given.
13146 return LFailureKind == ovl_fail_too_many_arguments;
13147 }
13148 return LDist < RDist;
13149 }
13150 return false;
13151 }
13152 if (RFailureKind == ovl_fail_too_many_arguments ||
13153 RFailureKind == ovl_fail_too_few_arguments)
13154 return true;
13155
13156 // 2. Bad conversions come first and are ordered by the number
13157 // of bad conversions and quality of good conversions.
13158 if (LFailureKind == ovl_fail_bad_conversion) {
13159 if (RFailureKind != ovl_fail_bad_conversion)
13160 return true;
13161
13162 // The conversion that can be fixed with a smaller number of changes,
13163 // comes first.
13164 unsigned numLFixes = L->Fix.NumConversionsFixed;
13165 unsigned numRFixes = R->Fix.NumConversionsFixed;
13166 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13167 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13168 if (numLFixes != numRFixes) {
13169 return numLFixes < numRFixes;
13170 }
13171
13172 // If there's any ordering between the defined conversions...
13173 if (int Ord = CompareConversions(*L, *R))
13174 return Ord < 0;
13175 } else if (RFailureKind == ovl_fail_bad_conversion)
13176 return false;
13177
13178 if (LFailureKind == ovl_fail_bad_deduction) {
13179 if (RFailureKind != ovl_fail_bad_deduction)
13180 return true;
13181
13182 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13183 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13184 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13185 if (LRank != RRank)
13186 return LRank < RRank;
13187 }
13188 } else if (RFailureKind == ovl_fail_bad_deduction)
13189 return false;
13190
13191 // TODO: others?
13192 }
13193
13194 // Sort everything else by location.
13195 SourceLocation LLoc = GetLocationForCandidate(L);
13196 SourceLocation RLoc = GetLocationForCandidate(R);
13197
13198 // Put candidates without locations (e.g. builtins) at the end.
13199 if (LLoc.isValid() && RLoc.isValid())
13200 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13201 if (LLoc.isValid() && !RLoc.isValid())
13202 return true;
13203 if (RLoc.isValid() && !LLoc.isValid())
13204 return false;
13205 assert(!LLoc.isValid() && !RLoc.isValid());
13206 // For builtins and other functions without locations, fallback to the order
13207 // in which they were added into the candidate set.
13208 return L < R;
13209 }
13210
13211private:
13212 struct ConversionSignals {
13213 unsigned KindRank = 0;
13215
13216 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13217 ConversionSignals Sig;
13218 Sig.KindRank = Seq.getKindRank();
13219 if (Seq.isStandard())
13220 Sig.Rank = Seq.Standard.getRank();
13221 else if (Seq.isUserDefined())
13222 Sig.Rank = Seq.UserDefined.After.getRank();
13223 // We intend StaticObjectArgumentConversion to compare the same as
13224 // StandardConversion with ICR_ExactMatch rank.
13225 return Sig;
13226 }
13227
13228 static ConversionSignals ForObjectArgument() {
13229 // We intend StaticObjectArgumentConversion to compare the same as
13230 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13231 return {};
13232 }
13233 };
13234
13235 // Returns -1 if conversions in L are considered better.
13236 // 0 if they are considered indistinguishable.
13237 // 1 if conversions in R are better.
13238 int CompareConversions(const OverloadCandidate &L,
13239 const OverloadCandidate &R) {
13240 // We cannot use `isBetterOverloadCandidate` because it is defined
13241 // according to the C++ standard and provides a partial order, but we need
13242 // a total order as this function is used in sort.
13243 assert(L.Conversions.size() == R.Conversions.size());
13244 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13245 auto LS = L.IgnoreObjectArgument && I == 0
13246 ? ConversionSignals::ForObjectArgument()
13247 : ConversionSignals::ForSequence(L.Conversions[I]);
13248 auto RS = R.IgnoreObjectArgument
13249 ? ConversionSignals::ForObjectArgument()
13250 : ConversionSignals::ForSequence(R.Conversions[I]);
13251 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13252 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13253 ? -1
13254 : 1;
13255 }
13256 // FIXME: find a way to compare templates for being more or less
13257 // specialized that provides a strict weak ordering.
13258 return 0;
13259 }
13260};
13261}
13262
13263/// CompleteNonViableCandidate - Normally, overload resolution only
13264/// computes up to the first bad conversion. Produces the FixIt set if
13265/// possible.
13266static void
13268 ArrayRef<Expr *> Args,
13270 assert(!Cand->Viable);
13271
13272 // Don't do anything on failures other than bad conversion.
13274 return;
13275
13276 // We only want the FixIts if all the arguments can be corrected.
13277 bool Unfixable = false;
13278 // Use a implicit copy initialization to check conversion fixes.
13280
13281 // Attempt to fix the bad conversion.
13282 unsigned ConvCount = Cand->Conversions.size();
13283 for (unsigned ConvIdx =
13284 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13285 : 0);
13286 /**/; ++ConvIdx) {
13287 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13288 if (Cand->Conversions[ConvIdx].isInitialized() &&
13289 Cand->Conversions[ConvIdx].isBad()) {
13290 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13291 break;
13292 }
13293 }
13294
13295 // FIXME: this should probably be preserved from the overload
13296 // operation somehow.
13297 bool SuppressUserConversions = false;
13298
13299 unsigned ConvIdx = 0;
13300 unsigned ArgIdx = 0;
13301 ArrayRef<QualType> ParamTypes;
13302 bool Reversed = Cand->isReversed();
13303
13304 if (Cand->IsSurrogate) {
13305 QualType ConvType
13307 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13308 ConvType = ConvPtrType->getPointeeType();
13309 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13310 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13311 ConvIdx = 1;
13312 } else if (Cand->Function) {
13313 ParamTypes =
13314 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13315 if (isa<CXXMethodDecl>(Cand->Function) &&
13318 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13319 ConvIdx = 1;
13321 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13323 OO_Subscript)
13324 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13325 ArgIdx = 1;
13326 }
13327 } else {
13328 // Builtin operator.
13329 assert(ConvCount <= 3);
13330 ParamTypes = Cand->BuiltinParamTypes;
13331 }
13332
13333 // Fill in the rest of the conversions.
13334 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13335 ConvIdx != ConvCount && ArgIdx < Args.size();
13336 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13337 if (Cand->Conversions[ConvIdx].isInitialized()) {
13338 // We've already checked this conversion.
13339 } else if (ParamIdx < ParamTypes.size()) {
13340 if (ParamTypes[ParamIdx]->isDependentType())
13341 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13342 Args[ArgIdx]->getType());
13343 else {
13344 Cand->Conversions[ConvIdx] =
13345 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13346 SuppressUserConversions,
13347 /*InOverloadResolution=*/true,
13348 /*AllowObjCWritebackConversion=*/
13349 S.getLangOpts().ObjCAutoRefCount);
13350 // Store the FixIt in the candidate if it exists.
13351 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13352 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13353 }
13354 } else
13355 Cand->Conversions[ConvIdx].setEllipsis();
13356 }
13357}
13358
13361 SourceLocation OpLoc,
13362 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13363
13365
13366 // Sort the candidates by viability and position. Sorting directly would
13367 // be prohibitive, so we make a set of pointers and sort those.
13369 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13370 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13371 Cand != LastCand; ++Cand) {
13372 if (!Filter(*Cand))
13373 continue;
13374 switch (OCD) {
13375 case OCD_AllCandidates:
13376 if (!Cand->Viable) {
13377 if (!Cand->Function && !Cand->IsSurrogate) {
13378 // This a non-viable builtin candidate. We do not, in general,
13379 // want to list every possible builtin candidate.
13380 continue;
13381 }
13382 CompleteNonViableCandidate(S, Cand, Args, Kind);
13383 }
13384 break;
13385
13387 if (!Cand->Viable)
13388 continue;
13389 break;
13390
13392 if (!Cand->Best)
13393 continue;
13394 break;
13395 }
13396
13397 Cands.push_back(Cand);
13398 }
13399
13400 llvm::stable_sort(
13401 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13402
13403 return Cands;
13404}
13405
13407 SourceLocation OpLoc) {
13408 bool DeferHint = false;
13409 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13410 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13411 // host device candidates.
13412 auto WrongSidedCands =
13413 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13414 return (Cand.Viable == false &&
13416 (Cand.Function &&
13417 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13418 Cand.Function->template hasAttr<CUDADeviceAttr>());
13419 });
13420 DeferHint = !WrongSidedCands.empty();
13421 }
13422 return DeferHint;
13423}
13424
13425/// When overload resolution fails, prints diagnostic messages containing the
13426/// candidates in the candidate set.
13429 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13430 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13431
13432 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13433
13434 {
13435 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13436 S.Diag(PD.first, PD.second);
13437 }
13438
13439 // In WebAssembly we don't want to emit further diagnostics if a table is
13440 // passed as an argument to a function.
13441 bool NoteCands = true;
13442 for (const Expr *Arg : Args) {
13443 if (Arg->getType()->isWebAssemblyTableType())
13444 NoteCands = false;
13445 }
13446
13447 if (NoteCands)
13448 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13449
13450 if (OCD == OCD_AmbiguousCandidates)
13452 {Candidates.begin(), Candidates.end()});
13453}
13454
13457 StringRef Opc, SourceLocation OpLoc) {
13458 bool ReportedAmbiguousConversions = false;
13459
13460 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13461 unsigned CandsShown = 0;
13462 auto I = Cands.begin(), E = Cands.end();
13463 for (; I != E; ++I) {
13464 OverloadCandidate *Cand = *I;
13465
13466 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13467 ShowOverloads == Ovl_Best) {
13468 break;
13469 }
13470 ++CandsShown;
13471
13472 if (Cand->Function)
13473 NoteFunctionCandidate(S, Cand, Args.size(),
13474 Kind == CSK_AddressOfOverloadSet, DestAS);
13475 else if (Cand->IsSurrogate)
13476 NoteSurrogateCandidate(S, Cand);
13477 else {
13478 assert(Cand->Viable &&
13479 "Non-viable built-in candidates are not added to Cands.");
13480 // Generally we only see ambiguities including viable builtin
13481 // operators if overload resolution got screwed up by an
13482 // ambiguous user-defined conversion.
13483 //
13484 // FIXME: It's quite possible for different conversions to see
13485 // different ambiguities, though.
13486 if (!ReportedAmbiguousConversions) {
13487 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13488 ReportedAmbiguousConversions = true;
13489 }
13490
13491 // If this is a viable builtin, print it.
13492 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13493 }
13494 }
13495
13496 // Inform S.Diags that we've shown an overload set with N elements. This may
13497 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13498 S.Diags.overloadCandidatesShown(CandsShown);
13499
13500 if (I != E) {
13501 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13502 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13503 }
13504}
13505
13506static SourceLocation
13508 return Cand->Specialization ? Cand->Specialization->getLocation()
13509 : SourceLocation();
13510}
13511
13512namespace {
13513struct CompareTemplateSpecCandidatesForDisplay {
13514 Sema &S;
13515 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13516
13517 bool operator()(const TemplateSpecCandidate *L,
13518 const TemplateSpecCandidate *R) {
13519 // Fast-path this check.
13520 if (L == R)
13521 return false;
13522
13523 // Assuming that both candidates are not matches...
13524
13525 // Sort by the ranking of deduction failures.
13526 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13528 RankDeductionFailure(R->DeductionFailure);
13529
13530 // Sort everything else by location.
13531 SourceLocation LLoc = GetLocationForCandidate(L);
13532 SourceLocation RLoc = GetLocationForCandidate(R);
13533
13534 // Put candidates without locations (e.g. builtins) at the end.
13535 if (LLoc.isInvalid())
13536 return false;
13537 if (RLoc.isInvalid())
13538 return true;
13539
13540 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13541 }
13542};
13543}
13544
13545/// Diagnose a template argument deduction failure.
13546/// We are treating these failures as overload failures due to bad
13547/// deductions.
13549 bool ForTakingAddress) {
13551 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13552}
13553
13554void TemplateSpecCandidateSet::destroyCandidates() {
13555 for (iterator i = begin(), e = end(); i != e; ++i) {
13556 i->DeductionFailure.Destroy();
13557 }
13558}
13559
13561 destroyCandidates();
13562 Candidates.clear();
13563}
13564
13565/// NoteCandidates - When no template specialization match is found, prints
13566/// diagnostic messages containing the non-matching specializations that form
13567/// the candidate set.
13568/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13569/// OCD == OCD_AllCandidates and Cand->Viable == false.
13571 // Sort the candidates by position (assuming no candidate is a match).
13572 // Sorting directly would be prohibitive, so we make a set of pointers
13573 // and sort those.
13575 Cands.reserve(size());
13576 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13577 if (Cand->Specialization)
13578 Cands.push_back(Cand);
13579 // Otherwise, this is a non-matching builtin candidate. We do not,
13580 // in general, want to list every possible builtin candidate.
13581 }
13582
13583 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13584
13585 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13586 // for generalization purposes (?).
13587 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13588
13590 unsigned CandsShown = 0;
13591 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13592 TemplateSpecCandidate *Cand = *I;
13593
13594 // Set an arbitrary limit on the number of candidates we'll spam
13595 // the user with. FIXME: This limit should depend on details of the
13596 // candidate list.
13597 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13598 break;
13599 ++CandsShown;
13600
13601 assert(Cand->Specialization &&
13602 "Non-matching built-in candidates are not added to Cands.");
13603 Cand->NoteDeductionFailure(S, ForTakingAddress);
13604 }
13605
13606 if (I != E)
13607 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13608}
13609
13610// [PossiblyAFunctionType] --> [Return]
13611// NonFunctionType --> NonFunctionType
13612// R (A) --> R(A)
13613// R (*)(A) --> R (A)
13614// R (&)(A) --> R (A)
13615// R (S::*)(A) --> R (A)
13617 QualType Ret = PossiblyAFunctionType;
13618 if (const PointerType *ToTypePtr =
13619 PossiblyAFunctionType->getAs<PointerType>())
13620 Ret = ToTypePtr->getPointeeType();
13621 else if (const ReferenceType *ToTypeRef =
13622 PossiblyAFunctionType->getAs<ReferenceType>())
13623 Ret = ToTypeRef->getPointeeType();
13624 else if (const MemberPointerType *MemTypePtr =
13625 PossiblyAFunctionType->getAs<MemberPointerType>())
13626 Ret = MemTypePtr->getPointeeType();
13627 Ret =
13628 Context.getCanonicalType(Ret).getUnqualifiedType();
13629 return Ret;
13630}
13631
13633 bool Complain = true) {
13634 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13635 S.DeduceReturnType(FD, Loc, Complain))
13636 return true;
13637
13638 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13639 if (S.getLangOpts().CPlusPlus17 &&
13640 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13641 !S.ResolveExceptionSpec(Loc, FPT))
13642 return true;
13643
13644 return false;
13645}
13646
13647namespace {
13648// A helper class to help with address of function resolution
13649// - allows us to avoid passing around all those ugly parameters
13650class AddressOfFunctionResolver {
13651 Sema& S;
13652 Expr* SourceExpr;
13653 const QualType& TargetType;
13654 QualType TargetFunctionType; // Extracted function type from target type
13655
13656 bool Complain;
13657 //DeclAccessPair& ResultFunctionAccessPair;
13658 ASTContext& Context;
13659
13660 bool TargetTypeIsNonStaticMemberFunction;
13661 bool FoundNonTemplateFunction;
13662 bool StaticMemberFunctionFromBoundPointer;
13663 bool HasComplained;
13664
13665 OverloadExpr::FindResult OvlExprInfo;
13666 OverloadExpr *OvlExpr;
13667 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13668 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13669 TemplateSpecCandidateSet FailedCandidates;
13670
13671public:
13672 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13673 const QualType &TargetType, bool Complain)
13674 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13675 Complain(Complain), Context(S.getASTContext()),
13676 TargetTypeIsNonStaticMemberFunction(
13677 !!TargetType->getAs<MemberPointerType>()),
13678 FoundNonTemplateFunction(false),
13679 StaticMemberFunctionFromBoundPointer(false),
13680 HasComplained(false),
13681 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13682 OvlExpr(OvlExprInfo.Expression),
13683 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13684 ExtractUnqualifiedFunctionTypeFromTargetType();
13685
13686 if (TargetFunctionType->isFunctionType()) {
13687 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13688 if (!UME->isImplicitAccess() &&
13690 StaticMemberFunctionFromBoundPointer = true;
13691 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13692 DeclAccessPair dap;
13693 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13694 OvlExpr, false, &dap)) {
13695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13696 if (!Method->isStatic()) {
13697 // If the target type is a non-function type and the function found
13698 // is a non-static member function, pretend as if that was the
13699 // target, it's the only possible type to end up with.
13700 TargetTypeIsNonStaticMemberFunction = true;
13701
13702 // And skip adding the function if its not in the proper form.
13703 // We'll diagnose this due to an empty set of functions.
13704 if (!OvlExprInfo.HasFormOfMemberPointer)
13705 return;
13706 }
13707
13708 Matches.push_back(std::make_pair(dap, Fn));
13709 }
13710 return;
13711 }
13712
13713 if (OvlExpr->hasExplicitTemplateArgs())
13714 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13715
13716 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13717 // C++ [over.over]p4:
13718 // If more than one function is selected, [...]
13719 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13720 if (FoundNonTemplateFunction) {
13721 EliminateAllTemplateMatches();
13722 EliminateLessPartialOrderingConstrainedMatches();
13723 } else
13724 EliminateAllExceptMostSpecializedTemplate();
13725 }
13726 }
13727
13728 if (S.getLangOpts().CUDA && Matches.size() > 1)
13729 EliminateSuboptimalCudaMatches();
13730 }
13731
13732 bool hasComplained() const { return HasComplained; }
13733
13734private:
13735 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13736 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13737 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13738 }
13739
13740 /// \return true if A is considered a better overload candidate for the
13741 /// desired type than B.
13742 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13743 // If A doesn't have exactly the correct type, we don't want to classify it
13744 // as "better" than anything else. This way, the user is required to
13745 // disambiguate for us if there are multiple candidates and no exact match.
13746 return candidateHasExactlyCorrectType(A) &&
13747 (!candidateHasExactlyCorrectType(B) ||
13748 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13749 }
13750
13751 /// \return true if we were able to eliminate all but one overload candidate,
13752 /// false otherwise.
13753 bool eliminiateSuboptimalOverloadCandidates() {
13754 // Same algorithm as overload resolution -- one pass to pick the "best",
13755 // another pass to be sure that nothing is better than the best.
13756 auto Best = Matches.begin();
13757 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13758 if (isBetterCandidate(I->second, Best->second))
13759 Best = I;
13760
13761 const FunctionDecl *BestFn = Best->second;
13762 auto IsBestOrInferiorToBest = [this, BestFn](
13763 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13764 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13765 };
13766
13767 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13768 // option, so we can potentially give the user a better error
13769 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13770 return false;
13771 Matches[0] = *Best;
13772 Matches.resize(1);
13773 return true;
13774 }
13775
13776 bool isTargetTypeAFunction() const {
13777 return TargetFunctionType->isFunctionType();
13778 }
13779
13780 // [ToType] [Return]
13781
13782 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13783 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13784 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13785 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13786 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13787 }
13788
13789 // return true if any matching specializations were found
13790 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13791 const DeclAccessPair& CurAccessFunPair) {
13792 if (CXXMethodDecl *Method
13793 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13794 // Skip non-static function templates when converting to pointer, and
13795 // static when converting to member pointer.
13796 bool CanConvertToFunctionPointer =
13797 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13798 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13799 return false;
13800 }
13801 else if (TargetTypeIsNonStaticMemberFunction)
13802 return false;
13803
13804 // C++ [over.over]p2:
13805 // If the name is a function template, template argument deduction is
13806 // done (14.8.2.2), and if the argument deduction succeeds, the
13807 // resulting template argument list is used to generate a single
13808 // function template specialization, which is added to the set of
13809 // overloaded functions considered.
13810 FunctionDecl *Specialization = nullptr;
13811 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13813 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13814 Specialization, Info, /*IsAddressOfFunction*/ true);
13815 Result != TemplateDeductionResult::Success) {
13816 // Make a note of the failed deduction for diagnostics.
13817 FailedCandidates.addCandidate()
13818 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13819 MakeDeductionFailureInfo(Context, Result, Info));
13820 return false;
13821 }
13822
13823 // Template argument deduction ensures that we have an exact match or
13824 // compatible pointer-to-function arguments that would be adjusted by ICS.
13825 // This function template specicalization works.
13827 Context.getCanonicalType(Specialization->getType()),
13828 Context.getCanonicalType(TargetFunctionType)));
13829
13831 return false;
13832
13833 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13834 return true;
13835 }
13836
13837 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13838 const DeclAccessPair& CurAccessFunPair) {
13839 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13840 // Skip non-static functions when converting to pointer, and static
13841 // when converting to member pointer.
13842 bool CanConvertToFunctionPointer =
13843 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13844 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13845 return false;
13846 }
13847 else if (TargetTypeIsNonStaticMemberFunction)
13848 return false;
13849
13850 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13851 if (S.getLangOpts().CUDA) {
13852 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13853 if (!(Caller && Caller->isImplicit()) &&
13854 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13855 return false;
13856 }
13857 if (FunDecl->isMultiVersion()) {
13858 const auto *TA = FunDecl->getAttr<TargetAttr>();
13859 if (TA && !TA->isDefaultVersion())
13860 return false;
13861 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13862 if (TVA && !TVA->isDefaultVersion())
13863 return false;
13864 }
13865
13866 // If any candidate has a placeholder return type, trigger its deduction
13867 // now.
13868 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13869 Complain)) {
13870 HasComplained |= Complain;
13871 return false;
13872 }
13873
13874 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13875 return false;
13876
13877 // If we're in C, we need to support types that aren't exactly identical.
13878 if (!S.getLangOpts().CPlusPlus ||
13879 candidateHasExactlyCorrectType(FunDecl)) {
13880 Matches.push_back(std::make_pair(
13881 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13882 FoundNonTemplateFunction = true;
13883 return true;
13884 }
13885 }
13886
13887 return false;
13888 }
13889
13890 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13891 bool Ret = false;
13892
13893 // If the overload expression doesn't have the form of a pointer to
13894 // member, don't try to convert it to a pointer-to-member type.
13895 if (IsInvalidFormOfPointerToMemberFunction())
13896 return false;
13897
13898 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13899 E = OvlExpr->decls_end();
13900 I != E; ++I) {
13901 // Look through any using declarations to find the underlying function.
13902 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13903
13904 // C++ [over.over]p3:
13905 // Non-member functions and static member functions match
13906 // targets of type "pointer-to-function" or "reference-to-function."
13907 // Nonstatic member functions match targets of
13908 // type "pointer-to-member-function."
13909 // Note that according to DR 247, the containing class does not matter.
13910 if (FunctionTemplateDecl *FunctionTemplate
13911 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13912 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13913 Ret = true;
13914 }
13915 // If we have explicit template arguments supplied, skip non-templates.
13916 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13917 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13918 Ret = true;
13919 }
13920 assert(Ret || Matches.empty());
13921 return Ret;
13922 }
13923
13924 void EliminateAllExceptMostSpecializedTemplate() {
13925 // [...] and any given function template specialization F1 is
13926 // eliminated if the set contains a second function template
13927 // specialization whose function template is more specialized
13928 // than the function template of F1 according to the partial
13929 // ordering rules of 14.5.5.2.
13930
13931 // The algorithm specified above is quadratic. We instead use a
13932 // two-pass algorithm (similar to the one used to identify the
13933 // best viable function in an overload set) that identifies the
13934 // best function template (if it exists).
13935
13936 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13937 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13938 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13939
13940 // TODO: It looks like FailedCandidates does not serve much purpose
13941 // here, since the no_viable diagnostic has index 0.
13942 UnresolvedSetIterator Result = S.getMostSpecialized(
13943 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13944 SourceExpr->getBeginLoc(), S.PDiag(),
13945 S.PDiag(diag::err_addr_ovl_ambiguous)
13946 << Matches[0].second->getDeclName(),
13947 S.PDiag(diag::note_ovl_candidate)
13948 << (unsigned)oc_function << (unsigned)ocs_described_template,
13949 Complain, TargetFunctionType);
13950
13951 if (Result != MatchesCopy.end()) {
13952 // Make it the first and only element
13953 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13954 Matches[0].second = cast<FunctionDecl>(*Result);
13955 Matches.resize(1);
13956 } else
13957 HasComplained |= Complain;
13958 }
13959
13960 void EliminateAllTemplateMatches() {
13961 // [...] any function template specializations in the set are
13962 // eliminated if the set also contains a non-template function, [...]
13963 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13964 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13965 ++I;
13966 else {
13967 Matches[I] = Matches[--N];
13968 Matches.resize(N);
13969 }
13970 }
13971 }
13972
13973 void EliminateLessPartialOrderingConstrainedMatches() {
13974 // C++ [over.over]p5:
13975 // [...] Any given non-template function F0 is eliminated if the set
13976 // contains a second non-template function that is more
13977 // partial-ordering-constrained than F0. [...]
13978 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13979 "Call EliminateAllTemplateMatches() first");
13980 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13981 Results.push_back(Matches[0]);
13982 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13983 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13984 FunctionDecl *F = getMorePartialOrderingConstrained(
13985 S, Matches[I].second, Results[0].second,
13986 /*IsFn1Reversed=*/false,
13987 /*IsFn2Reversed=*/false);
13988 if (!F) {
13989 Results.push_back(Matches[I]);
13990 continue;
13991 }
13992 if (F == Matches[I].second) {
13993 Results.clear();
13994 Results.push_back(Matches[I]);
13995 }
13996 }
13997 std::swap(Matches, Results);
13998 }
13999
14000 void EliminateSuboptimalCudaMatches() {
14001 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14002 Matches);
14003 }
14004
14005public:
14006 void ComplainNoMatchesFound() const {
14007 assert(Matches.empty());
14008 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14009 << OvlExpr->getName() << TargetFunctionType
14010 << OvlExpr->getSourceRange();
14011 if (FailedCandidates.empty())
14012 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14013 /*TakingAddress=*/true);
14014 else {
14015 // We have some deduction failure messages. Use them to diagnose
14016 // the function templates, and diagnose the non-template candidates
14017 // normally.
14018 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14019 IEnd = OvlExpr->decls_end();
14020 I != IEnd; ++I)
14021 if (FunctionDecl *Fun =
14022 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14024 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14025 /*TakingAddress=*/true);
14026 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14027 }
14028 }
14029
14030 bool IsInvalidFormOfPointerToMemberFunction() const {
14031 return TargetTypeIsNonStaticMemberFunction &&
14032 !OvlExprInfo.HasFormOfMemberPointer;
14033 }
14034
14035 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14036 // TODO: Should we condition this on whether any functions might
14037 // have matched, or is it more appropriate to do that in callers?
14038 // TODO: a fixit wouldn't hurt.
14039 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14040 << TargetType << OvlExpr->getSourceRange();
14041 }
14042
14043 bool IsStaticMemberFunctionFromBoundPointer() const {
14044 return StaticMemberFunctionFromBoundPointer;
14045 }
14046
14047 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14048 S.Diag(OvlExpr->getBeginLoc(),
14049 diag::err_invalid_form_pointer_member_function)
14050 << OvlExpr->getSourceRange();
14051 }
14052
14053 void ComplainOfInvalidConversion() const {
14054 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14055 << OvlExpr->getName() << TargetType;
14056 }
14057
14058 void ComplainMultipleMatchesFound() const {
14059 assert(Matches.size() > 1);
14060 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14061 << OvlExpr->getName() << OvlExpr->getSourceRange();
14062 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14063 /*TakingAddress=*/true);
14064 }
14065
14066 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14067
14068 int getNumMatches() const { return Matches.size(); }
14069
14070 FunctionDecl* getMatchingFunctionDecl() const {
14071 if (Matches.size() != 1) return nullptr;
14072 return Matches[0].second;
14073 }
14074
14075 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14076 if (Matches.size() != 1) return nullptr;
14077 return &Matches[0].first;
14078 }
14079};
14080}
14081
14082FunctionDecl *
14084 QualType TargetType,
14085 bool Complain,
14086 DeclAccessPair &FoundResult,
14087 bool *pHadMultipleCandidates) {
14088 assert(AddressOfExpr->getType() == Context.OverloadTy);
14089
14090 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14091 Complain);
14092 int NumMatches = Resolver.getNumMatches();
14093 FunctionDecl *Fn = nullptr;
14094 bool ShouldComplain = Complain && !Resolver.hasComplained();
14095 if (NumMatches == 0 && ShouldComplain) {
14096 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14097 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14098 else
14099 Resolver.ComplainNoMatchesFound();
14100 }
14101 else if (NumMatches > 1 && ShouldComplain)
14102 Resolver.ComplainMultipleMatchesFound();
14103 else if (NumMatches == 1) {
14104 Fn = Resolver.getMatchingFunctionDecl();
14105 assert(Fn);
14106 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14107 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14108 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14109 if (Complain) {
14110 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14111 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14112 else
14113 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14114 }
14115 }
14116
14117 if (pHadMultipleCandidates)
14118 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14119 return Fn;
14120}
14121
14125 OverloadExpr *Ovl = R.Expression;
14126 bool IsResultAmbiguous = false;
14127 FunctionDecl *Result = nullptr;
14128 DeclAccessPair DAP;
14129 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14130
14131 // Return positive for better, negative for worse, 0 for equal preference.
14132 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14133 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14134 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14135 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14136 };
14137
14138 // Don't use the AddressOfResolver because we're specifically looking for
14139 // cases where we have one overload candidate that lacks
14140 // enable_if/pass_object_size/...
14141 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14142 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14143 if (!FD)
14144 return nullptr;
14145
14147 continue;
14148
14149 // If we found a better result, update Result.
14150 auto FoundBetter = [&]() {
14151 IsResultAmbiguous = false;
14152 DAP = I.getPair();
14153 Result = FD;
14154 };
14155
14156 // We have more than one result - see if it is more
14157 // partial-ordering-constrained than the previous one.
14158 if (Result) {
14159 // Check CUDA preference first. If the candidates have differennt CUDA
14160 // preference, choose the one with higher CUDA preference. Otherwise,
14161 // choose the one with more constraints.
14162 if (getLangOpts().CUDA) {
14163 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14164 // FD has different preference than Result.
14165 if (PreferenceByCUDA != 0) {
14166 // FD is more preferable than Result.
14167 if (PreferenceByCUDA > 0)
14168 FoundBetter();
14169 continue;
14170 }
14171 }
14172 // FD has the same CUDA preference than Result. Continue to check
14173 // constraints.
14174
14175 // C++ [over.over]p5:
14176 // [...] Any given non-template function F0 is eliminated if the set
14177 // contains a second non-template function that is more
14178 // partial-ordering-constrained than F0 [...]
14179 FunctionDecl *MoreConstrained =
14181 /*IsFn1Reversed=*/false,
14182 /*IsFn2Reversed=*/false);
14183 if (MoreConstrained != FD) {
14184 if (!MoreConstrained) {
14185 IsResultAmbiguous = true;
14186 AmbiguousDecls.push_back(FD);
14187 }
14188 continue;
14189 }
14190 // FD is more constrained - replace Result with it.
14191 }
14192 FoundBetter();
14193 }
14194
14195 if (IsResultAmbiguous)
14196 return nullptr;
14197
14198 if (Result) {
14199 // We skipped over some ambiguous declarations which might be ambiguous with
14200 // the selected result.
14201 for (FunctionDecl *Skipped : AmbiguousDecls) {
14202 // If skipped candidate has different CUDA preference than the result,
14203 // there is no ambiguity. Otherwise check whether they have different
14204 // constraints.
14205 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14206 continue;
14207 if (!getMoreConstrainedFunction(Skipped, Result))
14208 return nullptr;
14209 }
14210 Pair = DAP;
14211 }
14212 return Result;
14213}
14214
14216 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14217 Expr *E = SrcExpr.get();
14218 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14219
14220 DeclAccessPair DAP;
14222 if (!Found || Found->isCPUDispatchMultiVersion() ||
14223 Found->isCPUSpecificMultiVersion())
14224 return false;
14225
14226 // Emitting multiple diagnostics for a function that is both inaccessible and
14227 // unavailable is consistent with our behavior elsewhere. So, always check
14228 // for both.
14232 if (Res.isInvalid())
14233 return false;
14234 Expr *Fixed = Res.get();
14235 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14236 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14237 else
14238 SrcExpr = Fixed;
14239 return true;
14240}
14241
14243 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14244 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14245 // C++ [over.over]p1:
14246 // [...] [Note: any redundant set of parentheses surrounding the
14247 // overloaded function name is ignored (5.1). ]
14248 // C++ [over.over]p1:
14249 // [...] The overloaded function name can be preceded by the &
14250 // operator.
14251
14252 // If we didn't actually find any template-ids, we're done.
14253 if (!ovl->hasExplicitTemplateArgs())
14254 return nullptr;
14255
14256 TemplateArgumentListInfo ExplicitTemplateArgs;
14257 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14258
14259 // Look through all of the overloaded functions, searching for one
14260 // whose type matches exactly.
14261 FunctionDecl *Matched = nullptr;
14262 for (UnresolvedSetIterator I = ovl->decls_begin(),
14263 E = ovl->decls_end(); I != E; ++I) {
14264 // C++0x [temp.arg.explicit]p3:
14265 // [...] In contexts where deduction is done and fails, or in contexts
14266 // where deduction is not done, if a template argument list is
14267 // specified and it, along with any default template arguments,
14268 // identifies a single function template specialization, then the
14269 // template-id is an lvalue for the function template specialization.
14271 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14272 if (!FunctionTemplate)
14273 continue;
14274
14275 // C++ [over.over]p2:
14276 // If the name is a function template, template argument deduction is
14277 // done (14.8.2.2), and if the argument deduction succeeds, the
14278 // resulting template argument list is used to generate a single
14279 // function template specialization, which is added to the set of
14280 // overloaded functions considered.
14281 FunctionDecl *Specialization = nullptr;
14282 TemplateDeductionInfo Info(ovl->getNameLoc());
14284 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14285 /*IsAddressOfFunction*/ true);
14287 // Make a note of the failed deduction for diagnostics.
14288 if (FailedTSC)
14289 FailedTSC->addCandidate().set(
14290 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14292 continue;
14293 }
14294
14295 assert(Specialization && "no specialization and no error?");
14296
14297 // C++ [temp.deduct.call]p6:
14298 // [...] If all successful deductions yield the same deduced A, that
14299 // deduced A is the result of deduction; otherwise, the parameter is
14300 // treated as a non-deduced context.
14301 if (Matched) {
14302 if (ForTypeDeduction &&
14304 Specialization->getType()))
14305 continue;
14306 // Multiple matches; we can't resolve to a single declaration.
14307 if (Complain) {
14308 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14309 << ovl->getName();
14311 }
14312 return nullptr;
14313 }
14314
14315 Matched = Specialization;
14316 if (FoundResult) *FoundResult = I.getPair();
14317 }
14318
14319 if (Matched &&
14320 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14321 return nullptr;
14322
14323 return Matched;
14324}
14325
14327 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14328 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14329 unsigned DiagIDForComplaining) {
14330 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14331
14333
14334 DeclAccessPair found;
14335 ExprResult SingleFunctionExpression;
14337 ovl.Expression, /*complain*/ false, &found)) {
14338 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14339 SrcExpr = ExprError();
14340 return true;
14341 }
14342
14343 // It is only correct to resolve to an instance method if we're
14344 // resolving a form that's permitted to be a pointer to member.
14345 // Otherwise we'll end up making a bound member expression, which
14346 // is illegal in all the contexts we resolve like this.
14347 if (!ovl.HasFormOfMemberPointer &&
14348 isa<CXXMethodDecl>(fn) &&
14349 cast<CXXMethodDecl>(fn)->isInstance()) {
14350 if (!complain) return false;
14351
14352 Diag(ovl.Expression->getExprLoc(),
14353 diag::err_bound_member_function)
14354 << 0 << ovl.Expression->getSourceRange();
14355
14356 // TODO: I believe we only end up here if there's a mix of
14357 // static and non-static candidates (otherwise the expression
14358 // would have 'bound member' type, not 'overload' type).
14359 // Ideally we would note which candidate was chosen and why
14360 // the static candidates were rejected.
14361 SrcExpr = ExprError();
14362 return true;
14363 }
14364
14365 // Fix the expression to refer to 'fn'.
14366 SingleFunctionExpression =
14367 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14368
14369 // If desired, do function-to-pointer decay.
14370 if (doFunctionPointerConversion) {
14371 SingleFunctionExpression =
14372 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14373 if (SingleFunctionExpression.isInvalid()) {
14374 SrcExpr = ExprError();
14375 return true;
14376 }
14377 }
14378 }
14379
14380 if (!SingleFunctionExpression.isUsable()) {
14381 if (complain) {
14382 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14383 << ovl.Expression->getName()
14384 << DestTypeForComplaining
14385 << OpRangeForComplaining
14387 NoteAllOverloadCandidates(SrcExpr.get());
14388
14389 SrcExpr = ExprError();
14390 return true;
14391 }
14392
14393 return false;
14394 }
14395
14396 SrcExpr = SingleFunctionExpression;
14397 return true;
14398}
14399
14400/// Add a single candidate to the overload set.
14402 DeclAccessPair FoundDecl,
14403 TemplateArgumentListInfo *ExplicitTemplateArgs,
14404 ArrayRef<Expr *> Args,
14405 OverloadCandidateSet &CandidateSet,
14406 bool PartialOverloading,
14407 bool KnownValid) {
14408 NamedDecl *Callee = FoundDecl.getDecl();
14409 if (isa<UsingShadowDecl>(Callee))
14410 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14411
14412 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14413 if (ExplicitTemplateArgs) {
14414 assert(!KnownValid && "Explicit template arguments?");
14415 return;
14416 }
14417 // Prevent ill-formed function decls to be added as overload candidates.
14418 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14419 return;
14420
14421 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14422 /*SuppressUserConversions=*/false,
14423 PartialOverloading);
14424 return;
14425 }
14426
14427 if (FunctionTemplateDecl *FuncTemplate
14428 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14429 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14430 ExplicitTemplateArgs, Args, CandidateSet,
14431 /*SuppressUserConversions=*/false,
14432 PartialOverloading);
14433 return;
14434 }
14435
14436 assert(!KnownValid && "unhandled case in overloaded call candidate");
14437}
14438
14440 ArrayRef<Expr *> Args,
14441 OverloadCandidateSet &CandidateSet,
14442 bool PartialOverloading) {
14443
14444#ifndef NDEBUG
14445 // Verify that ArgumentDependentLookup is consistent with the rules
14446 // in C++0x [basic.lookup.argdep]p3:
14447 //
14448 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14449 // and let Y be the lookup set produced by argument dependent
14450 // lookup (defined as follows). If X contains
14451 //
14452 // -- a declaration of a class member, or
14453 //
14454 // -- a block-scope function declaration that is not a
14455 // using-declaration, or
14456 //
14457 // -- a declaration that is neither a function or a function
14458 // template
14459 //
14460 // then Y is empty.
14461
14462 if (ULE->requiresADL()) {
14464 E = ULE->decls_end(); I != E; ++I) {
14465 assert(!(*I)->getDeclContext()->isRecord());
14466 assert(isa<UsingShadowDecl>(*I) ||
14467 !(*I)->getDeclContext()->isFunctionOrMethod());
14468 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14469 }
14470 }
14471#endif
14472
14473 // It would be nice to avoid this copy.
14474 TemplateArgumentListInfo TABuffer;
14475 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14476 if (ULE->hasExplicitTemplateArgs()) {
14477 ULE->copyTemplateArgumentsInto(TABuffer);
14478 ExplicitTemplateArgs = &TABuffer;
14479 }
14480
14482 E = ULE->decls_end(); I != E; ++I)
14483 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14484 CandidateSet, PartialOverloading,
14485 /*KnownValid*/ true);
14486
14487 if (ULE->requiresADL())
14489 Args, ExplicitTemplateArgs,
14490 CandidateSet, PartialOverloading);
14491}
14492
14494 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14495 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14496 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14497 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14498 CandidateSet, false, /*KnownValid*/ false);
14499}
14500
14501/// Determine whether a declaration with the specified name could be moved into
14502/// a different namespace.
14504 switch (Name.getCXXOverloadedOperator()) {
14505 case OO_New: case OO_Array_New:
14506 case OO_Delete: case OO_Array_Delete:
14507 return false;
14508
14509 default:
14510 return true;
14511 }
14512}
14513
14514/// Attempt to recover from an ill-formed use of a non-dependent name in a
14515/// template, where the non-dependent name was declared after the template
14516/// was defined. This is common in code written for a compilers which do not
14517/// correctly implement two-stage name lookup.
14518///
14519/// Returns true if a viable candidate was found and a diagnostic was issued.
14521 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14523 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14524 CXXRecordDecl **FoundInClass = nullptr) {
14525 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14526 return false;
14527
14528 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14529 if (DC->isTransparentContext())
14530 continue;
14531
14532 SemaRef.LookupQualifiedName(R, DC);
14533
14534 if (!R.empty()) {
14535 R.suppressDiagnostics();
14536
14537 OverloadCandidateSet Candidates(FnLoc, CSK);
14538 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14539 Candidates);
14540
14543 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14544
14545 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14546 // We either found non-function declarations or a best viable function
14547 // at class scope. A class-scope lookup result disables ADL. Don't
14548 // look past this, but let the caller know that we found something that
14549 // either is, or might be, usable in this class.
14550 if (FoundInClass) {
14551 *FoundInClass = RD;
14552 if (OR == OR_Success) {
14553 R.clear();
14554 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14555 R.resolveKind();
14556 }
14557 }
14558 return false;
14559 }
14560
14561 if (OR != OR_Success) {
14562 // There wasn't a unique best function or function template.
14563 return false;
14564 }
14565
14566 // Find the namespaces where ADL would have looked, and suggest
14567 // declaring the function there instead.
14568 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14569 Sema::AssociatedClassSet AssociatedClasses;
14570 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14571 AssociatedNamespaces,
14572 AssociatedClasses);
14573 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14574 if (canBeDeclaredInNamespace(R.getLookupName())) {
14575 DeclContext *Std = SemaRef.getStdNamespace();
14576 for (Sema::AssociatedNamespaceSet::iterator
14577 it = AssociatedNamespaces.begin(),
14578 end = AssociatedNamespaces.end(); it != end; ++it) {
14579 // Never suggest declaring a function within namespace 'std'.
14580 if (Std && Std->Encloses(*it))
14581 continue;
14582
14583 // Never suggest declaring a function within a namespace with a
14584 // reserved name, like __gnu_cxx.
14585 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14586 if (NS &&
14587 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14588 continue;
14589
14590 SuggestedNamespaces.insert(*it);
14591 }
14592 }
14593
14594 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14595 << R.getLookupName();
14596 if (SuggestedNamespaces.empty()) {
14597 SemaRef.Diag(Best->Function->getLocation(),
14598 diag::note_not_found_by_two_phase_lookup)
14599 << R.getLookupName() << 0;
14600 } else if (SuggestedNamespaces.size() == 1) {
14601 SemaRef.Diag(Best->Function->getLocation(),
14602 diag::note_not_found_by_two_phase_lookup)
14603 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14604 } else {
14605 // FIXME: It would be useful to list the associated namespaces here,
14606 // but the diagnostics infrastructure doesn't provide a way to produce
14607 // a localized representation of a list of items.
14608 SemaRef.Diag(Best->Function->getLocation(),
14609 diag::note_not_found_by_two_phase_lookup)
14610 << R.getLookupName() << 2;
14611 }
14612
14613 // Try to recover by calling this function.
14614 return true;
14615 }
14616
14617 R.clear();
14618 }
14619
14620 return false;
14621}
14622
14623/// Attempt to recover from ill-formed use of a non-dependent operator in a
14624/// template, where the non-dependent operator was declared after the template
14625/// was defined.
14626///
14627/// Returns true if a viable candidate was found and a diagnostic was issued.
14628static bool
14630 SourceLocation OpLoc,
14631 ArrayRef<Expr *> Args) {
14632 DeclarationName OpName =
14634 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14635 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14637 /*ExplicitTemplateArgs=*/nullptr, Args);
14638}
14639
14640namespace {
14641class BuildRecoveryCallExprRAII {
14642 Sema &SemaRef;
14643 Sema::SatisfactionStackResetRAII SatStack;
14644
14645public:
14646 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14647 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14648 SemaRef.IsBuildingRecoveryCallExpr = true;
14649 }
14650
14651 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14652};
14653}
14654
14655/// Attempts to recover from a call where no functions were found.
14656///
14657/// This function will do one of three things:
14658/// * Diagnose, recover, and return a recovery expression.
14659/// * Diagnose, fail to recover, and return ExprError().
14660/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14661/// expected to diagnose as appropriate.
14662static ExprResult
14665 SourceLocation LParenLoc,
14667 SourceLocation RParenLoc,
14668 bool EmptyLookup, bool AllowTypoCorrection) {
14669 // Do not try to recover if it is already building a recovery call.
14670 // This stops infinite loops for template instantiations like
14671 //
14672 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14673 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14674 if (SemaRef.IsBuildingRecoveryCallExpr)
14675 return ExprResult();
14676 BuildRecoveryCallExprRAII RCE(SemaRef);
14677
14678 CXXScopeSpec SS;
14679 SS.Adopt(ULE->getQualifierLoc());
14680 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14681
14682 TemplateArgumentListInfo TABuffer;
14683 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14684 if (ULE->hasExplicitTemplateArgs()) {
14685 ULE->copyTemplateArgumentsInto(TABuffer);
14686 ExplicitTemplateArgs = &TABuffer;
14687 }
14688
14689 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14691 CXXRecordDecl *FoundInClass = nullptr;
14692 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14694 ExplicitTemplateArgs, Args, &FoundInClass)) {
14695 // OK, diagnosed a two-phase lookup issue.
14696 } else if (EmptyLookup) {
14697 // Try to recover from an empty lookup with typo correction.
14698 R.clear();
14699 NoTypoCorrectionCCC NoTypoValidator{};
14700 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14701 ExplicitTemplateArgs != nullptr,
14702 dyn_cast<MemberExpr>(Fn));
14703 CorrectionCandidateCallback &Validator =
14704 AllowTypoCorrection
14705 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14706 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14707 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14708 Args))
14709 return ExprError();
14710 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14711 // We found a usable declaration of the name in a dependent base of some
14712 // enclosing class.
14713 // FIXME: We should also explain why the candidates found by name lookup
14714 // were not viable.
14715 if (SemaRef.DiagnoseDependentMemberLookup(R))
14716 return ExprError();
14717 } else {
14718 // We had viable candidates and couldn't recover; let the caller diagnose
14719 // this.
14720 return ExprResult();
14721 }
14722
14723 // If we get here, we should have issued a diagnostic and formed a recovery
14724 // lookup result.
14725 assert(!R.empty() && "lookup results empty despite recovery");
14726
14727 // If recovery created an ambiguity, just bail out.
14728 if (R.isAmbiguous()) {
14729 R.suppressDiagnostics();
14730 return ExprError();
14731 }
14732
14733 // Build an implicit member call if appropriate. Just drop the
14734 // casts and such from the call, we don't really care.
14735 ExprResult NewFn = ExprError();
14736 if ((*R.begin())->isCXXClassMember())
14737 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14738 ExplicitTemplateArgs, S);
14739 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14740 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14741 ExplicitTemplateArgs);
14742 else
14743 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14744
14745 if (NewFn.isInvalid())
14746 return ExprError();
14747
14748 // This shouldn't cause an infinite loop because we're giving it
14749 // an expression with viable lookup results, which should never
14750 // end up here.
14751 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14752 MultiExprArg(Args.data(), Args.size()),
14753 RParenLoc);
14754}
14755
14758 MultiExprArg Args,
14759 SourceLocation RParenLoc,
14760 OverloadCandidateSet *CandidateSet,
14761 ExprResult *Result) {
14762#ifndef NDEBUG
14763 if (ULE->requiresADL()) {
14764 // To do ADL, we must have found an unqualified name.
14765 assert(!ULE->getQualifier() && "qualified name with ADL");
14766
14767 // We don't perform ADL for implicit declarations of builtins.
14768 // Verify that this was correctly set up.
14769 FunctionDecl *F;
14770 if (ULE->decls_begin() != ULE->decls_end() &&
14771 ULE->decls_begin() + 1 == ULE->decls_end() &&
14772 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14773 F->getBuiltinID() && F->isImplicit())
14774 llvm_unreachable("performing ADL for builtin");
14775
14776 // We don't perform ADL in C.
14777 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14778 }
14779#endif
14780
14781 UnbridgedCastsSet UnbridgedCasts;
14782 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14783 *Result = ExprError();
14784 return true;
14785 }
14786
14787 // Add the functions denoted by the callee to the set of candidate
14788 // functions, including those from argument-dependent lookup.
14789 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14790
14791 if (getLangOpts().MSVCCompat &&
14792 CurContext->isDependentContext() && !isSFINAEContext() &&
14794
14796 if (CandidateSet->empty() ||
14797 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14799 // In Microsoft mode, if we are inside a template class member function
14800 // then create a type dependent CallExpr. The goal is to postpone name
14801 // lookup to instantiation time to be able to search into type dependent
14802 // base classes.
14803 CallExpr *CE =
14804 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14805 RParenLoc, CurFPFeatureOverrides());
14807 *Result = CE;
14808 return true;
14809 }
14810 }
14811
14812 if (CandidateSet->empty())
14813 return false;
14814
14815 UnbridgedCasts.restore();
14816 return false;
14817}
14818
14819// Guess at what the return type for an unresolvable overload should be.
14822 std::optional<QualType> Result;
14823 // Adjust Type after seeing a candidate.
14824 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14825 if (!Candidate.Function)
14826 return;
14827 if (Candidate.Function->isInvalidDecl())
14828 return;
14829 QualType T = Candidate.Function->getReturnType();
14830 if (T.isNull())
14831 return;
14832 if (!Result)
14833 Result = T;
14834 else if (Result != T)
14835 Result = QualType();
14836 };
14837
14838 // Look for an unambiguous type from a progressively larger subset.
14839 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14840 //
14841 // First, consider only the best candidate.
14842 if (Best && *Best != CS.end())
14843 ConsiderCandidate(**Best);
14844 // Next, consider only viable candidates.
14845 if (!Result)
14846 for (const auto &C : CS)
14847 if (C.Viable)
14848 ConsiderCandidate(C);
14849 // Finally, consider all candidates.
14850 if (!Result)
14851 for (const auto &C : CS)
14852 ConsiderCandidate(C);
14853
14854 if (!Result)
14855 return QualType();
14856 auto Value = *Result;
14857 if (Value.isNull() || Value->isUndeducedType())
14858 return QualType();
14859 return Value;
14860}
14861
14862/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14863/// the completed call expression. If overload resolution fails, emits
14864/// diagnostics and returns ExprError()
14867 SourceLocation LParenLoc,
14868 MultiExprArg Args,
14869 SourceLocation RParenLoc,
14870 Expr *ExecConfig,
14871 OverloadCandidateSet *CandidateSet,
14873 OverloadingResult OverloadResult,
14874 bool AllowTypoCorrection) {
14875 switch (OverloadResult) {
14876 case OR_Success: {
14877 FunctionDecl *FDecl = (*Best)->Function;
14878 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14879 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14880 return ExprError();
14881 ExprResult Res =
14882 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14883 if (Res.isInvalid())
14884 return ExprError();
14885 return SemaRef.BuildResolvedCallExpr(
14886 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14887 /*IsExecConfig=*/false,
14888 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14889 }
14890
14891 case OR_No_Viable_Function: {
14892 if (*Best != CandidateSet->end() &&
14893 CandidateSet->getKind() ==
14895 if (CXXMethodDecl *M =
14896 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14898 CandidateSet->NoteCandidates(
14900 Fn->getBeginLoc(),
14901 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14902 SemaRef, OCD_AmbiguousCandidates, Args);
14903 return ExprError();
14904 }
14905 }
14906
14907 // Try to recover by looking for viable functions which the user might
14908 // have meant to call.
14909 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14910 Args, RParenLoc,
14911 CandidateSet->empty(),
14912 AllowTypoCorrection);
14913 if (Recovery.isInvalid() || Recovery.isUsable())
14914 return Recovery;
14915
14916 // If the user passes in a function that we can't take the address of, we
14917 // generally end up emitting really bad error messages. Here, we attempt to
14918 // emit better ones.
14919 for (const Expr *Arg : Args) {
14920 if (!Arg->getType()->isFunctionType())
14921 continue;
14922 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14923 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14924 if (FD &&
14925 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14926 Arg->getExprLoc()))
14927 return ExprError();
14928 }
14929 }
14930
14931 CandidateSet->NoteCandidates(
14933 Fn->getBeginLoc(),
14934 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14935 << ULE->getName() << Fn->getSourceRange()),
14936 SemaRef, OCD_AllCandidates, Args);
14937 break;
14938 }
14939
14940 case OR_Ambiguous:
14941 CandidateSet->NoteCandidates(
14942 PartialDiagnosticAt(Fn->getBeginLoc(),
14943 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14944 << ULE->getName() << Fn->getSourceRange()),
14945 SemaRef, OCD_AmbiguousCandidates, Args);
14946 break;
14947
14948 case OR_Deleted: {
14949 FunctionDecl *FDecl = (*Best)->Function;
14950 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14951 Fn->getSourceRange(), ULE->getName(),
14952 *CandidateSet, FDecl, Args);
14953
14954 // We emitted an error for the unavailable/deleted function call but keep
14955 // the call in the AST.
14956 ExprResult Res =
14957 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14958 if (Res.isInvalid())
14959 return ExprError();
14960 return SemaRef.BuildResolvedCallExpr(
14961 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14962 /*IsExecConfig=*/false,
14963 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14964 }
14965 }
14966
14967 // Overload resolution failed, try to recover.
14968 SmallVector<Expr *, 8> SubExprs = {Fn};
14969 SubExprs.append(Args.begin(), Args.end());
14970 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14971 chooseRecoveryType(*CandidateSet, Best));
14972}
14973
14976 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14977 if (I->Viable &&
14978 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14979 I->Viable = false;
14980 I->FailureKind = ovl_fail_addr_not_available;
14981 }
14982 }
14983}
14984
14987 SourceLocation LParenLoc,
14988 MultiExprArg Args,
14989 SourceLocation RParenLoc,
14990 Expr *ExecConfig,
14991 bool AllowTypoCorrection,
14992 bool CalleesAddressIsTaken) {
14993
14997
14998 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14999 ExprResult result;
15000
15001 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15002 &result))
15003 return result;
15004
15005 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15006 // functions that aren't addressible are considered unviable.
15007 if (CalleesAddressIsTaken)
15008 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15009
15011 OverloadingResult OverloadResult =
15012 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15013
15014 // [C++23][over.call.func]
15015 // if overload resolution selects a non-static member function,
15016 // the call is ill-formed;
15018 Best != CandidateSet.end()) {
15019 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15020 M && M->isImplicitObjectMemberFunction()) {
15021 OverloadResult = OR_No_Viable_Function;
15022 }
15023 }
15024
15025 // Model the case with a call to a templated function whose definition
15026 // encloses the call and whose return type contains a placeholder type as if
15027 // the UnresolvedLookupExpr was type-dependent.
15028 if (OverloadResult == OR_Success) {
15029 const FunctionDecl *FDecl = Best->Function;
15030 if (LangOpts.CUDA)
15031 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15032 if (FDecl && FDecl->isTemplateInstantiation() &&
15033 FDecl->getReturnType()->isUndeducedType()) {
15034
15035 // Creating dependent CallExpr is not okay if the enclosing context itself
15036 // is not dependent. This situation notably arises if a non-dependent
15037 // member function calls the later-defined overloaded static function.
15038 //
15039 // For example, in
15040 // class A {
15041 // void c() { callee(1); }
15042 // static auto callee(auto x) { }
15043 // };
15044 //
15045 // Here callee(1) is unresolved at the call site, but is not inside a
15046 // dependent context. There will be no further attempt to resolve this
15047 // call if it is made dependent.
15048
15049 if (const auto *TP =
15050 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15051 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15052 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15053 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15054 }
15055 }
15056 }
15057
15058 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15059 ExecConfig, &CandidateSet, &Best,
15060 OverloadResult, AllowTypoCorrection);
15061}
15062
15066 const UnresolvedSetImpl &Fns,
15067 bool PerformADL) {
15069 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15070 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15071}
15072
15075 bool HadMultipleCandidates) {
15076 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15077 // the FoundDecl as it impedes TransformMemberExpr.
15078 // We go a bit further here: if there's no difference in UnderlyingDecl,
15079 // then using FoundDecl vs Method shouldn't make a difference either.
15080 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15081 FoundDecl = Method;
15082 // Convert the expression to match the conversion function's implicit object
15083 // parameter.
15084 ExprResult Exp;
15085 if (Method->isExplicitObjectMemberFunction())
15087 else
15089 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15090 if (Exp.isInvalid())
15091 return true;
15092
15093 if (Method->getParent()->isLambda() &&
15094 Method->getConversionType()->isBlockPointerType()) {
15095 // This is a lambda conversion to block pointer; check if the argument
15096 // was a LambdaExpr.
15097 Expr *SubE = E;
15098 auto *CE = dyn_cast<CastExpr>(SubE);
15099 if (CE && CE->getCastKind() == CK_NoOp)
15100 SubE = CE->getSubExpr();
15101 SubE = SubE->IgnoreParens();
15102 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15103 SubE = BE->getSubExpr();
15104 if (isa<LambdaExpr>(SubE)) {
15105 // For the conversion to block pointer on a lambda expression, we
15106 // construct a special BlockLiteral instead; this doesn't really make
15107 // a difference in ARC, but outside of ARC the resulting block literal
15108 // follows the normal lifetime rules for block literals instead of being
15109 // autoreleased.
15113 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15115
15116 // FIXME: This note should be produced by a CodeSynthesisContext.
15117 if (BlockExp.isInvalid())
15118 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15119 return BlockExp;
15120 }
15121 }
15122 CallExpr *CE;
15123 QualType ResultType = Method->getReturnType();
15125 ResultType = ResultType.getNonLValueExprType(Context);
15126 if (Method->isExplicitObjectMemberFunction()) {
15127 ExprResult FnExpr =
15128 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15129 HadMultipleCandidates, E->getBeginLoc());
15130 if (FnExpr.isInvalid())
15131 return ExprError();
15132 Expr *ObjectParam = Exp.get();
15133 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15134 ResultType, VK, Exp.get()->getEndLoc(),
15136 CE->setUsesMemberSyntax(true);
15137 } else {
15138 MemberExpr *ME =
15139 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15141 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15142 HadMultipleCandidates, DeclarationNameInfo(),
15143 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15144
15145 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15146 Exp.get()->getEndLoc(),
15148 }
15149
15150 if (CheckFunctionCall(Method, CE,
15151 Method->getType()->castAs<FunctionProtoType>()))
15152 return ExprError();
15153
15155}
15156
15159 const UnresolvedSetImpl &Fns,
15160 Expr *Input, bool PerformADL) {
15162 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15163 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15164 // TODO: provide better source location info.
15165 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15166
15167 if (checkPlaceholderForOverload(*this, Input))
15168 return ExprError();
15169
15170 Expr *Args[2] = { Input, nullptr };
15171 unsigned NumArgs = 1;
15172
15173 // For post-increment and post-decrement, add the implicit '0' as
15174 // the second argument, so that we know this is a post-increment or
15175 // post-decrement.
15176 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15177 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15178 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15179 SourceLocation());
15180 NumArgs = 2;
15181 }
15182
15183 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15184
15185 if (Input->isTypeDependent()) {
15187 // [C++26][expr.unary.op][expr.pre.incr]
15188 // The * operator yields an lvalue of type
15189 // The pre/post increment operators yied an lvalue.
15190 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15191 VK = VK_LValue;
15192
15193 if (Fns.empty())
15194 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15195 OK_Ordinary, OpLoc, false,
15197
15198 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15200 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15201 if (Fn.isInvalid())
15202 return ExprError();
15203 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15204 Context.DependentTy, VK_PRValue, OpLoc,
15206 }
15207
15208 // Build an empty overload set.
15210
15211 // Add the candidates from the given function set.
15212 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15213
15214 // Add operator candidates that are member functions.
15215 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15216
15217 // Add candidates from ADL.
15218 if (PerformADL) {
15219 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15220 /*ExplicitTemplateArgs*/nullptr,
15221 CandidateSet);
15222 }
15223
15224 // Add builtin operator candidates.
15225 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15226
15227 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15228
15229 // Perform overload resolution.
15231 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15232 case OR_Success: {
15233 // We found a built-in operator or an overloaded operator.
15234 FunctionDecl *FnDecl = Best->Function;
15235
15236 if (FnDecl) {
15237 Expr *Base = nullptr;
15238 // We matched an overloaded operator. Build a call to that
15239 // operator.
15240
15241 // Convert the arguments.
15242 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15243 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15244
15245 ExprResult InputInit;
15246 if (Method->isExplicitObjectMemberFunction())
15247 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15248 else
15250 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15251 if (InputInit.isInvalid())
15252 return ExprError();
15253 Base = Input = InputInit.get();
15254 } else {
15255 // Convert the arguments.
15256 ExprResult InputInit
15258 Context,
15259 FnDecl->getParamDecl(0)),
15261 Input);
15262 if (InputInit.isInvalid())
15263 return ExprError();
15264 Input = InputInit.get();
15265 }
15266
15267 // Build the actual expression node.
15268 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15269 Base, HadMultipleCandidates,
15270 OpLoc);
15271 if (FnExpr.isInvalid())
15272 return ExprError();
15273
15274 // Determine the result type.
15275 QualType ResultTy = FnDecl->getReturnType();
15277 ResultTy = ResultTy.getNonLValueExprType(Context);
15278
15279 Args[0] = Input;
15281 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15283 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15284
15285 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15286 return ExprError();
15287
15288 if (CheckFunctionCall(FnDecl, TheCall,
15289 FnDecl->getType()->castAs<FunctionProtoType>()))
15290 return ExprError();
15291 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15292 } else {
15293 // We matched a built-in operator. Convert the arguments, then
15294 // break out so that we will build the appropriate built-in
15295 // operator node.
15297 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15300 if (InputRes.isInvalid())
15301 return ExprError();
15302 Input = InputRes.get();
15303 break;
15304 }
15305 }
15306
15308 // This is an erroneous use of an operator which can be overloaded by
15309 // a non-member function. Check for non-member operators which were
15310 // defined too late to be candidates.
15311 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15312 // FIXME: Recover by calling the found function.
15313 return ExprError();
15314
15315 // No viable function; fall through to handling this as a
15316 // built-in operator, which will produce an error message for us.
15317 break;
15318
15319 case OR_Ambiguous:
15320 CandidateSet.NoteCandidates(
15321 PartialDiagnosticAt(OpLoc,
15322 PDiag(diag::err_ovl_ambiguous_oper_unary)
15324 << Input->getType() << Input->getSourceRange()),
15325 *this, OCD_AmbiguousCandidates, ArgsArray,
15326 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15327 return ExprError();
15328
15329 case OR_Deleted: {
15330 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15331 // object whose method was called. Later in NoteCandidates size of ArgsArray
15332 // is passed further and it eventually ends up compared to number of
15333 // function candidate parameters which never includes the object parameter,
15334 // so slice ArgsArray to make sure apples are compared to apples.
15335 StringLiteral *Msg = Best->Function->getDeletedMessage();
15336 CandidateSet.NoteCandidates(
15337 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15339 << (Msg != nullptr)
15340 << (Msg ? Msg->getString() : StringRef())
15341 << Input->getSourceRange()),
15342 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15343 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15344 return ExprError();
15345 }
15346 }
15347
15348 // Either we found no viable overloaded operator or we matched a
15349 // built-in operator. In either case, fall through to trying to
15350 // build a built-in operation.
15351 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15352}
15353
15356 const UnresolvedSetImpl &Fns,
15357 ArrayRef<Expr *> Args, bool PerformADL) {
15358 SourceLocation OpLoc = CandidateSet.getLocation();
15359
15360 OverloadedOperatorKind ExtraOp =
15363 : OO_None;
15364
15365 // Add the candidates from the given function set. This also adds the
15366 // rewritten candidates using these functions if necessary.
15367 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15368
15369 // As template candidates are not deduced immediately,
15370 // persist the array in the overload set.
15371 ArrayRef<Expr *> ReversedArgs;
15372 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15373 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15374 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15375
15376 // Add operator candidates that are member functions.
15377 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15378 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15379 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15381
15382 // In C++20, also add any rewritten member candidates.
15383 if (ExtraOp) {
15384 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15385 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15386 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15388 }
15389
15390 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15391 // performed for an assignment operator (nor for operator[] nor operator->,
15392 // which don't get here).
15393 if (Op != OO_Equal && PerformADL) {
15394 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15395 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15396 /*ExplicitTemplateArgs*/ nullptr,
15397 CandidateSet);
15398 if (ExtraOp) {
15399 DeclarationName ExtraOpName =
15400 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15401 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15402 /*ExplicitTemplateArgs*/ nullptr,
15403 CandidateSet);
15404 }
15405 }
15406
15407 // Add builtin operator candidates.
15408 //
15409 // FIXME: We don't add any rewritten candidates here. This is strictly
15410 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15411 // resulting in our selecting a rewritten builtin candidate. For example:
15412 //
15413 // enum class E { e };
15414 // bool operator!=(E, E) requires false;
15415 // bool k = E::e != E::e;
15416 //
15417 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15418 // it seems unreasonable to consider rewritten builtin candidates. A core
15419 // issue has been filed proposing to removed this requirement.
15420 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15421}
15422
15425 const UnresolvedSetImpl &Fns, Expr *LHS,
15426 Expr *RHS, bool PerformADL,
15427 bool AllowRewrittenCandidates,
15428 FunctionDecl *DefaultedFn) {
15429 Expr *Args[2] = { LHS, RHS };
15430 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15431
15432 if (!getLangOpts().CPlusPlus20)
15433 AllowRewrittenCandidates = false;
15434
15436
15437 // If either side is type-dependent, create an appropriate dependent
15438 // expression.
15439 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15440 if (Fns.empty()) {
15441 // If there are no functions to store, just build a dependent
15442 // BinaryOperator or CompoundAssignment.
15445 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15446 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15447 Context.DependentTy);
15449 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15451 }
15452
15453 // FIXME: save results of ADL from here?
15454 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15455 // TODO: provide better source location info in DNLoc component.
15456 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15457 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15459 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15460 if (Fn.isInvalid())
15461 return ExprError();
15462 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15463 Context.DependentTy, VK_PRValue, OpLoc,
15465 }
15466
15467 // If this is the .* operator, which is not overloadable, just
15468 // create a built-in binary operator.
15469 if (Opc == BO_PtrMemD) {
15470 auto CheckPlaceholder = [&](Expr *&Arg) {
15472 if (Res.isUsable())
15473 Arg = Res.get();
15474 return !Res.isUsable();
15475 };
15476
15477 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15478 // expression that contains placeholders (in either the LHS or RHS).
15479 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15480 return ExprError();
15481 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15482 }
15483
15484 // Always do placeholder-like conversions on the RHS.
15485 if (checkPlaceholderForOverload(*this, Args[1]))
15486 return ExprError();
15487
15488 // Do placeholder-like conversion on the LHS; note that we should
15489 // not get here with a PseudoObject LHS.
15490 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15491 if (checkPlaceholderForOverload(*this, Args[0]))
15492 return ExprError();
15493
15494 // If this is the assignment operator, we only perform overload resolution
15495 // if the left-hand side is a class or enumeration type. This is actually
15496 // a hack. The standard requires that we do overload resolution between the
15497 // various built-in candidates, but as DR507 points out, this can lead to
15498 // problems. So we do it this way, which pretty much follows what GCC does.
15499 // Note that we go the traditional code path for compound assignment forms.
15500 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15501 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15502
15503 // Build the overload set.
15506 Op, OpLoc, AllowRewrittenCandidates));
15507 if (DefaultedFn)
15508 CandidateSet.exclude(DefaultedFn);
15509 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15510
15511 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15512
15513 // Perform overload resolution.
15515 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15516 case OR_Success: {
15517 // We found a built-in operator or an overloaded operator.
15518 FunctionDecl *FnDecl = Best->Function;
15519
15520 bool IsReversed = Best->isReversed();
15521 if (IsReversed)
15522 std::swap(Args[0], Args[1]);
15523
15524 if (FnDecl) {
15525
15526 if (FnDecl->isInvalidDecl())
15527 return ExprError();
15528
15529 Expr *Base = nullptr;
15530 // We matched an overloaded operator. Build a call to that
15531 // operator.
15532
15533 OverloadedOperatorKind ChosenOp =
15535
15536 // C++2a [over.match.oper]p9:
15537 // If a rewritten operator== candidate is selected by overload
15538 // resolution for an operator@, its return type shall be cv bool
15539 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15540 !FnDecl->getReturnType()->isBooleanType()) {
15541 bool IsExtension =
15543 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15544 : diag::err_ovl_rewrite_equalequal_not_bool)
15545 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15546 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15547 Diag(FnDecl->getLocation(), diag::note_declared_at);
15548 if (!IsExtension)
15549 return ExprError();
15550 }
15551
15552 if (AllowRewrittenCandidates && !IsReversed &&
15553 CandidateSet.getRewriteInfo().isReversible()) {
15554 // We could have reversed this operator, but didn't. Check if some
15555 // reversed form was a viable candidate, and if so, if it had a
15556 // better conversion for either parameter. If so, this call is
15557 // formally ambiguous, and allowing it is an extension.
15559 for (OverloadCandidate &Cand : CandidateSet) {
15560 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15561 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15562 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15564 *this, OpLoc, Cand.Conversions[ArgIdx],
15565 Best->Conversions[ArgIdx]) ==
15567 AmbiguousWith.push_back(Cand.Function);
15568 break;
15569 }
15570 }
15571 }
15572 }
15573
15574 if (!AmbiguousWith.empty()) {
15575 bool AmbiguousWithSelf =
15576 AmbiguousWith.size() == 1 &&
15577 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15578 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15580 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15581 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15582 if (AmbiguousWithSelf) {
15583 Diag(FnDecl->getLocation(),
15584 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15585 // Mark member== const or provide matching != to disallow reversed
15586 // args. Eg.
15587 // struct S { bool operator==(const S&); };
15588 // S()==S();
15589 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15590 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15591 !MD->isConst() &&
15592 !MD->hasCXXExplicitFunctionObjectParameter() &&
15593 Context.hasSameUnqualifiedType(
15594 MD->getFunctionObjectParameterType(),
15595 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15596 Context.hasSameUnqualifiedType(
15597 MD->getFunctionObjectParameterType(),
15598 Args[0]->getType()) &&
15599 Context.hasSameUnqualifiedType(
15600 MD->getFunctionObjectParameterType(),
15601 Args[1]->getType()))
15602 Diag(FnDecl->getLocation(),
15603 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15604 } else {
15605 Diag(FnDecl->getLocation(),
15606 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15607 for (auto *F : AmbiguousWith)
15608 Diag(F->getLocation(),
15609 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15610 }
15611 }
15612 }
15613
15614 // Check for nonnull = nullable.
15615 // This won't be caught in the arg's initialization: the parameter to
15616 // the assignment operator is not marked nonnull.
15617 if (Op == OO_Equal)
15619 Args[1]->getType(), OpLoc);
15620
15621 // Convert the arguments.
15622 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15623 // Best->Access is only meaningful for class members.
15624 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15625
15626 ExprResult Arg0, Arg1;
15627 unsigned ParamIdx = 0;
15628 if (Method->isExplicitObjectMemberFunction()) {
15629 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15630 ParamIdx = 1;
15631 } else {
15633 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15634 }
15637 Context, FnDecl->getParamDecl(ParamIdx)),
15638 SourceLocation(), Args[1]);
15639 if (Arg0.isInvalid() || Arg1.isInvalid())
15640 return ExprError();
15641
15642 Base = Args[0] = Arg0.getAs<Expr>();
15643 Args[1] = RHS = Arg1.getAs<Expr>();
15644 } else {
15645 // Convert the arguments.
15648 FnDecl->getParamDecl(0)),
15649 SourceLocation(), Args[0]);
15650 if (Arg0.isInvalid())
15651 return ExprError();
15652
15653 ExprResult Arg1 =
15656 FnDecl->getParamDecl(1)),
15657 SourceLocation(), Args[1]);
15658 if (Arg1.isInvalid())
15659 return ExprError();
15660 Args[0] = LHS = Arg0.getAs<Expr>();
15661 Args[1] = RHS = Arg1.getAs<Expr>();
15662 }
15663
15664 // Build the actual expression node.
15665 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15666 Best->FoundDecl, Base,
15667 HadMultipleCandidates, OpLoc);
15668 if (FnExpr.isInvalid())
15669 return ExprError();
15670
15671 // Determine the result type.
15672 QualType ResultTy = FnDecl->getReturnType();
15674 ResultTy = ResultTy.getNonLValueExprType(Context);
15675
15676 CallExpr *TheCall;
15677 ArrayRef<const Expr *> ArgsArray(Args, 2);
15678 const Expr *ImplicitThis = nullptr;
15679
15680 // We always create a CXXOperatorCallExpr, even for explicit object
15681 // members; CodeGen should take care not to emit the this pointer.
15683 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15685 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15686
15687 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15688 Method && Method->isImplicitObjectMemberFunction()) {
15689 // Cut off the implicit 'this'.
15690 ImplicitThis = ArgsArray[0];
15691 ArgsArray = ArgsArray.slice(1);
15692 }
15693
15694 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15695 FnDecl))
15696 return ExprError();
15697
15698 if (Op == OO_Equal) {
15699 // Check for a self move.
15700 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15701 // lifetime check.
15703 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15704 Args[1]);
15705 }
15706 if (ImplicitThis) {
15707 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15708 QualType ThisTypeFromDecl = Context.getPointerType(
15709 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15710
15711 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15712 ThisTypeFromDecl);
15713 }
15714
15715 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15716 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15718
15719 ExprResult R = MaybeBindToTemporary(TheCall);
15720 if (R.isInvalid())
15721 return ExprError();
15722
15723 R = CheckForImmediateInvocation(R, FnDecl);
15724 if (R.isInvalid())
15725 return ExprError();
15726
15727 // For a rewritten candidate, we've already reversed the arguments
15728 // if needed. Perform the rest of the rewrite now.
15729 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15730 (Op == OO_Spaceship && IsReversed)) {
15731 if (Op == OO_ExclaimEqual) {
15732 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15733 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15734 } else {
15735 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15736 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15737 Expr *ZeroLiteral =
15739
15742 Ctx.Entity = FnDecl;
15744
15746 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15747 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15748 /*AllowRewrittenCandidates=*/false);
15749
15751 }
15752 if (R.isInvalid())
15753 return ExprError();
15754 } else {
15755 assert(ChosenOp == Op && "unexpected operator name");
15756 }
15757
15758 // Make a note in the AST if we did any rewriting.
15759 if (Best->RewriteKind != CRK_None)
15760 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15761
15762 return R;
15763 } else {
15764 // We matched a built-in operator. Convert the arguments, then
15765 // break out so that we will build the appropriate built-in
15766 // operator node.
15768 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15771 if (ArgsRes0.isInvalid())
15772 return ExprError();
15773 Args[0] = ArgsRes0.get();
15774
15776 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15779 if (ArgsRes1.isInvalid())
15780 return ExprError();
15781 Args[1] = ArgsRes1.get();
15782 break;
15783 }
15784 }
15785
15786 case OR_No_Viable_Function: {
15787 // C++ [over.match.oper]p9:
15788 // If the operator is the operator , [...] and there are no
15789 // viable functions, then the operator is assumed to be the
15790 // built-in operator and interpreted according to clause 5.
15791 if (Opc == BO_Comma)
15792 break;
15793
15794 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15795 // compare result using '==' and '<'.
15796 if (DefaultedFn && Opc == BO_Cmp) {
15797 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15798 Args[1], DefaultedFn);
15799 if (E.isInvalid() || E.isUsable())
15800 return E;
15801 }
15802
15803 // For class as left operand for assignment or compound assignment
15804 // operator do not fall through to handling in built-in, but report that
15805 // no overloaded assignment operator found
15807 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15808 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15809 Args, OpLoc);
15810 DeferDiagsRAII DDR(*this,
15811 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15812 if (Args[0]->getType()->isRecordType() &&
15813 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15814 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15816 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15817 if (Args[0]->getType()->isIncompleteType()) {
15818 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15819 << Args[0]->getType()
15820 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15821 }
15822 } else {
15823 // This is an erroneous use of an operator which can be overloaded by
15824 // a non-member function. Check for non-member operators which were
15825 // defined too late to be candidates.
15826 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15827 // FIXME: Recover by calling the found function.
15828 return ExprError();
15829
15830 // No viable function; try to create a built-in operation, which will
15831 // produce an error. Then, show the non-viable candidates.
15832 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15833 }
15834 assert(Result.isInvalid() &&
15835 "C++ binary operator overloading is missing candidates!");
15836 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15837 return Result;
15838 }
15839
15840 case OR_Ambiguous:
15841 CandidateSet.NoteCandidates(
15842 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15844 << Args[0]->getType()
15845 << Args[1]->getType()
15846 << Args[0]->getSourceRange()
15847 << Args[1]->getSourceRange()),
15849 OpLoc);
15850 return ExprError();
15851
15852 case OR_Deleted: {
15853 if (isImplicitlyDeleted(Best->Function)) {
15854 FunctionDecl *DeletedFD = Best->Function;
15856 if (DFK.isSpecialMember()) {
15857 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15858 << Args[0]->getType() << DFK.asSpecialMember();
15859 } else {
15860 assert(DFK.isComparison());
15861 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15862 << Args[0]->getType() << DeletedFD;
15863 }
15864
15865 // The user probably meant to call this special member. Just
15866 // explain why it's deleted.
15867 NoteDeletedFunction(DeletedFD);
15868 return ExprError();
15869 }
15870
15871 StringLiteral *Msg = Best->Function->getDeletedMessage();
15872 CandidateSet.NoteCandidates(
15874 OpLoc,
15875 PDiag(diag::err_ovl_deleted_oper)
15876 << getOperatorSpelling(Best->Function->getDeclName()
15877 .getCXXOverloadedOperator())
15878 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15879 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15881 OpLoc);
15882 return ExprError();
15883 }
15884 }
15885
15886 // We matched a built-in operator; build it.
15887 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15888}
15889
15891 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15892 FunctionDecl *DefaultedFn) {
15893 const ComparisonCategoryInfo *Info =
15894 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15895 // If we're not producing a known comparison category type, we can't
15896 // synthesize a three-way comparison. Let the caller diagnose this.
15897 if (!Info)
15898 return ExprResult((Expr*)nullptr);
15899
15900 // If we ever want to perform this synthesis more generally, we will need to
15901 // apply the temporary materialization conversion to the operands.
15902 assert(LHS->isGLValue() && RHS->isGLValue() &&
15903 "cannot use prvalue expressions more than once");
15904 Expr *OrigLHS = LHS;
15905 Expr *OrigRHS = RHS;
15906
15907 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15908 // each of them multiple times below.
15909 LHS = new (Context)
15910 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15911 LHS->getObjectKind(), LHS);
15912 RHS = new (Context)
15913 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15914 RHS->getObjectKind(), RHS);
15915
15916 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15917 DefaultedFn);
15918 if (Eq.isInvalid())
15919 return ExprError();
15920
15921 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15922 true, DefaultedFn);
15923 if (Less.isInvalid())
15924 return ExprError();
15925
15927 if (Info->isPartial()) {
15928 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15929 DefaultedFn);
15930 if (Greater.isInvalid())
15931 return ExprError();
15932 }
15933
15934 // Form the list of comparisons we're going to perform.
15935 struct Comparison {
15938 } Comparisons[4] =
15944 };
15945
15946 int I = Info->isPartial() ? 3 : 2;
15947
15948 // Combine the comparisons with suitable conditional expressions.
15950 for (; I >= 0; --I) {
15951 // Build a reference to the comparison category constant.
15952 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15953 // FIXME: Missing a constant for a comparison category. Diagnose this?
15954 if (!VI)
15955 return ExprResult((Expr*)nullptr);
15956 ExprResult ThisResult =
15958 if (ThisResult.isInvalid())
15959 return ExprError();
15960
15961 // Build a conditional unless this is the final case.
15962 if (Result.get()) {
15963 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15964 ThisResult.get(), Result.get());
15965 if (Result.isInvalid())
15966 return ExprError();
15967 } else {
15968 Result = ThisResult;
15969 }
15970 }
15971
15972 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15973 // bind the OpaqueValueExprs before they're (repeatedly) used.
15974 Expr *SyntacticForm = BinaryOperator::Create(
15975 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15976 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15978 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15979 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15980}
15981
15983 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15984 MultiExprArg Args, SourceLocation LParenLoc) {
15985
15986 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15987 unsigned NumParams = Proto->getNumParams();
15988 unsigned NumArgsSlots =
15989 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15990 // Build the full argument list for the method call (the implicit object
15991 // parameter is placed at the beginning of the list).
15992 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15993 bool IsError = false;
15994 // Initialize the implicit object parameter.
15995 // Check the argument types.
15996 for (unsigned i = 0; i != NumParams; i++) {
15997 Expr *Arg;
15998 if (i < Args.size()) {
15999 Arg = Args[i];
16000 ExprResult InputInit =
16002 S.Context, Method->getParamDecl(i)),
16003 SourceLocation(), Arg);
16004 IsError |= InputInit.isInvalid();
16005 Arg = InputInit.getAs<Expr>();
16006 } else {
16007 ExprResult DefArg =
16008 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16009 if (DefArg.isInvalid()) {
16010 IsError = true;
16011 break;
16012 }
16013 Arg = DefArg.getAs<Expr>();
16014 }
16015
16016 MethodArgs.push_back(Arg);
16017 }
16018 return IsError;
16019}
16020
16022 SourceLocation RLoc,
16023 Expr *Base,
16024 MultiExprArg ArgExpr) {
16026 Args.push_back(Base);
16027 for (auto *e : ArgExpr) {
16028 Args.push_back(e);
16029 }
16030 DeclarationName OpName =
16031 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16032
16033 SourceRange Range = ArgExpr.empty()
16034 ? SourceRange{}
16035 : SourceRange(ArgExpr.front()->getBeginLoc(),
16036 ArgExpr.back()->getEndLoc());
16037
16038 // If either side is type-dependent, create an appropriate dependent
16039 // expression.
16041
16042 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16043 // CHECKME: no 'operator' keyword?
16044 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16045 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16047 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16048 if (Fn.isInvalid())
16049 return ExprError();
16050 // Can't add any actual overloads yet
16051
16052 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16053 Context.DependentTy, VK_PRValue, RLoc,
16055 }
16056
16057 // Handle placeholders
16058 UnbridgedCastsSet UnbridgedCasts;
16059 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16060 return ExprError();
16061 }
16062 // Build an empty overload set.
16064
16065 // Subscript can only be overloaded as a member function.
16066
16067 // Add operator candidates that are member functions.
16068 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16069
16070 // Add builtin operator candidates.
16071 if (Args.size() == 2)
16072 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16073
16074 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16075
16076 // Perform overload resolution.
16078 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16079 case OR_Success: {
16080 // We found a built-in operator or an overloaded operator.
16081 FunctionDecl *FnDecl = Best->Function;
16082
16083 if (FnDecl) {
16084 // We matched an overloaded operator. Build a call to that
16085 // operator.
16086
16087 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16088
16089 // Convert the arguments.
16091 SmallVector<Expr *, 2> MethodArgs;
16092
16093 // Initialize the object parameter.
16094 if (Method->isExplicitObjectMemberFunction()) {
16095 ExprResult Res =
16097 if (Res.isInvalid())
16098 return ExprError();
16099 Args[0] = Res.get();
16100 ArgExpr = Args;
16101 } else {
16103 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16104 if (Arg0.isInvalid())
16105 return ExprError();
16106
16107 MethodArgs.push_back(Arg0.get());
16108 }
16109
16111 *this, MethodArgs, Method, ArgExpr, LLoc);
16112 if (IsError)
16113 return ExprError();
16114
16115 // Build the actual expression node.
16116 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16117 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16119 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16120 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16121 if (FnExpr.isInvalid())
16122 return ExprError();
16123
16124 // Determine the result type
16125 QualType ResultTy = FnDecl->getReturnType();
16127 ResultTy = ResultTy.getNonLValueExprType(Context);
16128
16130 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16132
16133 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16134 return ExprError();
16135
16136 if (CheckFunctionCall(Method, TheCall,
16137 Method->getType()->castAs<FunctionProtoType>()))
16138 return ExprError();
16139
16141 FnDecl);
16142 } else {
16143 // We matched a built-in operator. Convert the arguments, then
16144 // break out so that we will build the appropriate built-in
16145 // operator node.
16147 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16150 if (ArgsRes0.isInvalid())
16151 return ExprError();
16152 Args[0] = ArgsRes0.get();
16153
16155 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16158 if (ArgsRes1.isInvalid())
16159 return ExprError();
16160 Args[1] = ArgsRes1.get();
16161
16162 break;
16163 }
16164 }
16165
16166 case OR_No_Viable_Function: {
16168 CandidateSet.empty()
16169 ? (PDiag(diag::err_ovl_no_oper)
16170 << Args[0]->getType() << /*subscript*/ 0
16171 << Args[0]->getSourceRange() << Range)
16172 : (PDiag(diag::err_ovl_no_viable_subscript)
16173 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16174 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16175 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16176 return ExprError();
16177 }
16178
16179 case OR_Ambiguous:
16180 if (Args.size() == 2) {
16181 CandidateSet.NoteCandidates(
16183 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16184 << "[]" << Args[0]->getType() << Args[1]->getType()
16185 << Args[0]->getSourceRange() << Range),
16186 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16187 } else {
16188 CandidateSet.NoteCandidates(
16190 PDiag(diag::err_ovl_ambiguous_subscript_call)
16191 << Args[0]->getType()
16192 << Args[0]->getSourceRange() << Range),
16193 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16194 }
16195 return ExprError();
16196
16197 case OR_Deleted: {
16198 StringLiteral *Msg = Best->Function->getDeletedMessage();
16199 CandidateSet.NoteCandidates(
16201 PDiag(diag::err_ovl_deleted_oper)
16202 << "[]" << (Msg != nullptr)
16203 << (Msg ? Msg->getString() : StringRef())
16204 << Args[0]->getSourceRange() << Range),
16205 *this, OCD_AllCandidates, Args, "[]", LLoc);
16206 return ExprError();
16207 }
16208 }
16209
16210 // We matched a built-in operator; build it.
16211 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16212}
16213
16215 SourceLocation LParenLoc,
16216 MultiExprArg Args,
16217 SourceLocation RParenLoc,
16218 Expr *ExecConfig, bool IsExecConfig,
16219 bool AllowRecovery) {
16220 assert(MemExprE->getType() == Context.BoundMemberTy ||
16221 MemExprE->getType() == Context.OverloadTy);
16222
16223 // Dig out the member expression. This holds both the object
16224 // argument and the member function we're referring to.
16225 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16226
16227 // Determine whether this is a call to a pointer-to-member function.
16228 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16229 assert(op->getType() == Context.BoundMemberTy);
16230 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16231
16232 QualType fnType =
16233 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16234
16235 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16236 QualType resultType = proto->getCallResultType(Context);
16238
16239 // Check that the object type isn't more qualified than the
16240 // member function we're calling.
16241 Qualifiers funcQuals = proto->getMethodQuals();
16242
16243 QualType objectType = op->getLHS()->getType();
16244 if (op->getOpcode() == BO_PtrMemI)
16245 objectType = objectType->castAs<PointerType>()->getPointeeType();
16246 Qualifiers objectQuals = objectType.getQualifiers();
16247
16248 Qualifiers difference = objectQuals - funcQuals;
16249 difference.removeObjCGCAttr();
16250 difference.removeAddressSpace();
16251 if (difference) {
16252 std::string qualsString = difference.getAsString();
16253 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16254 << fnType.getUnqualifiedType()
16255 << qualsString
16256 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16257 }
16258
16260 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16262
16263 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16264 call, nullptr))
16265 return ExprError();
16266
16267 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16268 return ExprError();
16269
16270 if (CheckOtherCall(call, proto))
16271 return ExprError();
16272
16273 return MaybeBindToTemporary(call);
16274 }
16275
16276 // We only try to build a recovery expr at this level if we can preserve
16277 // the return type, otherwise we return ExprError() and let the caller
16278 // recover.
16279 auto BuildRecoveryExpr = [&](QualType Type) {
16280 if (!AllowRecovery)
16281 return ExprError();
16282 std::vector<Expr *> SubExprs = {MemExprE};
16283 llvm::append_range(SubExprs, Args);
16284 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16285 Type);
16286 };
16287 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16288 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16289 RParenLoc, CurFPFeatureOverrides());
16290
16291 UnbridgedCastsSet UnbridgedCasts;
16292 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16293 return ExprError();
16294
16295 MemberExpr *MemExpr;
16296 CXXMethodDecl *Method = nullptr;
16297 bool HadMultipleCandidates = false;
16298 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16299 NestedNameSpecifier Qualifier = std::nullopt;
16300 if (isa<MemberExpr>(NakedMemExpr)) {
16301 MemExpr = cast<MemberExpr>(NakedMemExpr);
16303 FoundDecl = MemExpr->getFoundDecl();
16304 Qualifier = MemExpr->getQualifier();
16305 UnbridgedCasts.restore();
16306 } else {
16307 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16308 Qualifier = UnresExpr->getQualifier();
16309
16310 QualType ObjectType = UnresExpr->getBaseType();
16311 Expr::Classification ObjectClassification
16313 : UnresExpr->getBase()->Classify(Context);
16314
16315 // Add overload candidates
16316 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16318
16319 // FIXME: avoid copy.
16320 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16321 if (UnresExpr->hasExplicitTemplateArgs()) {
16322 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16323 TemplateArgs = &TemplateArgsBuffer;
16324 }
16325
16327 E = UnresExpr->decls_end(); I != E; ++I) {
16328
16329 QualType ExplicitObjectType = ObjectType;
16330
16331 NamedDecl *Func = *I;
16332 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16334 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16335
16336 bool HasExplicitParameter = false;
16337 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16338 M && M->hasCXXExplicitFunctionObjectParameter())
16339 HasExplicitParameter = true;
16340 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16341 M &&
16342 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16343 HasExplicitParameter = true;
16344
16345 if (HasExplicitParameter)
16346 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16347
16348 // Microsoft supports direct constructor calls.
16349 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16351 CandidateSet,
16352 /*SuppressUserConversions*/ false);
16353 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16354 // If explicit template arguments were provided, we can't call a
16355 // non-template member function.
16356 if (TemplateArgs)
16357 continue;
16358
16359 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16360 ObjectClassification, Args, CandidateSet,
16361 /*SuppressUserConversions=*/false);
16362 } else {
16364 I.getPair(), ActingDC, TemplateArgs,
16365 ExplicitObjectType, ObjectClassification,
16366 Args, CandidateSet,
16367 /*SuppressUserConversions=*/false);
16368 }
16369 }
16370
16371 HadMultipleCandidates = (CandidateSet.size() > 1);
16372
16373 DeclarationName DeclName = UnresExpr->getMemberName();
16374
16375 UnbridgedCasts.restore();
16376
16378 bool Succeeded = false;
16379 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16380 Best)) {
16381 case OR_Success:
16382 Method = cast<CXXMethodDecl>(Best->Function);
16383 FoundDecl = Best->FoundDecl;
16384 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16385 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16386 break;
16387 // If FoundDecl is different from Method (such as if one is a template
16388 // and the other a specialization), make sure DiagnoseUseOfDecl is
16389 // called on both.
16390 // FIXME: This would be more comprehensively addressed by modifying
16391 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16392 // being used.
16393 if (Method != FoundDecl.getDecl() &&
16395 break;
16396 Succeeded = true;
16397 break;
16398
16400 CandidateSet.NoteCandidates(
16402 UnresExpr->getMemberLoc(),
16403 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16404 << DeclName << MemExprE->getSourceRange()),
16405 *this, OCD_AllCandidates, Args);
16406 break;
16407 case OR_Ambiguous:
16408 CandidateSet.NoteCandidates(
16409 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16410 PDiag(diag::err_ovl_ambiguous_member_call)
16411 << DeclName << MemExprE->getSourceRange()),
16412 *this, OCD_AmbiguousCandidates, Args);
16413 break;
16414 case OR_Deleted:
16416 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16417 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16418 break;
16419 }
16420 // Overload resolution fails, try to recover.
16421 if (!Succeeded)
16422 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16423
16424 ExprResult Res =
16425 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16426 if (Res.isInvalid())
16427 return ExprError();
16428 MemExprE = Res.get();
16429
16430 // If overload resolution picked a static member
16431 // build a non-member call based on that function.
16432 if (Method->isStatic()) {
16433 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16434 ExecConfig, IsExecConfig);
16435 }
16436
16437 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16438 }
16439
16440 QualType ResultType = Method->getReturnType();
16442 ResultType = ResultType.getNonLValueExprType(Context);
16443
16444 assert(Method && "Member call to something that isn't a method?");
16445 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16446
16447 CallExpr *TheCall = nullptr;
16449 if (Method->isExplicitObjectMemberFunction()) {
16450 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16451 NewArgs))
16452 return ExprError();
16453
16454 // Build the actual expression node.
16455 ExprResult FnExpr =
16456 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16457 HadMultipleCandidates, MemExpr->getExprLoc());
16458 if (FnExpr.isInvalid())
16459 return ExprError();
16460
16461 TheCall =
16462 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16463 CurFPFeatureOverrides(), Proto->getNumParams());
16464 TheCall->setUsesMemberSyntax(true);
16465 } else {
16466 // Convert the object argument (for a non-static member function call).
16468 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16469 if (ObjectArg.isInvalid())
16470 return ExprError();
16471 MemExpr->setBase(ObjectArg.get());
16472 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16473 RParenLoc, CurFPFeatureOverrides(),
16474 Proto->getNumParams());
16475 }
16476
16477 // Check for a valid return type.
16478 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16479 TheCall, Method))
16480 return BuildRecoveryExpr(ResultType);
16481
16482 // Convert the rest of the arguments
16483 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16484 RParenLoc))
16485 return BuildRecoveryExpr(ResultType);
16486
16487 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16488
16489 if (CheckFunctionCall(Method, TheCall, Proto))
16490 return ExprError();
16491
16492 // In the case the method to call was not selected by the overloading
16493 // resolution process, we still need to handle the enable_if attribute. Do
16494 // that here, so it will not hide previous -- and more relevant -- errors.
16495 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16496 if (const EnableIfAttr *Attr =
16497 CheckEnableIf(Method, LParenLoc, Args, true)) {
16498 Diag(MemE->getMemberLoc(),
16499 diag::err_ovl_no_viable_member_function_in_call)
16500 << Method << Method->getSourceRange();
16501 Diag(Method->getLocation(),
16502 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16503 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16504 return ExprError();
16505 }
16506 }
16507
16509 TheCall->getDirectCallee()->isPureVirtual()) {
16510 const FunctionDecl *MD = TheCall->getDirectCallee();
16511
16512 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16514 Diag(MemExpr->getBeginLoc(),
16515 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16517 << MD->getParent();
16518
16519 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16520 if (getLangOpts().AppleKext)
16521 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16522 << MD->getParent() << MD->getDeclName();
16523 }
16524 }
16525
16526 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16527 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16528 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16529 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16530 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16531 MemExpr->getMemberLoc());
16532 }
16533
16535 TheCall->getDirectCallee());
16536}
16537
16540 SourceLocation LParenLoc,
16541 MultiExprArg Args,
16542 SourceLocation RParenLoc) {
16543 if (checkPlaceholderForOverload(*this, Obj))
16544 return ExprError();
16545 ExprResult Object = Obj;
16546
16547 UnbridgedCastsSet UnbridgedCasts;
16548 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16549 return ExprError();
16550
16551 assert(Object.get()->getType()->isRecordType() &&
16552 "Requires object type argument");
16553
16554 // C++ [over.call.object]p1:
16555 // If the primary-expression E in the function call syntax
16556 // evaluates to a class object of type "cv T", then the set of
16557 // candidate functions includes at least the function call
16558 // operators of T. The function call operators of T are obtained by
16559 // ordinary lookup of the name operator() in the context of
16560 // (E).operator().
16561 OverloadCandidateSet CandidateSet(LParenLoc,
16563 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16564
16565 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16566 diag::err_incomplete_object_call, Object.get()))
16567 return true;
16568
16569 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16570 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16572 R.suppressAccessDiagnostics();
16573
16574 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16575 Oper != OperEnd; ++Oper) {
16576 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16577 Object.get()->Classify(Context), Args, CandidateSet,
16578 /*SuppressUserConversion=*/false);
16579 }
16580
16581 // When calling a lambda, both the call operator, and
16582 // the conversion operator to function pointer
16583 // are considered. But when constraint checking
16584 // on the call operator fails, it will also fail on the
16585 // conversion operator as the constraints are always the same.
16586 // As the user probably does not intend to perform a surrogate call,
16587 // we filter them out to produce better error diagnostics, ie to avoid
16588 // showing 2 failed overloads instead of one.
16589 bool IgnoreSurrogateFunctions = false;
16590 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16591 const OverloadCandidate &Candidate = *CandidateSet.begin();
16592 if (!Candidate.Viable &&
16594 IgnoreSurrogateFunctions = true;
16595 }
16596
16597 // C++ [over.call.object]p2:
16598 // In addition, for each (non-explicit in C++0x) conversion function
16599 // declared in T of the form
16600 //
16601 // operator conversion-type-id () cv-qualifier;
16602 //
16603 // where cv-qualifier is the same cv-qualification as, or a
16604 // greater cv-qualification than, cv, and where conversion-type-id
16605 // denotes the type "pointer to function of (P1,...,Pn) returning
16606 // R", or the type "reference to pointer to function of
16607 // (P1,...,Pn) returning R", or the type "reference to function
16608 // of (P1,...,Pn) returning R", a surrogate call function [...]
16609 // is also considered as a candidate function. Similarly,
16610 // surrogate call functions are added to the set of candidate
16611 // functions for each conversion function declared in an
16612 // accessible base class provided the function is not hidden
16613 // within T by another intervening declaration.
16614 const auto &Conversions = Record->getVisibleConversionFunctions();
16615 for (auto I = Conversions.begin(), E = Conversions.end();
16616 !IgnoreSurrogateFunctions && I != E; ++I) {
16617 NamedDecl *D = *I;
16618 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16619 if (isa<UsingShadowDecl>(D))
16620 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16621
16622 // Skip over templated conversion functions; they aren't
16623 // surrogates.
16625 continue;
16626
16628 if (!Conv->isExplicit()) {
16629 // Strip the reference type (if any) and then the pointer type (if
16630 // any) to get down to what might be a function type.
16631 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16632 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16633 ConvType = ConvPtrType->getPointeeType();
16634
16635 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16636 {
16637 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16638 Object.get(), Args, CandidateSet);
16639 }
16640 }
16641 }
16642
16643 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16644
16645 // Perform overload resolution.
16647 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16648 Best)) {
16649 case OR_Success:
16650 // Overload resolution succeeded; we'll build the appropriate call
16651 // below.
16652 break;
16653
16654 case OR_No_Viable_Function: {
16656 CandidateSet.empty()
16657 ? (PDiag(diag::err_ovl_no_oper)
16658 << Object.get()->getType() << /*call*/ 1
16659 << Object.get()->getSourceRange())
16660 : (PDiag(diag::err_ovl_no_viable_object_call)
16661 << Object.get()->getType() << Object.get()->getSourceRange());
16662 CandidateSet.NoteCandidates(
16663 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16664 OCD_AllCandidates, Args);
16665 break;
16666 }
16667 case OR_Ambiguous:
16668 if (!R.isAmbiguous())
16669 CandidateSet.NoteCandidates(
16670 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16671 PDiag(diag::err_ovl_ambiguous_object_call)
16672 << Object.get()->getType()
16673 << Object.get()->getSourceRange()),
16674 *this, OCD_AmbiguousCandidates, Args);
16675 break;
16676
16677 case OR_Deleted: {
16678 // FIXME: Is this diagnostic here really necessary? It seems that
16679 // 1. we don't have any tests for this diagnostic, and
16680 // 2. we already issue err_deleted_function_use for this later on anyway.
16681 StringLiteral *Msg = Best->Function->getDeletedMessage();
16682 CandidateSet.NoteCandidates(
16683 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16684 PDiag(diag::err_ovl_deleted_object_call)
16685 << Object.get()->getType() << (Msg != nullptr)
16686 << (Msg ? Msg->getString() : StringRef())
16687 << Object.get()->getSourceRange()),
16688 *this, OCD_AllCandidates, Args);
16689 break;
16690 }
16691 }
16692
16693 if (Best == CandidateSet.end())
16694 return true;
16695
16696 UnbridgedCasts.restore();
16697
16698 if (Best->Function == nullptr) {
16699 // Since there is no function declaration, this is one of the
16700 // surrogate candidates. Dig out the conversion function.
16701 CXXConversionDecl *Conv
16703 Best->Conversions[0].UserDefined.ConversionFunction);
16704
16705 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16706 Best->FoundDecl);
16707 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16708 return ExprError();
16709 assert(Conv == Best->FoundDecl.getDecl() &&
16710 "Found Decl & conversion-to-functionptr should be same, right?!");
16711 // We selected one of the surrogate functions that converts the
16712 // object parameter to a function pointer. Perform the conversion
16713 // on the object argument, then let BuildCallExpr finish the job.
16714
16715 // Create an implicit member expr to refer to the conversion operator.
16716 // and then call it.
16717 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16718 Conv, HadMultipleCandidates);
16719 if (Call.isInvalid())
16720 return ExprError();
16721 // Record usage of conversion in an implicit cast.
16723 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16724 nullptr, VK_PRValue, CurFPFeatureOverrides());
16725
16726 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16727 }
16728
16729 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16730
16731 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16732 // that calls this method, using Object for the implicit object
16733 // parameter and passing along the remaining arguments.
16734 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16735
16736 // An error diagnostic has already been printed when parsing the declaration.
16737 if (Method->isInvalidDecl())
16738 return ExprError();
16739
16740 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16741 unsigned NumParams = Proto->getNumParams();
16742
16743 DeclarationNameInfo OpLocInfo(
16744 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16745 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16746 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16747 Obj, HadMultipleCandidates,
16748 OpLocInfo.getLoc(),
16749 OpLocInfo.getInfo());
16750 if (NewFn.isInvalid())
16751 return true;
16752
16753 SmallVector<Expr *, 8> MethodArgs;
16754 MethodArgs.reserve(NumParams + 1);
16755
16756 bool IsError = false;
16757
16758 // Initialize the object parameter.
16760 if (Method->isExplicitObjectMemberFunction()) {
16761 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16762 } else {
16764 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16765 if (ObjRes.isInvalid())
16766 IsError = true;
16767 else
16768 Object = ObjRes;
16769 MethodArgs.push_back(Object.get());
16770 }
16771
16773 *this, MethodArgs, Method, Args, LParenLoc);
16774
16775 // If this is a variadic call, handle args passed through "...".
16776 if (Proto->isVariadic()) {
16777 // Promote the arguments (C99 6.5.2.2p7).
16778 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16780 Args[i], VariadicCallType::Method, nullptr);
16781 IsError |= Arg.isInvalid();
16782 MethodArgs.push_back(Arg.get());
16783 }
16784 }
16785
16786 if (IsError)
16787 return true;
16788
16789 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16790
16791 // Once we've built TheCall, all of the expressions are properly owned.
16792 QualType ResultTy = Method->getReturnType();
16794 ResultTy = ResultTy.getNonLValueExprType(Context);
16795
16797 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16799
16800 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16801 return true;
16802
16803 if (CheckFunctionCall(Method, TheCall, Proto))
16804 return true;
16805
16807}
16808
16810 SourceLocation OpLoc,
16811 bool *NoArrowOperatorFound) {
16812 assert(Base->getType()->isRecordType() &&
16813 "left-hand side must have class type");
16814
16816 return ExprError();
16817
16818 SourceLocation Loc = Base->getExprLoc();
16819
16820 // C++ [over.ref]p1:
16821 //
16822 // [...] An expression x->m is interpreted as (x.operator->())->m
16823 // for a class object x of type T if T::operator->() exists and if
16824 // the operator is selected as the best match function by the
16825 // overload resolution mechanism (13.3).
16826 DeclarationName OpName =
16827 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16829
16830 if (RequireCompleteType(Loc, Base->getType(),
16831 diag::err_typecheck_incomplete_tag, Base))
16832 return ExprError();
16833
16834 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16835 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16836 R.suppressAccessDiagnostics();
16837
16838 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16839 Oper != OperEnd; ++Oper) {
16840 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16841 {}, CandidateSet,
16842 /*SuppressUserConversion=*/false);
16843 }
16844
16845 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16846
16847 // Perform overload resolution.
16849 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16850 case OR_Success:
16851 // Overload resolution succeeded; we'll build the call below.
16852 break;
16853
16854 case OR_No_Viable_Function: {
16855 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16856 if (CandidateSet.empty()) {
16857 QualType BaseType = Base->getType();
16858 if (NoArrowOperatorFound) {
16859 // Report this specific error to the caller instead of emitting a
16860 // diagnostic, as requested.
16861 *NoArrowOperatorFound = true;
16862 return ExprError();
16863 }
16864 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16865 << BaseType << Base->getSourceRange();
16866 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16867 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16868 << FixItHint::CreateReplacement(OpLoc, ".");
16869 }
16870 } else
16871 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16872 << "operator->" << Base->getSourceRange();
16873 CandidateSet.NoteCandidates(*this, Base, Cands);
16874 return ExprError();
16875 }
16876 case OR_Ambiguous:
16877 if (!R.isAmbiguous())
16878 CandidateSet.NoteCandidates(
16879 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16880 << "->" << Base->getType()
16881 << Base->getSourceRange()),
16883 return ExprError();
16884
16885 case OR_Deleted: {
16886 StringLiteral *Msg = Best->Function->getDeletedMessage();
16887 CandidateSet.NoteCandidates(
16888 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16889 << "->" << (Msg != nullptr)
16890 << (Msg ? Msg->getString() : StringRef())
16891 << Base->getSourceRange()),
16892 *this, OCD_AllCandidates, Base);
16893 return ExprError();
16894 }
16895 }
16896
16897 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16898
16899 // Convert the object parameter.
16900 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16901
16902 if (Method->isExplicitObjectMemberFunction()) {
16904 if (R.isInvalid())
16905 return ExprError();
16906 Base = R.get();
16907 } else {
16909 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16910 if (BaseResult.isInvalid())
16911 return ExprError();
16912 Base = BaseResult.get();
16913 }
16914
16915 // Build the operator call.
16916 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16917 Base, HadMultipleCandidates, OpLoc);
16918 if (FnExpr.isInvalid())
16919 return ExprError();
16920
16921 QualType ResultTy = Method->getReturnType();
16923 ResultTy = ResultTy.getNonLValueExprType(Context);
16924
16925 CallExpr *TheCall =
16926 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16927 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16928
16929 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16930 return ExprError();
16931
16932 if (CheckFunctionCall(Method, TheCall,
16933 Method->getType()->castAs<FunctionProtoType>()))
16934 return ExprError();
16935
16937}
16938
16940 DeclarationNameInfo &SuffixInfo,
16941 ArrayRef<Expr*> Args,
16942 SourceLocation LitEndLoc,
16943 TemplateArgumentListInfo *TemplateArgs) {
16944 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16945
16946 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16948 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16949 TemplateArgs);
16950
16951 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16952
16953 // Perform overload resolution. This will usually be trivial, but might need
16954 // to perform substitutions for a literal operator template.
16956 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16957 case OR_Success:
16958 case OR_Deleted:
16959 break;
16960
16962 CandidateSet.NoteCandidates(
16963 PartialDiagnosticAt(UDSuffixLoc,
16964 PDiag(diag::err_ovl_no_viable_function_in_call)
16965 << R.getLookupName()),
16966 *this, OCD_AllCandidates, Args);
16967 return ExprError();
16968
16969 case OR_Ambiguous:
16970 CandidateSet.NoteCandidates(
16971 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16972 << R.getLookupName()),
16973 *this, OCD_AmbiguousCandidates, Args);
16974 return ExprError();
16975 }
16976
16977 FunctionDecl *FD = Best->Function;
16978 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16979 nullptr, HadMultipleCandidates,
16980 SuffixInfo.getLoc(),
16981 SuffixInfo.getInfo());
16982 if (Fn.isInvalid())
16983 return true;
16984
16985 // Check the argument types. This should almost always be a no-op, except
16986 // that array-to-pointer decay is applied to string literals.
16987 Expr *ConvArgs[2];
16988 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16991 SourceLocation(), Args[ArgIdx]);
16992 if (InputInit.isInvalid())
16993 return true;
16994 ConvArgs[ArgIdx] = InputInit.get();
16995 }
16996
16997 QualType ResultTy = FD->getReturnType();
16999 ResultTy = ResultTy.getNonLValueExprType(Context);
17000
17002 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17003 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17004
17005 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17006 return ExprError();
17007
17008 if (CheckFunctionCall(FD, UDL, nullptr))
17009 return ExprError();
17010
17012}
17013
17016 SourceLocation RangeLoc,
17017 const DeclarationNameInfo &NameInfo,
17018 LookupResult &MemberLookup,
17019 OverloadCandidateSet *CandidateSet,
17020 Expr *Range, ExprResult *CallExpr) {
17021 Scope *S = nullptr;
17022
17024 if (!MemberLookup.empty()) {
17025 ExprResult MemberRef =
17026 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17027 /*IsPtr=*/false, CXXScopeSpec(),
17028 /*TemplateKWLoc=*/SourceLocation(),
17029 /*FirstQualifierInScope=*/nullptr,
17030 MemberLookup,
17031 /*TemplateArgs=*/nullptr, S);
17032 if (MemberRef.isInvalid()) {
17033 *CallExpr = ExprError();
17034 return FRS_DiagnosticIssued;
17035 }
17036 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17037 if (CallExpr->isInvalid()) {
17038 *CallExpr = ExprError();
17039 return FRS_DiagnosticIssued;
17040 }
17041 } else {
17042 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17044 NameInfo, UnresolvedSet<0>());
17045 if (FnR.isInvalid())
17046 return FRS_DiagnosticIssued;
17048
17049 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17050 CandidateSet, CallExpr);
17051 if (CandidateSet->empty() || CandidateSetError) {
17052 *CallExpr = ExprError();
17053 return FRS_NoViableFunction;
17054 }
17056 OverloadingResult OverloadResult =
17057 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17058
17059 if (OverloadResult == OR_No_Viable_Function) {
17060 *CallExpr = ExprError();
17061 return FRS_NoViableFunction;
17062 }
17063 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17064 Loc, nullptr, CandidateSet, &Best,
17065 OverloadResult,
17066 /*AllowTypoCorrection=*/false);
17067 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17068 *CallExpr = ExprError();
17069 return FRS_DiagnosticIssued;
17070 }
17071 }
17072 return FRS_Success;
17073}
17074
17076 FunctionDecl *Fn) {
17077 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17078 ExprResult SubExpr =
17079 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17080 if (SubExpr.isInvalid())
17081 return ExprError();
17082 if (SubExpr.get() == PE->getSubExpr())
17083 return PE;
17084
17085 return new (Context)
17086 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17087 }
17088
17089 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17090 ExprResult SubExpr =
17091 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17092 if (SubExpr.isInvalid())
17093 return ExprError();
17094 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17095 SubExpr.get()->getType()) &&
17096 "Implicit cast type cannot be determined from overload");
17097 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17098 if (SubExpr.get() == ICE->getSubExpr())
17099 return ICE;
17100
17101 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17102 SubExpr.get(), nullptr, ICE->getValueKind(),
17104 }
17105
17106 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17107 if (!GSE->isResultDependent()) {
17108 ExprResult SubExpr =
17109 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17110 if (SubExpr.isInvalid())
17111 return ExprError();
17112 if (SubExpr.get() == GSE->getResultExpr())
17113 return GSE;
17114
17115 // Replace the resulting type information before rebuilding the generic
17116 // selection expression.
17117 ArrayRef<Expr *> A = GSE->getAssocExprs();
17118 SmallVector<Expr *, 4> AssocExprs(A);
17119 unsigned ResultIdx = GSE->getResultIndex();
17120 AssocExprs[ResultIdx] = SubExpr.get();
17121
17122 if (GSE->isExprPredicate())
17124 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17125 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17126 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17127 ResultIdx);
17129 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17130 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17131 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17132 ResultIdx);
17133 }
17134 // Rather than fall through to the unreachable, return the original generic
17135 // selection expression.
17136 return GSE;
17137 }
17138
17139 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17140 assert(UnOp->getOpcode() == UO_AddrOf &&
17141 "Can only take the address of an overloaded function");
17142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17143 if (!Method->isImplicitObjectMemberFunction()) {
17144 // Do nothing: the address of static and
17145 // explicit object member functions is a (non-member) function pointer.
17146 } else {
17147 // Fix the subexpression, which really has to be an
17148 // UnresolvedLookupExpr holding an overloaded member function
17149 // or template.
17150 ExprResult SubExpr =
17151 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17152 if (SubExpr.isInvalid())
17153 return ExprError();
17154 if (SubExpr.get() == UnOp->getSubExpr())
17155 return UnOp;
17156
17157 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17158 SubExpr.get(), Method))
17159 return ExprError();
17160
17161 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17162 "fixed to something other than a decl ref");
17163 NestedNameSpecifier Qualifier =
17164 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17165 assert(Qualifier &&
17166 "fixed to a member ref with no nested name qualifier");
17167
17168 // We have taken the address of a pointer to member
17169 // function. Perform the computation here so that we get the
17170 // appropriate pointer to member type.
17171 QualType MemPtrType = Context.getMemberPointerType(
17172 Fn->getType(), Qualifier,
17173 cast<CXXRecordDecl>(Method->getDeclContext()));
17174 // Under the MS ABI, lock down the inheritance model now.
17175 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17176 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17177
17178 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17179 MemPtrType, VK_PRValue, OK_Ordinary,
17180 UnOp->getOperatorLoc(), false,
17182 }
17183 }
17184 ExprResult SubExpr =
17185 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17186 if (SubExpr.isInvalid())
17187 return ExprError();
17188 if (SubExpr.get() == UnOp->getSubExpr())
17189 return UnOp;
17190
17191 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17192 SubExpr.get());
17193 }
17194
17195 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17196 if (Found.getAccess() == AS_none) {
17198 }
17199 // FIXME: avoid copy.
17200 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17201 if (ULE->hasExplicitTemplateArgs()) {
17202 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17203 TemplateArgs = &TemplateArgsBuffer;
17204 }
17205
17206 QualType Type = Fn->getType();
17207 ExprValueKind ValueKind =
17208 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17209 ? VK_LValue
17210 : VK_PRValue;
17211
17212 // FIXME: Duplicated from BuildDeclarationNameExpr.
17213 if (unsigned BID = Fn->getBuiltinID()) {
17214 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17215 Type = Context.BuiltinFnTy;
17216 ValueKind = VK_PRValue;
17217 }
17218 }
17219
17221 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17222 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17223 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17224 return DRE;
17225 }
17226
17227 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17228 // FIXME: avoid copy.
17229 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17230 if (MemExpr->hasExplicitTemplateArgs()) {
17231 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17232 TemplateArgs = &TemplateArgsBuffer;
17233 }
17234
17235 Expr *Base;
17236
17237 // If we're filling in a static method where we used to have an
17238 // implicit member access, rewrite to a simple decl ref.
17239 if (MemExpr->isImplicitAccess()) {
17240 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17242 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17243 MemExpr->getQualifierLoc(), Found.getDecl(),
17244 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17245 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17246 return DRE;
17247 } else {
17248 SourceLocation Loc = MemExpr->getMemberLoc();
17249 if (MemExpr->getQualifier())
17250 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17251 Base =
17252 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17253 }
17254 } else
17255 Base = MemExpr->getBase();
17256
17257 ExprValueKind valueKind;
17258 QualType type;
17259 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17260 valueKind = VK_LValue;
17261 type = Fn->getType();
17262 } else {
17263 valueKind = VK_PRValue;
17264 type = Context.BoundMemberTy;
17265 }
17266
17267 return BuildMemberExpr(
17268 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17269 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17270 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17271 type, valueKind, OK_Ordinary, TemplateArgs);
17272 }
17273
17274 llvm_unreachable("Invalid reference to overloaded function");
17275}
17276
17282
17283bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17285 if (!PartialOverloading || !Function)
17286 return true;
17287 if (Function->isVariadic())
17288 return false;
17289 if (const auto *Proto =
17290 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17291 if (Proto->isTemplateVariadic())
17292 return false;
17293 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17294 if (const auto *Proto =
17295 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17296 if (Proto->isTemplateVariadic())
17297 return false;
17298 return true;
17299}
17300
17302 DeclarationName Name,
17303 OverloadCandidateSet &CandidateSet,
17304 FunctionDecl *Fn, MultiExprArg Args,
17305 bool IsMember) {
17306 StringLiteral *Msg = Fn->getDeletedMessage();
17307 CandidateSet.NoteCandidates(
17308 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17309 << IsMember << Name << (Msg != nullptr)
17310 << (Msg ? Msg->getString() : StringRef())
17311 << Range),
17312 *this, OCD_AllCandidates, Args);
17313}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
__device__ __2f16 b
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:481
bool isFloat() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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:802
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:918
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:917
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:3942
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:281
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
QualType getElementType() const
Definition TypeBase.h:3784
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8230
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
StringRef getOpcodeStr() const
Definition Expr.h:4107
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
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:5094
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
Pointer to a block type.
Definition TypeBase.h:3592
This class is used for builtin types like 'int'.
Definition TypeBase.h:3214
Kind getKind() const
Definition TypeBase.h:3262
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:2611
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3037
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:3074
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2982
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2986
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:180
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
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:2721
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:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2838
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:287
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
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:2946
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:1517
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3110
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3328
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:3325
QualType getElementType() const
Definition TypeBase.h:3335
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:5116
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4456
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4453
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:1466
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:785
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:770
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:761
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:597
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4028
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4246
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4144
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1955
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1939
const Expr * getExpr() const
Definition DeclCXX.h:1940
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2372
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3339
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4229
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
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:4068
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3175
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2015
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2704
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4194
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
param_iterator param_end()
Definition Decl.h:2802
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3667
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
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:4265
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3748
param_iterator param_begin()
Definition Decl.h:2801
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3134
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4330
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4258
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3870
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2485
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4131
bool isConsteval() const
Definition Decl.h:2497
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3711
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:2877
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:3716
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2700
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5861
unsigned getNumParams() const
Definition TypeBase.h:5635
Qualifiers getMethodQuals() const
Definition TypeBase.h:5783
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5797
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:4664
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4735
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4592
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
ExtInfo getExtInfo() const
Definition TypeBase.h:4909
CallingConv getCallConv() const
Definition TypeBase.h:4908
QualType getReturnType() const
Definition TypeBase.h:4893
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4921
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:4716
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:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:770
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:827
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:681
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:812
bool hasInitializerListContainerType() const
Definition Overload.h:809
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:734
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:816
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:685
QualType getInitializerListContainerType() const
Definition Overload.h:819
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5417
unsigned getNumInits() const
Definition Expr.h:5332
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2496
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2514
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:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3667
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:4401
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3478
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3464
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
void setBase(Expr *E)
Definition Expr.h:3443
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1794
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3562
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3454
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3735
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5534
QualType getPointeeType() const
Definition TypeBase.h:3721
Describes a module or submodule.
Definition Module.h:246
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:258
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7993
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8049
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8138
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8107
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8061
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8101
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1854
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8113
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition Overload.h:1360
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1458
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1392
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1350
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1549
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1185
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition Overload.h:1368
SourceLocation getLocation() const
Definition Overload.h:1348
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1349
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1383
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3129
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3281
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3190
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3245
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3242
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3220
decls_iterator decls_begin() const
Definition ExprCXX.h:3222
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3233
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3255
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3251
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3343
decls_iterator decls_end() const
Definition ExprCXX.h:3225
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3239
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1805
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3059
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5188
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8509
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8520
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3628
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1231
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
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:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8585
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8552
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
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:8596
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8463
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8371
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8378
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4738
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3685
Represents a struct/union/class.
Definition Decl.h:4342
field_range fields() const
Definition Decl.h:4545
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3623
QualType getPointeeType() const
Definition TypeBase.h:3641
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:1605
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1650
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:212
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:459
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:400
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:406
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:312
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:10391
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6422
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6451
RAII class to control scope of DeferDiags.
Definition Sema.h:10114
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1382
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1417
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:12538
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12572
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
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:10132
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9402
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9429
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9414
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9410
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:415
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition Sema.h:1469
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:10474
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10477
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10483
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10481
@ AR_dependent
Definition Sema.h:1684
@ AR_accessible
Definition Sema.h:1682
@ AR_inaccessible
Definition Sema.h:1683
@ AR_delayed
Definition Sema.h:1685
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:2073
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:1711
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:1304
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:681
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:225
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition Sema.h:1514
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:758
ASTContext & getASTContext() const
Definition Sema.h:939
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:757
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
@ FRS_Success
Definition Sema.h:10862
@ FRS_DiagnosticIssued
Definition Sema.h:10864
@ FRS_NoViableFunction
Definition Sema.h:10863
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9395
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:10183
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:1208
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:3633
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:12236
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:932
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1302
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:1479
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9394
MemberPointerConversionDirection
Definition Sema.h:10315
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:10502
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:643
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:15596
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7044
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:1442
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:8248
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:14047
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:7542
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:13780
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:15551
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:124
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:6807
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6776
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:10307
SourceManager & SourceMgr
Definition Sema.h:1307
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1306
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:519
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:6484
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:1449
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:8730
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:362
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:339
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition Overload.h:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:367
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:329
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition Overload.h:384
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
StringRef getString() const
Definition Expr.h:1870
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:679
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3553
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2533
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isObjCBuiltinType() const
Definition TypeBase.h:8898
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
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:1965
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:789
bool isIncompleteArrayType() const
Definition TypeBase.h:8775
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isFloat16Type() const
Definition TypeBase.h:9043
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:726
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
bool isRValueReferenceType() const
Definition TypeBase.h:8700
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:8771
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9201
bool isArrayType() const
Definition TypeBase.h:8767
bool isCharType() const
Definition Type.cpp:2158
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9106
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2375
bool isPointerType() const
Definition TypeBase.h:8668
bool isArrayParameterType() const
Definition TypeBase.h:8783
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2618
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2121
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8868
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2194
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8855
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2840
bool isLValueReferenceType() const
Definition TypeBase.h:8696
bool isBitIntType() const
Definition TypeBase.h:8943
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2456
bool isAnyComplexType() const
Definition TypeBase.h:8803
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9094
bool isHalfType() const
Definition TypeBase.h:9038
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9016
bool isQueueT() const
Definition TypeBase.h:8924
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isObjCIdType() const
Definition TypeBase.h:8880
bool isMatrixType() const
Definition TypeBase.h:8831
bool isOverflowBehaviorType() const
Definition TypeBase.h:8839
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2558
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8916
bool isBFloat16Type() const
Definition TypeBase.h:9055
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
bool isVectorType() const
Definition TypeBase.h:8807
bool isObjCClassType() const
Definition TypeBase.h:8886
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2639
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8991
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:2285
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
bool isSamplerT() const
Definition TypeBase.h:8912
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:655
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1430
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:5151
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1406
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3391
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3460
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4127
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4235
QualType getBaseType() const
Definition ExprCXX.h:4209
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4219
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4200
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4245
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4239
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:641
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4240
QualType getElementType() const
Definition TypeBase.h:4239
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:246
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:61
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:859
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:887
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:896
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:879
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:883
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition Overload.h:924
@ ovl_fail_too_few_arguments
Definition Overload.h:861
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:903
@ ovl_fail_too_many_arguments
Definition Overload.h:860
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:911
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:892
@ ovl_fail_bad_deduction
Definition Overload.h:863
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:907
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:916
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:900
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:868
@ Comparison
A comparison.
Definition Sema.h:667
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1791
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1794
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1045
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:150
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:310
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:522
ConversionSet::const_iterator const_iterator
Definition Overload.h:558
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:523
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:549
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:607
QualType getFromType() const
Definition Overload.h:606
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
Extra information about a function prototype.
Definition TypeBase.h:5442
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5447
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1195
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1217
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1244
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1206
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1208
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1234
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:998
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:989
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1063
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1037
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1002
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:979
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:947
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:943
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:938
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1010
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:959
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:973
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1028
unsigned getNumParams() const
Definition Overload.h:1076
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1006
unsigned TookAddressOfOverload
Definition Overload.h:992
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
DeductionFailureInfo DeductionFailure
Definition Overload.h:1022
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:951
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1033
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10594
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10601
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13186
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13274
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13320
Abstract class used to diagnose incomplete types.
Definition Sema.h:8329
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:477
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.