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
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
169 };
170 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
171 return Rank[(int)Kind];
172}
173
192
193/// GetImplicitConversionName - Return the name of this kind of
194/// implicit conversion.
196 static const char *const Name[] = {
197 "No conversion",
198 "Lvalue-to-rvalue",
199 "Array-to-pointer",
200 "Function-to-pointer",
201 "Function pointer conversion",
202 "Qualification",
203 "Integral promotion",
204 "Floating point promotion",
205 "Complex promotion",
206 "Integral conversion",
207 "Floating conversion",
208 "Complex conversion",
209 "Floating-integral conversion",
210 "Pointer conversion",
211 "Pointer-to-member conversion",
212 "Boolean conversion",
213 "Compatible-types conversion",
214 "Derived-to-base conversion",
215 "Vector conversion",
216 "SVE Vector conversion",
217 "RVV Vector conversion",
218 "Vector splat",
219 "Complex-real conversion",
220 "Block Pointer conversion",
221 "Transparent Union Conversion",
222 "Writeback conversion",
223 "OpenCL Zero Event Conversion",
224 "OpenCL Zero Queue Conversion",
225 "C specific type conversion",
226 "Incompatible pointer conversion",
227 "Fixed point conversion",
228 "HLSL vector truncation",
229 "HLSL matrix truncation",
230 "Non-decaying array conversion",
231 "HLSL vector splat",
232 "HLSL matrix splat",
233 };
234 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
235 return Name[Kind];
236}
237
238/// StandardConversionSequence - Set the standard conversion
239/// sequence to the identity conversion.
257
258/// getRank - Retrieve the rank of this standard conversion sequence
259/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260/// implicit conversions.
273
274/// isPointerConversionToBool - Determines whether this conversion is
275/// a conversion of a pointer or pointer-to-member to bool. This is
276/// used as part of the ranking of standard conversion sequences
277/// (C++ 13.3.3.2p4).
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
289 return true;
290
291 return false;
292}
293
294/// isPointerConversionToVoidPointer - Determines whether this
295/// conversion is a conversion of a pointer to a void pointer. This is
296/// used as part of the ranking of standard conversion sequences (C++
297/// 13.3.3.2p4).
298bool
301 QualType FromType = getFromType();
302 QualType ToType = getToType(1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
308 FromType = Context.getArrayDecayedType(FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315}
316
317/// Skip any implicit casts which could be either part of a narrowing conversion
318/// or after one in an implicit conversion.
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
326 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
327 EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349}
350
351/// Check if this standard conversion sequence represents a narrowing
352/// conversion, according to C++11 [dcl.init.list]p7.
353///
354/// \param Ctx The AST context.
355/// \param Converted The result of applying this standard conversion sequence.
356/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357/// value of the expression prior to the narrowing conversion.
358/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359/// type of the expression prior to the narrowing conversion.
360/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361/// from floating point types to integral types should be ignored.
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(0);
371 QualType ToType = getToType(1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (const auto *ED = ToType->getAsEnumDecl())
377 ToType = ED->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
414 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
415 llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 llvm::APFloat::opStatus Status = Result.convertToInteger(
420 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
421 // If the converted-back integer has unspecified value, or if the
422 // resulting value is different, this was a narrowing conversion.
423 if (Status == llvm::APFloat::opInvalidOp ||
424 *IntConstantValue != ConvertedValue) {
425 ConstantValue = APValue(*IntConstantValue);
426 ConstantType = Initializer->getType();
428 }
429 } else {
430 // Variables are always narrowings.
432 }
433 }
434 return NK_Not_Narrowing;
435
436 // -- from long double to double or float, or from double to float, except
437 // where the source is a constant expression and the actual value after
438 // conversion is within the range of values that can be represented (even
439 // if it cannot be represented exactly), or
441 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
442 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
443 // FromType is larger than ToType.
444 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
445
446 // If it's value-dependent, we can't tell whether it's narrowing.
447 if (Initializer->isValueDependent())
449
451 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
452 ((Ctx.getLangOpts().CPlusPlus &&
453 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
454 // Constant!
455 if (Ctx.getLangOpts().C23)
456 ConstantValue = R.Val;
457 assert(ConstantValue.isFloat());
458 llvm::APFloat FloatVal = ConstantValue.getFloat();
459 // Convert the source value into the target type.
460 bool ignored;
461 llvm::APFloat Converted = FloatVal;
462 llvm::APFloat::opStatus ConvertStatus =
463 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
464 llvm::APFloat::rmNearestTiesToEven, &ignored);
465 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
466 llvm::APFloat::rmNearestTiesToEven, &ignored);
467 if (Ctx.getLangOpts().C23) {
468 if (FloatVal.isNaN() && Converted.isNaN() &&
469 !FloatVal.isSignaling() && !Converted.isSignaling()) {
470 // Quiet NaNs are considered the same value, regardless of
471 // payloads.
472 return NK_Not_Narrowing;
473 }
474 // For normal values, check exact equality.
475 if (!Converted.bitwiseIsEqual(FloatVal)) {
476 ConstantType = Initializer->getType();
478 }
479 } else {
480 // If there was no overflow, the source value is within the range of
481 // values that can be represented.
482 if (ConvertStatus & llvm::APFloat::opOverflow) {
483 ConstantType = Initializer->getType();
485 }
486 }
487 } else {
489 }
490 }
491 return NK_Not_Narrowing;
492
493 // -- from an integer type or unscoped enumeration type to an integer type
494 // that cannot represent all the values of the original type, except where
495 // (CWG2627) -- the source is a bit-field whose width w is less than that
496 // of its type (or, for an enumeration type, its underlying type) and the
497 // target type can represent all the values of a hypothetical extended
498 // integer type with width w and with the same signedness as the original
499 // type or
500 // -- the source is a constant expression and the actual value after
501 // conversion will fit into the target type and will produce the original
502 // value when converted back to the original type.
504 IntegralConversion: {
505 assert(FromType->isIntegralOrUnscopedEnumerationType());
506 assert(ToType->isIntegralOrUnscopedEnumerationType());
507 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
508 unsigned FromWidth = Ctx.getIntWidth(FromType);
509 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
510 const unsigned ToWidth = Ctx.getIntWidth(ToType);
511
512 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
513 bool ToSigned, unsigned ToWidth) {
514 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
515 !(FromSigned && !ToSigned);
516 };
517
518 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
519 return NK_Not_Narrowing;
520
521 // Not all values of FromType can be represented in ToType.
522 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
523
524 bool DependentBitField = false;
525 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
526 if (BitField->getBitWidth()->isValueDependent())
527 DependentBitField = true;
528 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
529 BitFieldWidth < FromWidth) {
530 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // The initializer will be truncated to the bit-field width
534 FromWidth = BitFieldWidth;
535 }
536 }
537
538 // If it's value-dependent, we can't tell whether it's narrowing.
539 if (Initializer->isValueDependent())
541
542 std::optional<llvm::APSInt> OptInitializerValue =
543 Initializer->getIntegerConstantExpr(Ctx);
544 if (!OptInitializerValue) {
545 // If the bit-field width was dependent, it might end up being small
546 // enough to fit in the target type (unless the target type is unsigned
547 // and the source type is signed, in which case it will never fit)
548 if (DependentBitField && !(FromSigned && !ToSigned))
550
551 // Otherwise, such a conversion is always narrowing
553 }
554 llvm::APSInt &InitializerValue = *OptInitializerValue;
555 bool Narrowing = false;
556 if (FromWidth < ToWidth) {
557 // Negative -> unsigned is narrowing. Otherwise, more bits is never
558 // narrowing.
559 if (InitializerValue.isSigned() && InitializerValue.isNegative())
560 Narrowing = true;
561 } else {
562 // Add a bit to the InitializerValue so we don't have to worry about
563 // signed vs. unsigned comparisons.
564 InitializerValue =
565 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
566 // Convert the initializer to and from the target width and signed-ness.
567 llvm::APSInt ConvertedValue = InitializerValue;
568 ConvertedValue = ConvertedValue.trunc(ToWidth);
569 ConvertedValue.setIsSigned(ToSigned);
570 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
571 ConvertedValue.setIsSigned(InitializerValue.isSigned());
572 // If the result is different, this was a narrowing conversion.
573 if (ConvertedValue != InitializerValue)
574 Narrowing = true;
575 }
576 if (Narrowing) {
577 ConstantType = Initializer->getType();
578 ConstantValue = APValue(InitializerValue);
580 }
581
582 return NK_Not_Narrowing;
583 }
584 case ICK_Complex_Real:
585 if (FromType->isComplexType() && !ToType->isComplexType())
586 return NK_Type_Narrowing;
587 return NK_Not_Narrowing;
588
590 if (Ctx.getLangOpts().C23) {
591 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
593 if (Initializer->EvaluateAsRValue(R, Ctx)) {
594 ConstantValue = R.Val;
595 assert(ConstantValue.isFloat());
596 llvm::APFloat FloatVal = ConstantValue.getFloat();
597 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
598 // value, the unqualified versions of the type of the initializer and
599 // the corresponding real type of the object declared shall be
600 // compatible.
601 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
602 ConstantType = Initializer->getType();
604 }
605 }
606 }
607 return NK_Not_Narrowing;
608 default:
609 // Other kinds of conversions are not narrowings.
610 return NK_Not_Narrowing;
611 }
612}
613
614/// dump - Print this standard conversion sequence to standard
615/// error. Useful for debugging overloading issues.
616LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
617 raw_ostream &OS = llvm::errs();
618 bool PrintedSomething = false;
619 if (First != ICK_Identity) {
621 PrintedSomething = true;
622 }
623
624 if (Second != ICK_Identity) {
625 if (PrintedSomething) {
626 OS << " -> ";
627 }
629
630 if (CopyConstructor) {
631 OS << " (by copy constructor)";
632 } else if (DirectBinding) {
633 OS << " (direct reference binding)";
634 } else if (ReferenceBinding) {
635 OS << " (reference binding)";
636 }
637 PrintedSomething = true;
638 }
639
640 if (Third != ICK_Identity) {
641 if (PrintedSomething) {
642 OS << " -> ";
643 }
645 PrintedSomething = true;
646 }
647
648 if (!PrintedSomething) {
649 OS << "No conversions required";
650 }
651}
652
653/// dump - Print this user-defined conversion sequence to standard
654/// error. Useful for debugging overloading issues.
656 raw_ostream &OS = llvm::errs();
657 if (Before.First || Before.Second || Before.Third) {
658 Before.dump();
659 OS << " -> ";
660 }
662 OS << '\'' << *ConversionFunction << '\'';
663 else
664 OS << "aggregate initialization";
665 if (After.First || After.Second || After.Third) {
666 OS << " -> ";
667 After.dump();
668 }
669}
670
671/// dump - Print this implicit conversion sequence to standard
672/// error. Useful for debugging overloading issues.
674 raw_ostream &OS = llvm::errs();
676 OS << "Worst list element conversion: ";
677 switch (ConversionKind) {
679 OS << "Standard conversion: ";
680 Standard.dump();
681 break;
683 OS << "User-defined conversion: ";
684 UserDefined.dump();
685 break;
687 OS << "Ellipsis conversion";
688 break;
690 OS << "Ambiguous conversion";
691 break;
692 case BadConversion:
693 OS << "Bad conversion";
694 break;
695 }
696
697 OS << "\n";
698}
699
703
705 conversions().~ConversionSet();
706}
707
708void
714
715namespace {
716 // Structure used by DeductionFailureInfo to store
717 // template argument information.
718 struct DFIArguments {
719 TemplateArgument FirstArg;
720 TemplateArgument SecondArg;
721 };
722 // Structure used by DeductionFailureInfo to store
723 // template parameter and template argument information.
724 struct DFIParamWithArguments : DFIArguments {
725 TemplateParameter Param;
726 };
727 // Structure used by DeductionFailureInfo to store template argument
728 // information and the index of the problematic call argument.
729 struct DFIDeducedMismatchArgs : DFIArguments {
730 TemplateArgumentList *TemplateArgs;
731 unsigned CallArgIndex;
732 };
733 // Structure used by DeductionFailureInfo to store information about
734 // unsatisfied constraints.
735 struct CNSInfo {
736 TemplateArgumentList *TemplateArgs;
737 ConstraintSatisfaction Satisfaction;
738 };
739}
740
741/// Convert from Sema's representation of template deduction information
742/// to the form used in overload-candidate information.
746 TemplateDeductionInfo &Info) {
748 Result.Result = static_cast<unsigned>(TDK);
749 Result.HasDiagnostic = false;
750 switch (TDK) {
757 Result.Data = nullptr;
758 break;
759
762 Result.Data = Info.Param.getOpaqueValue();
763 break;
764
767 // FIXME: Should allocate from normal heap so that we can free this later.
768 auto *Saved = new (Context) DFIDeducedMismatchArgs;
769 Saved->FirstArg = Info.FirstArg;
770 Saved->SecondArg = Info.SecondArg;
771 Saved->TemplateArgs = Info.takeSugared();
772 Saved->CallArgIndex = Info.CallArgIndex;
773 Result.Data = Saved;
774 break;
775 }
776
778 // FIXME: Should allocate from normal heap so that we can free this later.
779 DFIArguments *Saved = new (Context) DFIArguments;
780 Saved->FirstArg = Info.FirstArg;
781 Saved->SecondArg = Info.SecondArg;
782 Result.Data = Saved;
783 break;
784 }
785
787 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
790 // FIXME: Should allocate from normal heap so that we can free this later.
791 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
792 Saved->Param = Info.Param;
793 Saved->FirstArg = Info.FirstArg;
794 Saved->SecondArg = Info.SecondArg;
795 Result.Data = Saved;
796 break;
797 }
798
800 Result.Data = Info.takeSugared();
801 if (Info.hasSFINAEDiagnostic()) {
805 Result.HasDiagnostic = true;
806 }
807 break;
808
810 CNSInfo *Saved = new (Context) CNSInfo;
811 Saved->TemplateArgs = Info.takeSugared();
812 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
813 Result.Data = Saved;
814 break;
815 }
816
820 llvm_unreachable("not a deduction failure");
821 }
822
823 return Result;
824}
825
827 switch (static_cast<TemplateDeductionResult>(Result)) {
837 break;
838
845 // FIXME: Destroy the data?
846 Data = nullptr;
847 break;
848
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
859 // FIXME: Destroy the template argument list?
860 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
861 Data = nullptr;
863 Diag->~PartialDiagnosticAt();
864 HasDiagnostic = false;
865 }
866 break;
867
868 // Unhandled
871 break;
872 }
873}
874
876 if (HasDiagnostic)
877 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
878 return nullptr;
879}
880
914
950
982
1014
1016 switch (static_cast<TemplateDeductionResult>(Result)) {
1019 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1020
1021 default:
1022 return std::nullopt;
1023 }
1024}
1025
1027 const FunctionDecl *Y) {
1028 if (!X || !Y)
1029 return false;
1030 if (X->getNumParams() != Y->getNumParams())
1031 return false;
1032 // FIXME: when do rewritten comparison operators
1033 // with explicit object parameters correspond?
1034 // https://cplusplus.github.io/CWG/issues/2797.html
1035 for (unsigned I = 0; I < X->getNumParams(); ++I)
1036 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1037 Y->getParamDecl(I)->getType()))
1038 return false;
1039 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1040 auto *FTY = Y->getDescribedFunctionTemplate();
1041 if (!FTY)
1042 return false;
1043 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1044 FTY->getTemplateParameters()))
1045 return false;
1046 }
1047 return true;
1048}
1049
1051 Expr *FirstOperand, FunctionDecl *EqFD) {
1052 assert(EqFD->getOverloadedOperator() ==
1053 OverloadedOperatorKind::OO_EqualEqual);
1054 // C++2a [over.match.oper]p4:
1055 // A non-template function or function template F named operator== is a
1056 // rewrite target with first operand o unless a search for the name operator!=
1057 // in the scope S from the instantiation context of the operator expression
1058 // finds a function or function template that would correspond
1059 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1060 // scope of the class type of o if F is a class member, and the namespace
1061 // scope of which F is a member otherwise. A function template specialization
1062 // named operator== is a rewrite target if its function template is a rewrite
1063 // target.
1065 OverloadedOperatorKind::OO_ExclaimEqual);
1066 if (isa<CXXMethodDecl>(EqFD)) {
1067 // If F is a class member, search scope is class type of first operand.
1068 QualType RHS = FirstOperand->getType();
1069 auto *RHSRec = RHS->getAsCXXRecordDecl();
1070 if (!RHSRec)
1071 return true;
1072 LookupResult Members(S, NotEqOp, OpLoc,
1074 S.LookupQualifiedName(Members, RHSRec);
1075 Members.suppressAccessDiagnostics();
1076 for (NamedDecl *Op : Members)
1077 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1078 return false;
1079 return true;
1080 }
1081 // Otherwise the search scope is the namespace scope of which F is a member.
1082 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1083 auto *NotEqFD = Op->getAsFunction();
1084 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1085 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1086 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1088 cast<Decl>(Op->getLexicalDeclContext())))
1089 return false;
1090 }
1091 return true;
1092}
1093
1095 OverloadedOperatorKind Op) const {
1097 return false;
1098 return Op == OO_EqualEqual || Op == OO_Spaceship;
1099}
1100
1102 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1103 auto Op = FD->getOverloadedOperator();
1104 if (!allowsReversed(Op))
1105 return false;
1106 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1107 assert(OriginalArgs.size() == 2);
1109 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1110 return false;
1111 }
1112 // Don't bother adding a reversed candidate that can never be a better
1113 // match than the non-reversed version.
1114 return FD->getNumNonObjectParams() != 2 ||
1116 FD->getParamDecl(1)->getType()) ||
1117 FD->hasAttr<EnableIfAttr>();
1118}
1119
1120void OverloadCandidateSet::destroyCandidates() {
1121 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1122 for (auto &C : i->Conversions)
1123 C.~ImplicitConversionSequence();
1124 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1125 i->DeductionFailure.Destroy();
1126 }
1127}
1128
1130 destroyCandidates();
1131 SlabAllocator.Reset();
1132 NumInlineBytesUsed = 0;
1133 Candidates.clear();
1134 Functions.clear();
1135 Kind = CSK;
1136 FirstDeferredCandidate = nullptr;
1137 DeferredCandidatesCount = 0;
1138 HasDeferredTemplateConstructors = false;
1139 ResolutionByPerfectCandidateIsDisabled = false;
1140}
1141
1142namespace {
1143 class UnbridgedCastsSet {
1144 struct Entry {
1145 Expr **Addr;
1146 Expr *Saved;
1147 };
1148 SmallVector<Entry, 2> Entries;
1149
1150 public:
1151 void save(Sema &S, Expr *&E) {
1152 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1153 Entry entry = { &E, E };
1154 Entries.push_back(entry);
1155 E = S.ObjC().stripARCUnbridgedCast(E);
1156 }
1157
1158 void restore() {
1159 for (SmallVectorImpl<Entry>::iterator
1160 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1161 *i->Addr = i->Saved;
1162 }
1163 };
1164}
1165
1166/// checkPlaceholderForOverload - Do any interesting placeholder-like
1167/// preprocessing on the given expression.
1168///
1169/// \param unbridgedCasts a collection to which to add unbridged casts;
1170/// without this, they will be immediately diagnosed as errors
1171///
1172/// Return true on unrecoverable error.
1173static bool
1175 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1176 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1177 // We can't handle overloaded expressions here because overload
1178 // resolution might reasonably tweak them.
1179 if (placeholder->getKind() == BuiltinType::Overload) return false;
1180
1181 // If the context potentially accepts unbridged ARC casts, strip
1182 // the unbridged cast and add it to the collection for later restoration.
1183 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1184 unbridgedCasts) {
1185 unbridgedCasts->save(S, E);
1186 return false;
1187 }
1188
1189 // Go ahead and check everything else.
1190 ExprResult result = S.CheckPlaceholderExpr(E);
1191 if (result.isInvalid())
1192 return true;
1193
1194 E = result.get();
1195 return false;
1196 }
1197
1198 // Nothing to do.
1199 return false;
1200}
1201
1202/// checkArgPlaceholdersForOverload - Check a set of call operands for
1203/// placeholders.
1205 UnbridgedCastsSet &unbridged) {
1206 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1207 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1208 return true;
1209
1210 return false;
1211}
1212
1214 const LookupResult &Old, NamedDecl *&Match,
1215 bool NewIsUsingDecl) {
1216 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1217 I != E; ++I) {
1218 NamedDecl *OldD = *I;
1219
1220 bool OldIsUsingDecl = false;
1221 if (isa<UsingShadowDecl>(OldD)) {
1222 OldIsUsingDecl = true;
1223
1224 // We can always introduce two using declarations into the same
1225 // context, even if they have identical signatures.
1226 if (NewIsUsingDecl) continue;
1227
1228 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1229 }
1230
1231 // A using-declaration does not conflict with another declaration
1232 // if one of them is hidden.
1233 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1234 continue;
1235
1236 // If either declaration was introduced by a using declaration,
1237 // we'll need to use slightly different rules for matching.
1238 // Essentially, these rules are the normal rules, except that
1239 // function templates hide function templates with different
1240 // return types or template parameter lists.
1241 bool UseMemberUsingDeclRules =
1242 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1243 !New->getFriendObjectKind();
1244
1245 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1246 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1247 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1249 continue;
1250 }
1251
1252 if (!isa<FunctionTemplateDecl>(OldD) &&
1253 !shouldLinkPossiblyHiddenDecl(*I, New))
1254 continue;
1255
1256 Match = *I;
1257 return OverloadKind::Match;
1258 }
1259
1260 // Builtins that have custom typechecking or have a reference should
1261 // not be overloadable or redeclarable.
1262 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1263 Match = *I;
1265 }
1266 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1267 // We can overload with these, which can show up when doing
1268 // redeclaration checks for UsingDecls.
1269 assert(Old.getLookupKind() == LookupUsingDeclName);
1270 } else if (isa<TagDecl>(OldD)) {
1271 // We can always overload with tags by hiding them.
1272 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1273 // Optimistically assume that an unresolved using decl will
1274 // overload; if it doesn't, we'll have to diagnose during
1275 // template instantiation.
1276 //
1277 // Exception: if the scope is dependent and this is not a class
1278 // member, the using declaration can only introduce an enumerator.
1279 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1280 Match = *I;
1282 }
1283 } else {
1284 // (C++ 13p1):
1285 // Only function declarations can be overloaded; object and type
1286 // declarations cannot be overloaded.
1287 Match = *I;
1289 }
1290 }
1291
1292 // C++ [temp.friend]p1:
1293 // For a friend function declaration that is not a template declaration:
1294 // -- if the name of the friend is a qualified or unqualified template-id,
1295 // [...], otherwise
1296 // -- if the name of the friend is a qualified-id and a matching
1297 // non-template function is found in the specified class or namespace,
1298 // the friend declaration refers to that function, otherwise,
1299 // -- if the name of the friend is a qualified-id and a matching function
1300 // template is found in the specified class or namespace, the friend
1301 // declaration refers to the deduced specialization of that function
1302 // template, otherwise
1303 // -- the name shall be an unqualified-id [...]
1304 // If we get here for a qualified friend declaration, we've just reached the
1305 // third bullet. If the type of the friend is dependent, skip this lookup
1306 // until instantiation.
1307 if (New->getFriendObjectKind() && New->getQualifier() &&
1308 !New->getDescribedFunctionTemplate() &&
1309 !New->getDependentSpecializationInfo() &&
1310 !New->getType()->isDependentType()) {
1311 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1312 TemplateSpecResult.addAllDecls(Old);
1313 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1314 /*QualifiedFriend*/true)) {
1315 New->setInvalidDecl();
1317 }
1318
1319 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1320 return OverloadKind::Match;
1321 }
1322
1324}
1325
1326template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1327 assert(D && "function decl should not be null");
1328 if (auto *A = D->getAttr<AttrT>())
1329 return !A->isImplicit();
1330 return false;
1331}
1332
1334 FunctionDecl *Old,
1335 bool UseMemberUsingDeclRules,
1336 bool ConsiderCudaAttrs,
1337 bool UseOverrideRules = false) {
1338 // C++ [basic.start.main]p2: This function shall not be overloaded.
1339 if (New->isMain())
1340 return false;
1341
1342 // MSVCRT user defined entry points cannot be overloaded.
1343 if (New->isMSVCRTEntryPoint())
1344 return false;
1345
1346 NamedDecl *OldDecl = Old;
1347 NamedDecl *NewDecl = New;
1349 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1350
1351 // C++ [temp.fct]p2:
1352 // A function template can be overloaded with other function templates
1353 // and with normal (non-template) functions.
1354 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1355 return true;
1356
1357 // Is the function New an overload of the function Old?
1358 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1359 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1360
1361 // Compare the signatures (C++ 1.3.10) of the two functions to
1362 // determine whether they are overloads. If we find any mismatch
1363 // in the signature, they are overloads.
1364
1365 // If either of these functions is a K&R-style function (no
1366 // prototype), then we consider them to have matching signatures.
1367 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1369 return false;
1370
1371 const auto *OldType = cast<FunctionProtoType>(OldQType);
1372 const auto *NewType = cast<FunctionProtoType>(NewQType);
1373
1374 // The signature of a function includes the types of its
1375 // parameters (C++ 1.3.10), which includes the presence or absence
1376 // of the ellipsis; see C++ DR 357).
1377 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1378 return true;
1379
1380 // For member-like friends, the enclosing class is part of the signature.
1381 if ((New->isMemberLikeConstrainedFriend() ||
1383 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1384 return true;
1385
1386 // Compare the parameter lists.
1387 // This can only be done once we have establish that friend functions
1388 // inhabit the same context, otherwise we might tried to instantiate
1389 // references to non-instantiated entities during constraint substitution.
1390 // GH78101.
1391 if (NewTemplate) {
1392 OldDecl = OldTemplate;
1393 NewDecl = NewTemplate;
1394 // C++ [temp.over.link]p4:
1395 // The signature of a function template consists of its function
1396 // signature, its return type and its template parameter list. The names
1397 // of the template parameters are significant only for establishing the
1398 // relationship between the template parameters and the rest of the
1399 // signature.
1400 //
1401 // We check the return type and template parameter lists for function
1402 // templates first; the remaining checks follow.
1403 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1404 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1405 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1406 bool SameReturnType = SemaRef.Context.hasSameType(
1407 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1408 // FIXME(GH58571): Match template parameter list even for non-constrained
1409 // template heads. This currently ensures that the code prior to C++20 is
1410 // not newly broken.
1411 bool ConstraintsInTemplateHead =
1414 // C++ [namespace.udecl]p11:
1415 // The set of declarations named by a using-declarator that inhabits a
1416 // class C does not include member functions and member function
1417 // templates of a base class that "correspond" to (and thus would
1418 // conflict with) a declaration of a function or function template in
1419 // C.
1420 // Comparing return types is not required for the "correspond" check to
1421 // decide whether a member introduced by a shadow declaration is hidden.
1422 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1423 !SameTemplateParameterList)
1424 return true;
1425 if (!UseMemberUsingDeclRules &&
1426 (!SameTemplateParameterList || !SameReturnType))
1427 return true;
1428 }
1429
1430 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1431 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1432
1433 int OldParamsOffset = 0;
1434 int NewParamsOffset = 0;
1435
1436 // When determining if a method is an overload from a base class, act as if
1437 // the implicit object parameter are of the same type.
1438
1439 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1441 auto ThisType = M->getFunctionObjectParameterReferenceType();
1442 if (ThisType.isConstQualified())
1443 Q.removeConst();
1444 return Q;
1445 }
1446
1447 // We do not allow overloading based off of '__restrict'.
1448 Q.removeRestrict();
1449
1450 // We may not have applied the implicit const for a constexpr member
1451 // function yet (because we haven't yet resolved whether this is a static
1452 // or non-static member function). Add it now, on the assumption that this
1453 // is a redeclaration of OldMethod.
1454 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1455 (M->isConstexpr() || M->isConsteval()) &&
1456 !isa<CXXConstructorDecl>(NewMethod))
1457 Q.addConst();
1458 return Q;
1459 };
1460
1461 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1462 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1463 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1464
1465 if (OldMethod->isExplicitObjectMemberFunction()) {
1466 BS.Quals.removeVolatile();
1467 DS.Quals.removeVolatile();
1468 }
1469
1470 return BS.Quals == DS.Quals;
1471 };
1472
1473 auto CompareType = [&](QualType Base, QualType D) {
1474 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1475 auto DS = D.getNonReferenceType().getCanonicalType().split();
1476
1477 if (!AreQualifiersEqual(BS, DS))
1478 return false;
1479
1480 if (OldMethod->isImplicitObjectMemberFunction() &&
1481 OldMethod->getParent() != NewMethod->getParent()) {
1482 CanQualType ParentType =
1483 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1484 if (ParentType.getTypePtr() != BS.Ty)
1485 return false;
1486 BS.Ty = DS.Ty;
1487 }
1488
1489 // FIXME: should we ignore some type attributes here?
1490 if (BS.Ty != DS.Ty)
1491 return false;
1492
1493 if (Base->isLValueReferenceType())
1494 return D->isLValueReferenceType();
1495 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1496 };
1497
1498 // If the function is a class member, its signature includes the
1499 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1500 auto DiagnoseInconsistentRefQualifiers = [&]() {
1501 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1502 return false;
1503 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1504 return false;
1505 if (OldMethod->isExplicitObjectMemberFunction() ||
1506 NewMethod->isExplicitObjectMemberFunction())
1507 return false;
1508 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1509 NewMethod->getRefQualifier() == RQ_None)) {
1510 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1511 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1512 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1513 return true;
1514 }
1515 return false;
1516 };
1517
1518 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1519 OldParamsOffset++;
1520 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1521 NewParamsOffset++;
1522
1523 if (OldType->getNumParams() - OldParamsOffset !=
1524 NewType->getNumParams() - NewParamsOffset ||
1526 {OldType->param_type_begin() + OldParamsOffset,
1527 OldType->param_type_end()},
1528 {NewType->param_type_begin() + NewParamsOffset,
1529 NewType->param_type_end()},
1530 nullptr)) {
1531 return true;
1532 }
1533
1534 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1535 !NewMethod->isStatic()) {
1536 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1537 const CXXMethodDecl *New) {
1538 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1539 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1540
1541 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1542 return F->getRefQualifier() == RQ_None &&
1543 !F->isExplicitObjectMemberFunction();
1544 };
1545
1546 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1547 CompareType(OldObjectType.getNonReferenceType(),
1548 NewObjectType.getNonReferenceType()))
1549 return true;
1550 return CompareType(OldObjectType, NewObjectType);
1551 }(OldMethod, NewMethod);
1552
1553 if (!HaveCorrespondingObjectParameters) {
1554 if (DiagnoseInconsistentRefQualifiers())
1555 return true;
1556 // CWG2554
1557 // and, if at least one is an explicit object member function, ignoring
1558 // object parameters
1559 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1560 !OldMethod->isExplicitObjectMemberFunction()))
1561 return true;
1562 }
1563 }
1564
1565 if (!UseOverrideRules &&
1566 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1567 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1568 OldRC = Old->getTrailingRequiresClause();
1569 if (!NewRC != !OldRC)
1570 return true;
1571 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1572 return true;
1573 if (NewRC &&
1574 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1575 NewDecl, NewRC.ConstraintExpr))
1576 return true;
1577 }
1578
1579 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1580 NewMethod->isImplicitObjectMemberFunction()) {
1581 if (DiagnoseInconsistentRefQualifiers())
1582 return true;
1583 }
1584
1585 // Though pass_object_size is placed on parameters and takes an argument, we
1586 // consider it to be a function-level modifier for the sake of function
1587 // identity. Either the function has one or more parameters with
1588 // pass_object_size or it doesn't.
1591 return true;
1592
1593 // enable_if attributes are an order-sensitive part of the signature.
1595 NewI = New->specific_attr_begin<EnableIfAttr>(),
1596 NewE = New->specific_attr_end<EnableIfAttr>(),
1597 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1598 OldE = Old->specific_attr_end<EnableIfAttr>();
1599 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1600 if (NewI == NewE || OldI == OldE)
1601 return true;
1602 llvm::FoldingSetNodeID NewID, OldID;
1603 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1604 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1605 if (NewID != OldID)
1606 return true;
1607 }
1608
1609 // At this point, it is known that the two functions have the same signature.
1610 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1611 // Don't allow overloading of destructors. (In theory we could, but it
1612 // would be a giant change to clang.)
1614 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1615 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1616 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1617 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1618 "Unexpected invalid target.");
1619
1620 // Allow overloading of functions with same signature and different CUDA
1621 // target attributes.
1622 if (NewTarget != OldTarget) {
1623 // Special case: non-constexpr function is allowed to override
1624 // constexpr virtual function
1625 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1626 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1631 return false;
1632 }
1633 return true;
1634 }
1635 }
1636 }
1637 }
1638
1639 // The signatures match; this is not an overload.
1640 return false;
1641}
1642
1644 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1645 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1646 ConsiderCudaAttrs);
1647}
1648
1650 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1651 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1652 /*UseMemberUsingDeclRules=*/false,
1653 /*ConsiderCudaAttrs=*/true,
1654 /*UseOverrideRules=*/true);
1655}
1656
1657/// Tries a user-defined conversion from From to ToType.
1658///
1659/// Produces an implicit conversion sequence for when a standard conversion
1660/// is not an option. See TryImplicitConversion for more information.
1663 bool SuppressUserConversions,
1664 AllowedExplicit AllowExplicit,
1665 bool InOverloadResolution,
1666 bool CStyle,
1667 bool AllowObjCWritebackConversion,
1668 bool AllowObjCConversionOnExplicit) {
1670
1671 if (SuppressUserConversions) {
1672 // We're not in the case above, so there is no conversion that
1673 // we can perform.
1675 return ICS;
1676 }
1677
1678 // Attempt user-defined conversion.
1679 OverloadCandidateSet Conversions(From->getExprLoc(),
1681 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1682 Conversions, AllowExplicit,
1683 AllowObjCConversionOnExplicit)) {
1684 case OR_Success:
1685 case OR_Deleted:
1686 ICS.setUserDefined();
1687 // C++ [over.ics.user]p4:
1688 // A conversion of an expression of class type to the same class
1689 // type is given Exact Match rank, and a conversion of an
1690 // expression of class type to a base class of that type is
1691 // given Conversion rank, in spite of the fact that a copy
1692 // constructor (i.e., a user-defined conversion function) is
1693 // called for those cases.
1695 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1696 QualType FromType;
1697 SourceLocation FromLoc;
1698 // C++11 [over.ics.list]p6, per DR2137:
1699 // C++17 [over.ics.list]p6:
1700 // If C is not an initializer-list constructor and the initializer list
1701 // has a single element of type cv U, where U is X or a class derived
1702 // from X, the implicit conversion sequence has Exact Match rank if U is
1703 // X, or Conversion rank if U is derived from X.
1704 bool FromListInit = false;
1705 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1706 InitList && InitList->getNumInits() == 1 &&
1708 const Expr *SingleInit = InitList->getInit(0);
1709 FromType = SingleInit->getType();
1710 FromLoc = SingleInit->getBeginLoc();
1711 FromListInit = true;
1712 } else {
1713 FromType = From->getType();
1714 FromLoc = From->getBeginLoc();
1715 }
1716 QualType FromCanon =
1718 QualType ToCanon
1720 if ((FromCanon == ToCanon ||
1721 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1722 // Turn this into a "standard" conversion sequence, so that it
1723 // gets ranked with standard conversion sequences.
1725 ICS.setStandard();
1727 ICS.Standard.setFromType(FromType);
1728 ICS.Standard.setAllToTypes(ToType);
1729 ICS.Standard.FromBracedInitList = FromListInit;
1732 if (ToCanon != FromCanon)
1734 }
1735 }
1736 break;
1737
1738 case OR_Ambiguous:
1739 ICS.setAmbiguous();
1740 ICS.Ambiguous.setFromType(From->getType());
1741 ICS.Ambiguous.setToType(ToType);
1742 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1743 Cand != Conversions.end(); ++Cand)
1744 if (Cand->Best)
1745 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1746 break;
1747
1748 // Fall through.
1751 break;
1752 }
1753
1754 return ICS;
1755}
1756
1757/// TryImplicitConversion - Attempt to perform an implicit conversion
1758/// from the given expression (Expr) to the given type (ToType). This
1759/// function returns an implicit conversion sequence that can be used
1760/// to perform the initialization. Given
1761///
1762/// void f(float f);
1763/// void g(int i) { f(i); }
1764///
1765/// this routine would produce an implicit conversion sequence to
1766/// describe the initialization of f from i, which will be a standard
1767/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1768/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1769//
1770/// Note that this routine only determines how the conversion can be
1771/// performed; it does not actually perform the conversion. As such,
1772/// it will not produce any diagnostics if no conversion is available,
1773/// but will instead return an implicit conversion sequence of kind
1774/// "BadConversion".
1775///
1776/// If @p SuppressUserConversions, then user-defined conversions are
1777/// not permitted.
1778/// If @p AllowExplicit, then explicit user-defined conversions are
1779/// permitted.
1780///
1781/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1782/// writeback conversion, which allows __autoreleasing id* parameters to
1783/// be initialized with __strong id* or __weak id* arguments.
1784static ImplicitConversionSequence
1786 bool SuppressUserConversions,
1787 AllowedExplicit AllowExplicit,
1788 bool InOverloadResolution,
1789 bool CStyle,
1790 bool AllowObjCWritebackConversion,
1791 bool AllowObjCConversionOnExplicit) {
1793 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1794 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1795 ICS.setStandard();
1796 return ICS;
1797 }
1798
1799 if (!S.getLangOpts().CPlusPlus) {
1801 return ICS;
1802 }
1803
1804 // C++ [over.ics.user]p4:
1805 // A conversion of an expression of class type to the same class
1806 // type is given Exact Match rank, and a conversion of an
1807 // expression of class type to a base class of that type is
1808 // given Conversion rank, in spite of the fact that a copy/move
1809 // constructor (i.e., a user-defined conversion function) is
1810 // called for those cases.
1811 QualType FromType = From->getType();
1812 if (ToType->isRecordType() &&
1813 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1814 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1815 ICS.setStandard();
1817 ICS.Standard.setFromType(FromType);
1818 ICS.Standard.setAllToTypes(ToType);
1819
1820 // We don't actually check at this point whether there is a valid
1821 // copy/move constructor, since overloading just assumes that it
1822 // exists. When we actually perform initialization, we'll find the
1823 // appropriate constructor to copy the returned object, if needed.
1824 ICS.Standard.CopyConstructor = nullptr;
1825
1826 // Determine whether this is considered a derived-to-base conversion.
1827 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1829
1830 return ICS;
1831 }
1832
1833 if (S.getLangOpts().HLSL) {
1834 // Handle conversion of the HLSL resource types.
1835 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1836 if (FromTy->isHLSLAttributedResourceType()) {
1837 // Attributed resource types can convert to other attributed
1838 // resource types with the same attributes and contained types,
1839 // or to __hlsl_resource_t without any attributes.
1840 bool CanConvert = false;
1841 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1842 if (ToTy->isHLSLAttributedResourceType()) {
1843 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1844 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1845 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1846 FromResType->getWrappedType()) &&
1847 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1848 FromResType->getContainedType()) &&
1849 ToResType->getAttrs() == FromResType->getAttrs())
1850 CanConvert = true;
1851 } else if (ToTy->isHLSLResourceType()) {
1852 CanConvert = true;
1853 }
1854 if (CanConvert) {
1855 ICS.setStandard();
1857 ICS.Standard.setFromType(FromType);
1858 ICS.Standard.setAllToTypes(ToType);
1859 return ICS;
1860 }
1861 }
1862 }
1863
1864 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1865 AllowExplicit, InOverloadResolution, CStyle,
1866 AllowObjCWritebackConversion,
1867 AllowObjCConversionOnExplicit);
1868}
1869
1870ImplicitConversionSequence
1872 bool SuppressUserConversions,
1873 AllowedExplicit AllowExplicit,
1874 bool InOverloadResolution,
1875 bool CStyle,
1876 bool AllowObjCWritebackConversion) {
1877 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1878 AllowExplicit, InOverloadResolution, CStyle,
1879 AllowObjCWritebackConversion,
1880 /*AllowObjCConversionOnExplicit=*/false);
1881}
1882
1884 AssignmentAction Action,
1885 bool AllowExplicit) {
1886 if (checkPlaceholderForOverload(*this, From))
1887 return ExprError();
1888
1889 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1890 bool AllowObjCWritebackConversion =
1891 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1892 Action == AssignmentAction::Sending);
1893 if (getLangOpts().ObjC)
1894 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1895 From->getType(), From);
1897 *this, From, ToType,
1898 /*SuppressUserConversions=*/false,
1899 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1900 /*InOverloadResolution=*/false,
1901 /*CStyle=*/false, AllowObjCWritebackConversion,
1902 /*AllowObjCConversionOnExplicit=*/false);
1903 return PerformImplicitConversion(From, ToType, ICS, Action);
1904}
1905
1907 QualType &ResultTy) const {
1908 bool Changed = IsFunctionConversion(FromType, ToType);
1909 if (Changed)
1910 ResultTy = ToType;
1911 return Changed;
1912}
1913
1914bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1915 if (Context.hasSameUnqualifiedType(FromType, ToType))
1916 return false;
1917
1918 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1919 // or F(t noexcept) -> F(t)
1920 // where F adds one of the following at most once:
1921 // - a pointer
1922 // - a member pointer
1923 // - a block pointer
1924 // Changes here need matching changes in FindCompositePointerType.
1925 CanQualType CanTo = Context.getCanonicalType(ToType);
1926 CanQualType CanFrom = Context.getCanonicalType(FromType);
1927 Type::TypeClass TyClass = CanTo->getTypeClass();
1928 if (TyClass != CanFrom->getTypeClass()) return false;
1929 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1930 if (TyClass == Type::Pointer) {
1931 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1932 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1933 } else if (TyClass == Type::BlockPointer) {
1934 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1935 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1936 } else if (TyClass == Type::MemberPointer) {
1937 auto ToMPT = CanTo.castAs<MemberPointerType>();
1938 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1939 // A function pointer conversion cannot change the class of the function.
1940 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1941 FromMPT->getMostRecentCXXRecordDecl()))
1942 return false;
1943 CanTo = ToMPT->getPointeeType();
1944 CanFrom = FromMPT->getPointeeType();
1945 } else {
1946 return false;
1947 }
1948
1949 TyClass = CanTo->getTypeClass();
1950 if (TyClass != CanFrom->getTypeClass()) return false;
1951 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1952 return false;
1953 }
1954
1955 const auto *FromFn = cast<FunctionType>(CanFrom);
1956 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1957
1958 const auto *ToFn = cast<FunctionType>(CanTo);
1959 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1960
1961 bool Changed = false;
1962
1963 // Drop 'noreturn' if not present in target type.
1964 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1965 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1966 Changed = true;
1967 }
1968
1969 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1970 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1971
1972 if (FromFPT && ToFPT) {
1973 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1974 QualType NewTy = Context.getFunctionType(
1975 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1976 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1977 ToFPT->hasCFIUncheckedCallee()));
1978 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1979 FromFn = FromFPT;
1980 Changed = true;
1981 }
1982 }
1983
1984 // Drop 'noexcept' if not present in target type.
1985 if (FromFPT && ToFPT) {
1986 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1987 FromFn = cast<FunctionType>(
1988 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1989 EST_None)
1990 .getTypePtr());
1991 Changed = true;
1992 }
1993
1994 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1995 // only if the ExtParameterInfo lists of the two function prototypes can be
1996 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1998 bool CanUseToFPT, CanUseFromFPT;
1999 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2000 CanUseFromFPT, NewParamInfos) &&
2001 CanUseToFPT && !CanUseFromFPT) {
2002 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2003 ExtInfo.ExtParameterInfos =
2004 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2005 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2006 FromFPT->getParamTypes(), ExtInfo);
2007 FromFn = QT->getAs<FunctionType>();
2008 Changed = true;
2009 }
2010
2011 if (Context.hasAnyFunctionEffects()) {
2012 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2013
2014 // Transparently add/drop effects; here we are concerned with
2015 // language rules/canonicalization. Adding/dropping effects is a warning.
2016 const auto FromFX = FromFPT->getFunctionEffects();
2017 const auto ToFX = ToFPT->getFunctionEffects();
2018 if (FromFX != ToFX) {
2019 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2020 ExtInfo.FunctionEffects = ToFX;
2021 QualType QT = Context.getFunctionType(
2022 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2023 FromFn = QT->getAs<FunctionType>();
2024 Changed = true;
2025 }
2026 }
2027 }
2028
2029 if (!Changed)
2030 return false;
2031
2032 assert(QualType(FromFn, 0).isCanonical());
2033 if (QualType(FromFn, 0) != CanTo) return false;
2034
2035 return true;
2036}
2037
2038/// Determine whether the conversion from FromType to ToType is a valid
2039/// floating point conversion.
2040///
2041static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2042 QualType ToType) {
2043 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2044 return false;
2045 // FIXME: disable conversions between long double, __ibm128 and __float128
2046 // if their representation is different until there is back end support
2047 // We of course allow this conversion if long double is really double.
2048
2049 // Conversions between bfloat16 and float16 are currently not supported.
2050 if ((FromType->isBFloat16Type() &&
2051 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2052 (ToType->isBFloat16Type() &&
2053 (FromType->isFloat16Type() || FromType->isHalfType())))
2054 return false;
2055
2056 // Conversions between IEEE-quad and IBM-extended semantics are not
2057 // permitted.
2058 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2059 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2060 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2061 &ToSem == &llvm::APFloat::IEEEquad()) ||
2062 (&FromSem == &llvm::APFloat::IEEEquad() &&
2063 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2064 return false;
2065 return true;
2066}
2067
2069 QualType ToType,
2071 Expr *From) {
2072 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2073 return true;
2074
2075 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2077 return true;
2078 }
2079
2080 if (IsFloatingPointConversion(S, FromType, ToType)) {
2082 return true;
2083 }
2084
2085 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2087 return true;
2088 }
2089
2090 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2092 ToType->isRealFloatingType())) {
2094 return true;
2095 }
2096
2097 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2099 return true;
2100 }
2101
2102 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2103 ToType->isIntegralType(S.Context)) {
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
2111/// Determine whether the conversion from FromType to ToType is a valid
2112/// matrix conversion.
2113///
2114/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2115/// conversion.
2116static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2118 ImplicitConversionKind &ElConv, Expr *From,
2119 bool InOverloadResolution, bool CStyle) {
2120 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2121 if (!S.getLangOpts().HLSL)
2122 return false;
2123
2124 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2125 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2126
2127 // If both arguments are matrix, handle possible matrix truncation and
2128 // element conversion.
2129 if (ToMatrixType && FromMatrixType) {
2130 unsigned FromCols = FromMatrixType->getNumColumns();
2131 unsigned ToCols = ToMatrixType->getNumColumns();
2132 if (FromCols < ToCols)
2133 return false;
2134
2135 unsigned FromRows = FromMatrixType->getNumRows();
2136 unsigned ToRows = ToMatrixType->getNumRows();
2137 if (FromRows < ToRows)
2138 return false;
2139
2140 if (FromRows == ToRows && FromCols == ToCols)
2141 ElConv = ICK_Identity;
2142 else
2144
2145 QualType FromElTy = FromMatrixType->getElementType();
2146 QualType ToElTy = ToMatrixType->getElementType();
2147 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2148 return true;
2149 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2150 }
2151
2152 // Matrix splat from any arithmetic type to a matrix.
2153 if (ToMatrixType && FromType->isArithmeticType()) {
2154 ElConv = ICK_HLSL_Matrix_Splat;
2155 QualType ToElTy = ToMatrixType->getElementType();
2156 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2158 return true;
2159 }
2160 if (FromMatrixType && !ToMatrixType) {
2162 QualType FromElTy = FromMatrixType->getElementType();
2163 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2164 return true;
2165 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2166 }
2167
2168 return false;
2169}
2170
2171/// Determine whether the conversion from FromType to ToType is a valid
2172/// vector conversion.
2173///
2174/// \param ICK Will be set to the vector conversion kind, if this is a vector
2175/// conversion.
2176static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2178 ImplicitConversionKind &ElConv, Expr *From,
2179 bool InOverloadResolution, bool CStyle) {
2180 // We need at least one of these types to be a vector type to have a vector
2181 // conversion.
2182 if (!ToType->isVectorType() && !FromType->isVectorType())
2183 return false;
2184
2185 // Identical types require no conversions.
2186 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2187 return false;
2188
2189 // HLSL allows implicit truncation of vector types.
2190 if (S.getLangOpts().HLSL) {
2191 auto *ToExtType = ToType->getAs<ExtVectorType>();
2192 auto *FromExtType = FromType->getAs<ExtVectorType>();
2193
2194 // If both arguments are vectors, handle possible vector truncation and
2195 // element conversion.
2196 if (ToExtType && FromExtType) {
2197 unsigned FromElts = FromExtType->getNumElements();
2198 unsigned ToElts = ToExtType->getNumElements();
2199 if (FromElts < ToElts)
2200 return false;
2201 if (FromElts == ToElts)
2202 ElConv = ICK_Identity;
2203 else
2205
2206 QualType FromElTy = FromExtType->getElementType();
2207 QualType ToElTy = ToExtType->getElementType();
2208 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2209 return true;
2210 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2211 }
2212 if (FromExtType && !ToExtType) {
2214 QualType FromElTy = FromExtType->getElementType();
2215 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2216 return true;
2217 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2218 }
2219 // Fallthrough for the case where ToType is a vector and FromType is not.
2220 }
2221
2222 // There are no conversions between extended vector types, only identity.
2223 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2224 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2225 // Implicit conversions require the same number of elements.
2226 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2227 return false;
2228
2229 // Permit implicit conversions from integral values to boolean vectors.
2230 if (ToType->isExtVectorBoolType() &&
2231 FromExtType->getElementType()->isIntegerType()) {
2233 return true;
2234 }
2235 // There are no other conversions between extended vector types.
2236 return false;
2237 }
2238
2239 // Vector splat from any arithmetic type to a vector.
2240 if (FromType->isArithmeticType()) {
2241 if (S.getLangOpts().HLSL) {
2242 ElConv = ICK_HLSL_Vector_Splat;
2243 QualType ToElTy = ToExtType->getElementType();
2244 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2245 From);
2246 }
2247 ICK = ICK_Vector_Splat;
2248 return true;
2249 }
2250 }
2251
2252 if (ToType->isSVESizelessBuiltinType() ||
2253 FromType->isSVESizelessBuiltinType())
2254 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2255 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2257 return true;
2258 }
2259
2260 if (ToType->isRVVSizelessBuiltinType() ||
2261 FromType->isRVVSizelessBuiltinType())
2262 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2263 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2265 return true;
2266 }
2267
2268 // We can perform the conversion between vector types in the following cases:
2269 // 1)vector types are equivalent AltiVec and GCC vector types
2270 // 2)lax vector conversions are permitted and the vector types are of the
2271 // same size
2272 // 3)the destination type does not have the ARM MVE strict-polymorphism
2273 // attribute, which inhibits lax vector conversion for overload resolution
2274 // only
2275 if (ToType->isVectorType() && FromType->isVectorType()) {
2276 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2277 (S.isLaxVectorConversion(FromType, ToType) &&
2278 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2279 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2280 S.isLaxVectorConversion(FromType, ToType) &&
2281 S.anyAltivecTypes(FromType, ToType) &&
2282 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2283 !InOverloadResolution && !CStyle) {
2284 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2285 << FromType << ToType;
2286 }
2288 return true;
2289 }
2290 }
2291
2292 return false;
2293}
2294
2295static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2296 bool InOverloadResolution,
2297 StandardConversionSequence &SCS,
2298 bool CStyle);
2299
2300/// IsStandardConversion - Determines whether there is a standard
2301/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2302/// expression From to the type ToType. Standard conversion sequences
2303/// only consider non-class types; for conversions that involve class
2304/// types, use TryImplicitConversion. If a conversion exists, SCS will
2305/// contain the standard conversion sequence required to perform this
2306/// conversion and this routine will return true. Otherwise, this
2307/// routine will return false and the value of SCS is unspecified.
2308static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2309 bool InOverloadResolution,
2311 bool CStyle,
2312 bool AllowObjCWritebackConversion) {
2313 QualType FromType = From->getType();
2314
2315 // Standard conversions (C++ [conv])
2317 SCS.IncompatibleObjC = false;
2318 SCS.setFromType(FromType);
2319 SCS.CopyConstructor = nullptr;
2320
2321 // There are no standard conversions for class types in C++, so
2322 // abort early. When overloading in C, however, we do permit them.
2323 if (S.getLangOpts().CPlusPlus &&
2324 (FromType->isRecordType() || ToType->isRecordType()))
2325 return false;
2326
2327 // The first conversion can be an lvalue-to-rvalue conversion,
2328 // array-to-pointer conversion, or function-to-pointer conversion
2329 // (C++ 4p1).
2330
2331 if (FromType == S.Context.OverloadTy) {
2332 DeclAccessPair AccessPair;
2333 if (FunctionDecl *Fn
2334 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2335 AccessPair)) {
2336 // We were able to resolve the address of the overloaded function,
2337 // so we can convert to the type of that function.
2338 FromType = Fn->getType();
2339 SCS.setFromType(FromType);
2340
2341 // we can sometimes resolve &foo<int> regardless of ToType, so check
2342 // if the type matches (identity) or we are converting to bool
2344 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2345 // if the function type matches except for [[noreturn]], it's ok
2346 if (!S.IsFunctionConversion(FromType,
2348 // otherwise, only a boolean conversion is standard
2349 if (!ToType->isBooleanType())
2350 return false;
2351 }
2352
2353 // Check if the "from" expression is taking the address of an overloaded
2354 // function and recompute the FromType accordingly. Take advantage of the
2355 // fact that non-static member functions *must* have such an address-of
2356 // expression.
2357 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2358 if (Method && !Method->isStatic() &&
2359 !Method->isExplicitObjectMemberFunction()) {
2360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2361 "Non-unary operator on non-static member address");
2362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2363 == UO_AddrOf &&
2364 "Non-address-of operator on non-static member address");
2365 FromType = S.Context.getMemberPointerType(
2366 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2367 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2368 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2369 UO_AddrOf &&
2370 "Non-address-of operator for overloaded function expression");
2371 FromType = S.Context.getPointerType(FromType);
2372 }
2373 } else {
2374 return false;
2375 }
2376 }
2377
2378 bool argIsLValue = From->isGLValue();
2379 // To handle conversion from ArrayParameterType to ConstantArrayType
2380 // this block must be above the one below because Array parameters
2381 // do not decay and when handling HLSLOutArgExprs and
2382 // the From expression is an LValue.
2383 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2384 ToType->isConstantArrayType()) {
2385 // HLSL constant array parameters do not decay, so if the argument is a
2386 // constant array and the parameter is an ArrayParameterType we have special
2387 // handling here.
2388 if (ToType->isArrayParameterType()) {
2389 FromType = S.Context.getArrayParameterType(FromType);
2390 } else if (FromType->isArrayParameterType()) {
2391 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2392 FromType = APT->getConstantArrayType(S.Context);
2393 }
2394
2396
2397 // Don't consider qualifiers, which include things like address spaces
2398 if (FromType.getCanonicalType().getUnqualifiedType() !=
2400 return false;
2401
2402 SCS.setAllToTypes(ToType);
2403 return true;
2404 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2405 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2406 // Lvalue-to-rvalue conversion (C++11 4.1):
2407 // A glvalue (3.10) of a non-function, non-array type T can
2408 // be converted to a prvalue.
2409
2411
2412 // C11 6.3.2.1p2:
2413 // ... if the lvalue has atomic type, the value has the non-atomic version
2414 // of the type of the lvalue ...
2415 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2416 FromType = Atomic->getValueType();
2417
2418 // If T is a non-class type, the type of the rvalue is the
2419 // cv-unqualified version of T. Otherwise, the type of the rvalue
2420 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2421 // just strip the qualifiers because they don't matter.
2422 FromType = FromType.getUnqualifiedType();
2423 } else if (FromType->isArrayType()) {
2424 // Array-to-pointer conversion (C++ 4.2)
2426
2427 // An lvalue or rvalue of type "array of N T" or "array of unknown
2428 // bound of T" can be converted to an rvalue of type "pointer to
2429 // T" (C++ 4.2p1).
2430 FromType = S.Context.getArrayDecayedType(FromType);
2431
2432 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2433 // This conversion is deprecated in C++03 (D.4)
2435
2436 // For the purpose of ranking in overload resolution
2437 // (13.3.3.1.1), this conversion is considered an
2438 // array-to-pointer conversion followed by a qualification
2439 // conversion (4.4). (C++ 4.2p2)
2440 SCS.Second = ICK_Identity;
2443 SCS.setAllToTypes(FromType);
2444 return true;
2445 }
2446 } else if (FromType->isFunctionType() && argIsLValue) {
2447 // Function-to-pointer conversion (C++ 4.3).
2449
2450 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2451 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2453 return false;
2454
2455 // An lvalue of function type T can be converted to an rvalue of
2456 // type "pointer to T." The result is a pointer to the
2457 // function. (C++ 4.3p1).
2458 FromType = S.Context.getPointerType(FromType);
2459 } else {
2460 // We don't require any conversions for the first step.
2461 SCS.First = ICK_Identity;
2462 }
2463 SCS.setToType(0, FromType);
2464
2465 // The second conversion can be an integral promotion, floating
2466 // point promotion, integral conversion, floating point conversion,
2467 // floating-integral conversion, pointer conversion,
2468 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2469 // For overloading in C, this can also be a "compatible-type"
2470 // conversion.
2471 bool IncompatibleObjC = false;
2473 ImplicitConversionKind DimensionICK = ICK_Identity;
2474 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2475 // The unqualified versions of the types are the same: there's no
2476 // conversion to do.
2477 SCS.Second = ICK_Identity;
2478 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2479 // Integral promotion (C++ 4.5).
2481 FromType = ToType.getUnqualifiedType();
2482 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2483 // Floating point promotion (C++ 4.6).
2485 FromType = ToType.getUnqualifiedType();
2486 } else if (S.IsComplexPromotion(FromType, ToType)) {
2487 // Complex promotion (Clang extension)
2489 FromType = ToType.getUnqualifiedType();
2490 } else if (ToType->isBooleanType() &&
2491 (FromType->isArithmeticType() ||
2492 FromType->isAnyPointerType() ||
2493 FromType->isBlockPointerType() ||
2494 FromType->isMemberPointerType())) {
2495 // Boolean conversions (C++ 4.12).
2497 FromType = S.Context.BoolTy;
2498 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2499 ToType->isIntegralType(S.Context)) {
2500 // Integral conversions (C++ 4.7).
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2504 // Complex conversions (C99 6.3.1.6)
2506 FromType = ToType.getUnqualifiedType();
2507 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2508 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2509 // Complex-real conversions (C99 6.3.1.7)
2511 FromType = ToType.getUnqualifiedType();
2512 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2513 // Floating point conversions (C++ 4.8).
2515 FromType = ToType.getUnqualifiedType();
2516 } else if ((FromType->isRealFloatingType() &&
2517 ToType->isIntegralType(S.Context)) ||
2519 ToType->isRealFloatingType())) {
2520
2521 // Floating-integral conversions (C++ 4.9).
2523 FromType = ToType.getUnqualifiedType();
2524 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2526 } else if (AllowObjCWritebackConversion &&
2527 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2529 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2530 FromType, IncompatibleObjC)) {
2531 // Pointer conversions (C++ 4.10).
2533 SCS.IncompatibleObjC = IncompatibleObjC;
2534 FromType = FromType.getUnqualifiedType();
2535 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2536 InOverloadResolution, FromType)) {
2537 // Pointer to member conversions (4.11).
2539 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2540 From, InOverloadResolution, CStyle)) {
2541 SCS.Second = SecondICK;
2542 SCS.Dimension = DimensionICK;
2543 FromType = ToType.getUnqualifiedType();
2544 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2545 From, InOverloadResolution, CStyle)) {
2546 SCS.Second = SecondICK;
2547 SCS.Dimension = DimensionICK;
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (!S.getLangOpts().CPlusPlus &&
2550 S.Context.typesAreCompatible(ToType, FromType)) {
2551 // Compatible conversions (Clang extension for C function overloading)
2553 FromType = ToType.getUnqualifiedType();
2555 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2557 FromType = ToType;
2558 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2559 CStyle)) {
2560 // tryAtomicConversion has updated the standard conversion sequence
2561 // appropriately.
2562 return true;
2563 } else if (ToType->isEventT() &&
2565 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2567 FromType = ToType;
2568 } else if (ToType->isQueueT() &&
2570 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2572 FromType = ToType;
2573 } else if (ToType->isSamplerT() &&
2576 FromType = ToType;
2577 } else if ((ToType->isFixedPointType() &&
2578 FromType->isConvertibleToFixedPointType()) ||
2579 (FromType->isFixedPointType() &&
2580 ToType->isConvertibleToFixedPointType())) {
2582 FromType = ToType;
2583 } else {
2584 // No second conversion required.
2585 SCS.Second = ICK_Identity;
2586 }
2587 SCS.setToType(1, FromType);
2588
2589 // The third conversion can be a function pointer conversion or a
2590 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2591 bool ObjCLifetimeConversion;
2592 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2593 // Function pointer conversions (removing 'noexcept') including removal of
2594 // 'noreturn' (Clang extension).
2596 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2597 ObjCLifetimeConversion)) {
2599 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2600 FromType = ToType;
2601 } else {
2602 // No conversion required
2603 SCS.Third = ICK_Identity;
2604 }
2605
2606 // C++ [over.best.ics]p6:
2607 // [...] Any difference in top-level cv-qualification is
2608 // subsumed by the initialization itself and does not constitute
2609 // a conversion. [...]
2610 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2611 QualType CanonTo = S.Context.getCanonicalType(ToType);
2612 if (CanonFrom.getLocalUnqualifiedType()
2613 == CanonTo.getLocalUnqualifiedType() &&
2614 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2615 FromType = ToType;
2616 CanonFrom = CanonTo;
2617 }
2618
2619 SCS.setToType(2, FromType);
2620
2621 if (CanonFrom == CanonTo)
2622 return true;
2623
2624 // If we have not converted the argument type to the parameter type,
2625 // this is a bad conversion sequence, unless we're resolving an overload in C.
2626 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2627 return false;
2628
2629 ExprResult ER = ExprResult{From};
2630 AssignConvertType Conv =
2632 /*Diagnose=*/false,
2633 /*DiagnoseCFAudited=*/false,
2634 /*ConvertRHS=*/false);
2635 ImplicitConversionKind SecondConv;
2636 switch (Conv) {
2638 case AssignConvertType::
2639 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2640 SecondConv = ICK_C_Only_Conversion;
2641 break;
2642 // For our purposes, discarding qualifiers is just as bad as using an
2643 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2644 // qualifiers, as well.
2649 break;
2650 default:
2651 return false;
2652 }
2653
2654 // First can only be an lvalue conversion, so we pretend that this was the
2655 // second conversion. First should already be valid from earlier in the
2656 // function.
2657 SCS.Second = SecondConv;
2658 SCS.setToType(1, ToType);
2659
2660 // Third is Identity, because Second should rank us worse than any other
2661 // conversion. This could also be ICK_Qualification, but it's simpler to just
2662 // lump everything in with the second conversion, and we don't gain anything
2663 // from making this ICK_Qualification.
2664 SCS.Third = ICK_Identity;
2665 SCS.setToType(2, ToType);
2666 return true;
2667}
2668
2669static bool
2671 QualType &ToType,
2672 bool InOverloadResolution,
2674 bool CStyle) {
2675
2676 const RecordType *UT = ToType->getAsUnionType();
2677 if (!UT)
2678 return false;
2679 // The field to initialize within the transparent union.
2680 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2681 if (!UD->hasAttr<TransparentUnionAttr>())
2682 return false;
2683 // It's compatible if the expression matches any of the fields.
2684 for (const auto *it : UD->fields()) {
2685 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2686 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2687 ToType = it->getType();
2688 return true;
2689 }
2690 }
2691 return false;
2692}
2693
2694bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2695 const BuiltinType *To = ToType->getAs<BuiltinType>();
2696 // All integers are built-in.
2697 if (!To) {
2698 return false;
2699 }
2700
2701 // An rvalue of type char, signed char, unsigned char, short int, or
2702 // unsigned short int can be converted to an rvalue of type int if
2703 // int can represent all the values of the source type; otherwise,
2704 // the source rvalue can be converted to an rvalue of type unsigned
2705 // int (C++ 4.5p1).
2706 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2707 !FromType->isEnumeralType()) {
2708 if ( // We can promote any signed, promotable integer type to an int
2709 (FromType->isSignedIntegerType() ||
2710 // We can promote any unsigned integer type whose size is
2711 // less than int to an int.
2712 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2713 return To->getKind() == BuiltinType::Int;
2714 }
2715
2716 return To->getKind() == BuiltinType::UInt;
2717 }
2718
2719 // C++11 [conv.prom]p3:
2720 // A prvalue of an unscoped enumeration type whose underlying type is not
2721 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2722 // following types that can represent all the values of the enumeration
2723 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2724 // unsigned int, long int, unsigned long int, long long int, or unsigned
2725 // long long int. If none of the types in that list can represent all the
2726 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2727 // type can be converted to an rvalue a prvalue of the extended integer type
2728 // with lowest integer conversion rank (4.13) greater than the rank of long
2729 // long in which all the values of the enumeration can be represented. If
2730 // there are two such extended types, the signed one is chosen.
2731 // C++11 [conv.prom]p4:
2732 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2733 // can be converted to a prvalue of its underlying type. Moreover, if
2734 // integral promotion can be applied to its underlying type, a prvalue of an
2735 // unscoped enumeration type whose underlying type is fixed can also be
2736 // converted to a prvalue of the promoted underlying type.
2737 if (const auto *FromED = FromType->getAsEnumDecl()) {
2738 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2739 // provided for a scoped enumeration.
2740 if (FromED->isScoped())
2741 return false;
2742
2743 // We can perform an integral promotion to the underlying type of the enum,
2744 // even if that's not the promoted type. Note that the check for promoting
2745 // the underlying type is based on the type alone, and does not consider
2746 // the bitfield-ness of the actual source expression.
2747 if (FromED->isFixed()) {
2748 QualType Underlying = FromED->getIntegerType();
2749 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2750 IsIntegralPromotion(nullptr, Underlying, ToType);
2751 }
2752
2753 // We have already pre-calculated the promotion type, so this is trivial.
2754 if (ToType->isIntegerType() &&
2755 isCompleteType(From->getBeginLoc(), FromType))
2756 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2757
2758 // C++ [conv.prom]p5:
2759 // If the bit-field has an enumerated type, it is treated as any other
2760 // value of that type for promotion purposes.
2761 //
2762 // ... so do not fall through into the bit-field checks below in C++.
2763 if (getLangOpts().CPlusPlus)
2764 return false;
2765 }
2766
2767 // C++0x [conv.prom]p2:
2768 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2769 // to an rvalue a prvalue of the first of the following types that can
2770 // represent all the values of its underlying type: int, unsigned int,
2771 // long int, unsigned long int, long long int, or unsigned long long int.
2772 // If none of the types in that list can represent all the values of its
2773 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2774 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2775 // type.
2776 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2777 ToType->isIntegerType()) {
2778 // Determine whether the type we're converting from is signed or
2779 // unsigned.
2780 bool FromIsSigned = FromType->isSignedIntegerType();
2781 uint64_t FromSize = Context.getTypeSize(FromType);
2782
2783 // The types we'll try to promote to, in the appropriate
2784 // order. Try each of these types.
2785 QualType PromoteTypes[6] = {
2786 Context.IntTy, Context.UnsignedIntTy,
2787 Context.LongTy, Context.UnsignedLongTy ,
2788 Context.LongLongTy, Context.UnsignedLongLongTy
2789 };
2790 for (int Idx = 0; Idx < 6; ++Idx) {
2791 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2792 if (FromSize < ToSize ||
2793 (FromSize == ToSize &&
2794 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2795 // We found the type that we can promote to. If this is the
2796 // type we wanted, we have a promotion. Otherwise, no
2797 // promotion.
2798 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2799 }
2800 }
2801 }
2802
2803 // An rvalue for an integral bit-field (9.6) can be converted to an
2804 // rvalue of type int if int can represent all the values of the
2805 // bit-field; otherwise, it can be converted to unsigned int if
2806 // unsigned int can represent all the values of the bit-field. If
2807 // the bit-field is larger yet, no integral promotion applies to
2808 // it. If the bit-field has an enumerated type, it is treated as any
2809 // other value of that type for promotion purposes (C++ 4.5p3).
2810 // FIXME: We should delay checking of bit-fields until we actually perform the
2811 // conversion.
2812 //
2813 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2814 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2815 // bit-fields and those whose underlying type is larger than int) for GCC
2816 // compatibility.
2817 if (From) {
2818 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2819 std::optional<llvm::APSInt> BitWidth;
2820 if (FromType->isIntegralType(Context) &&
2821 (BitWidth =
2822 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2823 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2824 ToSize = Context.getTypeSize(ToType);
2825
2826 // Are we promoting to an int from a bitfield that fits in an int?
2827 if (*BitWidth < ToSize ||
2828 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2829 return To->getKind() == BuiltinType::Int;
2830 }
2831
2832 // Are we promoting to an unsigned int from an unsigned bitfield
2833 // that fits into an unsigned int?
2834 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2835 return To->getKind() == BuiltinType::UInt;
2836 }
2837
2838 return false;
2839 }
2840 }
2841 }
2842
2843 // An rvalue of type bool can be converted to an rvalue of type int,
2844 // with false becoming zero and true becoming one (C++ 4.5p4).
2845 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2846 return true;
2847 }
2848
2849 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2850 // integral type.
2851 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2852 ToType->isIntegerType())
2853 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2854
2855 return false;
2856}
2857
2859 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2860 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2861 /// An rvalue of type float can be converted to an rvalue of type
2862 /// double. (C++ 4.6p1).
2863 if (FromBuiltin->getKind() == BuiltinType::Float &&
2864 ToBuiltin->getKind() == BuiltinType::Double)
2865 return true;
2866
2867 // C99 6.3.1.5p1:
2868 // When a float is promoted to double or long double, or a
2869 // double is promoted to long double [...].
2870 if (!getLangOpts().CPlusPlus &&
2871 (FromBuiltin->getKind() == BuiltinType::Float ||
2872 FromBuiltin->getKind() == BuiltinType::Double) &&
2873 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2874 ToBuiltin->getKind() == BuiltinType::Float128 ||
2875 ToBuiltin->getKind() == BuiltinType::Ibm128))
2876 return true;
2877
2878 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2879 // or not native half types are enabled.
2880 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2881 (ToBuiltin->getKind() == BuiltinType::Float ||
2882 ToBuiltin->getKind() == BuiltinType::Double))
2883 return true;
2884
2885 // Half can be promoted to float.
2886 if (!getLangOpts().NativeHalfType &&
2887 FromBuiltin->getKind() == BuiltinType::Half &&
2888 ToBuiltin->getKind() == BuiltinType::Float)
2889 return true;
2890 }
2891
2892 return false;
2893}
2894
2896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2897 if (!FromComplex)
2898 return false;
2899
2900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2901 if (!ToComplex)
2902 return false;
2903
2904 return IsFloatingPointPromotion(FromComplex->getElementType(),
2905 ToComplex->getElementType()) ||
2906 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2907 ToComplex->getElementType());
2908}
2909
2910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2911/// the pointer type FromPtr to a pointer to type ToPointee, with the
2912/// same type qualifiers as FromPtr has on its pointee type. ToType,
2913/// if non-empty, will be a pointer to ToType that may or may not have
2914/// the right set of qualifiers on its pointee.
2915///
2916static QualType
2918 QualType ToPointee, QualType ToType,
2919 ASTContext &Context,
2920 bool StripObjCLifetime = false) {
2921 assert((FromPtr->getTypeClass() == Type::Pointer ||
2922 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2923 "Invalid similarly-qualified pointer type");
2924
2925 /// Conversions to 'id' subsume cv-qualifier conversions.
2926 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2927 return ToType.getUnqualifiedType();
2928
2929 QualType CanonFromPointee
2930 = Context.getCanonicalType(FromPtr->getPointeeType());
2931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2932 Qualifiers Quals = CanonFromPointee.getQualifiers();
2933
2934 if (StripObjCLifetime)
2935 Quals.removeObjCLifetime();
2936
2937 // Exact qualifier match -> return the pointer type we're converting to.
2938 if (CanonToPointee.getLocalQualifiers() == Quals) {
2939 // ToType is exactly what we need. Return it.
2940 if (!ToType.isNull())
2941 return ToType.getUnqualifiedType();
2942
2943 // Build a pointer to ToPointee. It has the right qualifiers
2944 // already.
2945 if (isa<ObjCObjectPointerType>(ToType))
2946 return Context.getObjCObjectPointerType(ToPointee);
2947 return Context.getPointerType(ToPointee);
2948 }
2949
2950 // Just build a canonical type that has the right qualifiers.
2951 QualType QualifiedCanonToPointee
2952 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2953
2954 if (isa<ObjCObjectPointerType>(ToType))
2955 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2956 return Context.getPointerType(QualifiedCanonToPointee);
2957}
2958
2960 bool InOverloadResolution,
2961 ASTContext &Context) {
2962 // Handle value-dependent integral null pointer constants correctly.
2963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2966 return !InOverloadResolution;
2967
2968 return Expr->isNullPointerConstant(Context,
2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971}
2972
2974 bool InOverloadResolution,
2975 QualType& ConvertedType,
2976 bool &IncompatibleObjC) {
2977 IncompatibleObjC = false;
2978 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2979 IncompatibleObjC))
2980 return true;
2981
2982 // Conversion from a null pointer constant to any Objective-C pointer type.
2983 if (ToType->isObjCObjectPointerType() &&
2984 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2985 ConvertedType = ToType;
2986 return true;
2987 }
2988
2989 // Blocks: Block pointers can be converted to void*.
2990 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2991 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2992 ConvertedType = ToType;
2993 return true;
2994 }
2995 // Blocks: A null pointer constant can be converted to a block
2996 // pointer type.
2997 if (ToType->isBlockPointerType() &&
2998 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2999 ConvertedType = ToType;
3000 return true;
3001 }
3002
3003 // If the left-hand-side is nullptr_t, the right side can be a null
3004 // pointer constant.
3005 if (ToType->isNullPtrType() &&
3006 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3007 ConvertedType = ToType;
3008 return true;
3009 }
3010
3011 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3012 if (!ToTypePtr)
3013 return false;
3014
3015 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3016 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3017 ConvertedType = ToType;
3018 return true;
3019 }
3020
3021 // Beyond this point, both types need to be pointers
3022 // , including objective-c pointers.
3023 QualType ToPointeeType = ToTypePtr->getPointeeType();
3024 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3025 !getLangOpts().ObjCAutoRefCount) {
3026 ConvertedType = BuildSimilarlyQualifiedPointerType(
3027 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3028 Context);
3029 return true;
3030 }
3031 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3032 if (!FromTypePtr)
3033 return false;
3034
3035 QualType FromPointeeType = FromTypePtr->getPointeeType();
3036
3037 // If the unqualified pointee types are the same, this can't be a
3038 // pointer conversion, so don't do all of the work below.
3039 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3040 return false;
3041
3042 // An rvalue of type "pointer to cv T," where T is an object type,
3043 // can be converted to an rvalue of type "pointer to cv void" (C++
3044 // 4.10p2).
3045 if (FromPointeeType->isIncompleteOrObjectType() &&
3046 ToPointeeType->isVoidType()) {
3047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3048 ToPointeeType,
3049 ToType, Context,
3050 /*StripObjCLifetime=*/true);
3051 return true;
3052 }
3053
3054 // MSVC allows implicit function to void* type conversion.
3055 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3056 ToPointeeType->isVoidType()) {
3057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3058 ToPointeeType,
3059 ToType, Context);
3060 return true;
3061 }
3062
3063 // When we're overloading in C, we allow a special kind of pointer
3064 // conversion for compatible-but-not-identical pointee types.
3065 if (!getLangOpts().CPlusPlus &&
3066 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3068 ToPointeeType,
3069 ToType, Context);
3070 return true;
3071 }
3072
3073 // C++ [conv.ptr]p3:
3074 //
3075 // An rvalue of type "pointer to cv D," where D is a class type,
3076 // can be converted to an rvalue of type "pointer to cv B," where
3077 // B is a base class (clause 10) of D. If B is an inaccessible
3078 // (clause 11) or ambiguous (10.2) base class of D, a program that
3079 // necessitates this conversion is ill-formed. The result of the
3080 // conversion is a pointer to the base class sub-object of the
3081 // derived class object. The null pointer value is converted to
3082 // the null pointer value of the destination type.
3083 //
3084 // Note that we do not check for ambiguity or inaccessibility
3085 // here. That is handled by CheckPointerConversion.
3086 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3087 ToPointeeType->isRecordType() &&
3088 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3089 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3091 ToPointeeType,
3092 ToType, Context);
3093 return true;
3094 }
3095
3096 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3097 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3098 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3099 ToPointeeType,
3100 ToType, Context);
3101 return true;
3102 }
3103
3104 return false;
3105}
3106
3107/// Adopt the given qualifiers for the given type.
3109 Qualifiers TQs = T.getQualifiers();
3110
3111 // Check whether qualifiers already match.
3112 if (TQs == Qs)
3113 return T;
3114
3115 if (Qs.compatiblyIncludes(TQs, Context))
3116 return Context.getQualifiedType(T, Qs);
3117
3118 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3119}
3120
3122 QualType& ConvertedType,
3123 bool &IncompatibleObjC) {
3124 if (!getLangOpts().ObjC)
3125 return false;
3126
3127 // The set of qualifiers on the type we're converting from.
3128 Qualifiers FromQualifiers = FromType.getQualifiers();
3129
3130 // First, we handle all conversions on ObjC object pointer types.
3131 const ObjCObjectPointerType* ToObjCPtr =
3132 ToType->getAs<ObjCObjectPointerType>();
3133 const ObjCObjectPointerType *FromObjCPtr =
3134 FromType->getAs<ObjCObjectPointerType>();
3135
3136 if (ToObjCPtr && FromObjCPtr) {
3137 // If the pointee types are the same (ignoring qualifications),
3138 // then this is not a pointer conversion.
3139 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3140 FromObjCPtr->getPointeeType()))
3141 return false;
3142
3143 // Conversion between Objective-C pointers.
3144 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3145 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3146 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3147 if (getLangOpts().CPlusPlus && LHS && RHS &&
3149 FromObjCPtr->getPointeeType(), getASTContext()))
3150 return false;
3151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3152 ToObjCPtr->getPointeeType(),
3153 ToType, Context);
3154 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3155 return true;
3156 }
3157
3158 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3159 // Okay: this is some kind of implicit downcast of Objective-C
3160 // interfaces, which is permitted. However, we're going to
3161 // complain about it.
3162 IncompatibleObjC = true;
3163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3164 ToObjCPtr->getPointeeType(),
3165 ToType, Context);
3166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3167 return true;
3168 }
3169 }
3170 // Beyond this point, both types need to be C pointers or block pointers.
3171 QualType ToPointeeType;
3172 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3173 ToPointeeType = ToCPtr->getPointeeType();
3174 else if (const BlockPointerType *ToBlockPtr =
3175 ToType->getAs<BlockPointerType>()) {
3176 // Objective C++: We're able to convert from a pointer to any object
3177 // to a block pointer type.
3178 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3180 return true;
3181 }
3182 ToPointeeType = ToBlockPtr->getPointeeType();
3183 }
3184 else if (FromType->getAs<BlockPointerType>() &&
3185 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3186 // Objective C++: We're able to convert from a block pointer type to a
3187 // pointer to any object.
3188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3189 return true;
3190 }
3191 else
3192 return false;
3193
3194 QualType FromPointeeType;
3195 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3196 FromPointeeType = FromCPtr->getPointeeType();
3197 else if (const BlockPointerType *FromBlockPtr =
3198 FromType->getAs<BlockPointerType>())
3199 FromPointeeType = FromBlockPtr->getPointeeType();
3200 else
3201 return false;
3202
3203 // If we have pointers to pointers, recursively check whether this
3204 // is an Objective-C conversion.
3205 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3206 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3207 IncompatibleObjC)) {
3208 // We always complain about this conversion.
3209 IncompatibleObjC = true;
3210 ConvertedType = Context.getPointerType(ConvertedType);
3211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3212 return true;
3213 }
3214 // Allow conversion of pointee being objective-c pointer to another one;
3215 // as in I* to id.
3216 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3217 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3219 IncompatibleObjC)) {
3220
3221 ConvertedType = Context.getPointerType(ConvertedType);
3222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3223 return true;
3224 }
3225
3226 // If we have pointers to functions or blocks, check whether the only
3227 // differences in the argument and result types are in Objective-C
3228 // pointer conversions. If so, we permit the conversion (but
3229 // complain about it).
3230 const FunctionProtoType *FromFunctionType
3231 = FromPointeeType->getAs<FunctionProtoType>();
3232 const FunctionProtoType *ToFunctionType
3233 = ToPointeeType->getAs<FunctionProtoType>();
3234 if (FromFunctionType && ToFunctionType) {
3235 // If the function types are exactly the same, this isn't an
3236 // Objective-C pointer conversion.
3237 if (Context.getCanonicalType(FromPointeeType)
3238 == Context.getCanonicalType(ToPointeeType))
3239 return false;
3240
3241 // Perform the quick checks that will tell us whether these
3242 // function types are obviously different.
3243 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3244 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3245 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3246 return false;
3247
3248 bool HasObjCConversion = false;
3249 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3250 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3251 // Okay, the types match exactly. Nothing to do.
3252 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3253 ToFunctionType->getReturnType(),
3254 ConvertedType, IncompatibleObjC)) {
3255 // Okay, we have an Objective-C pointer conversion.
3256 HasObjCConversion = true;
3257 } else {
3258 // Function types are too different. Abort.
3259 return false;
3260 }
3261
3262 // Check argument types.
3263 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3264 ArgIdx != NumArgs; ++ArgIdx) {
3265 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3266 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3267 if (Context.getCanonicalType(FromArgType)
3268 == Context.getCanonicalType(ToArgType)) {
3269 // Okay, the types match exactly. Nothing to do.
3270 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3271 ConvertedType, IncompatibleObjC)) {
3272 // Okay, we have an Objective-C pointer conversion.
3273 HasObjCConversion = true;
3274 } else {
3275 // Argument types are too different. Abort.
3276 return false;
3277 }
3278 }
3279
3280 if (HasObjCConversion) {
3281 // We had an Objective-C conversion. Allow this pointer
3282 // conversion, but complain about it.
3283 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3284 IncompatibleObjC = true;
3285 return true;
3286 }
3287 }
3288
3289 return false;
3290}
3291
3293 QualType& ConvertedType) {
3294 QualType ToPointeeType;
3295 if (const BlockPointerType *ToBlockPtr =
3296 ToType->getAs<BlockPointerType>())
3297 ToPointeeType = ToBlockPtr->getPointeeType();
3298 else
3299 return false;
3300
3301 QualType FromPointeeType;
3302 if (const BlockPointerType *FromBlockPtr =
3303 FromType->getAs<BlockPointerType>())
3304 FromPointeeType = FromBlockPtr->getPointeeType();
3305 else
3306 return false;
3307 // We have pointer to blocks, check whether the only
3308 // differences in the argument and result types are in Objective-C
3309 // pointer conversions. If so, we permit the conversion.
3310
3311 const FunctionProtoType *FromFunctionType
3312 = FromPointeeType->getAs<FunctionProtoType>();
3313 const FunctionProtoType *ToFunctionType
3314 = ToPointeeType->getAs<FunctionProtoType>();
3315
3316 if (!FromFunctionType || !ToFunctionType)
3317 return false;
3318
3319 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3320 return true;
3321
3322 // Perform the quick checks that will tell us whether these
3323 // function types are obviously different.
3324 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3325 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3326 return false;
3327
3328 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3329 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3330 if (FromEInfo != ToEInfo)
3331 return false;
3332
3333 bool IncompatibleObjC = false;
3334 if (Context.hasSameType(FromFunctionType->getReturnType(),
3335 ToFunctionType->getReturnType())) {
3336 // Okay, the types match exactly. Nothing to do.
3337 } else {
3338 QualType RHS = FromFunctionType->getReturnType();
3339 QualType LHS = ToFunctionType->getReturnType();
3340 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3341 !RHS.hasQualifiers() && LHS.hasQualifiers())
3342 LHS = LHS.getUnqualifiedType();
3343
3344 if (Context.hasSameType(RHS,LHS)) {
3345 // OK exact match.
3346 } else if (isObjCPointerConversion(RHS, LHS,
3347 ConvertedType, IncompatibleObjC)) {
3348 if (IncompatibleObjC)
3349 return false;
3350 // Okay, we have an Objective-C pointer conversion.
3351 }
3352 else
3353 return false;
3354 }
3355
3356 // Check argument types.
3357 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3358 ArgIdx != NumArgs; ++ArgIdx) {
3359 IncompatibleObjC = false;
3360 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3361 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3362 if (Context.hasSameType(FromArgType, ToArgType)) {
3363 // Okay, the types match exactly. Nothing to do.
3364 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3365 ConvertedType, IncompatibleObjC)) {
3366 if (IncompatibleObjC)
3367 return false;
3368 // Okay, we have an Objective-C pointer conversion.
3369 } else
3370 // Argument types are too different. Abort.
3371 return false;
3372 }
3373
3375 bool CanUseToFPT, CanUseFromFPT;
3376 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3377 CanUseToFPT, CanUseFromFPT,
3378 NewParamInfos))
3379 return false;
3380
3381 ConvertedType = ToType;
3382 return true;
3383}
3384
3385enum {
3393};
3394
3395/// Attempts to get the FunctionProtoType from a Type. Handles
3396/// MemberFunctionPointers properly.
3398 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3399 return FPT;
3400
3401 if (auto *MPT = FromType->getAs<MemberPointerType>())
3402 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3403
3404 return nullptr;
3405}
3406
3408 QualType FromType, QualType ToType) {
3409 // If either type is not valid, include no extra info.
3410 if (FromType.isNull() || ToType.isNull()) {
3411 PDiag << ft_default;
3412 return;
3413 }
3414
3415 // Get the function type from the pointers.
3416 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3417 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3418 *ToMember = ToType->castAs<MemberPointerType>();
3419 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3420 ToMember->getMostRecentCXXRecordDecl())) {
3422 if (ToMember->isSugared())
3423 PDiag << Context.getCanonicalTagType(
3424 ToMember->getMostRecentCXXRecordDecl());
3425 else
3426 PDiag << ToMember->getQualifier();
3427 if (FromMember->isSugared())
3428 PDiag << Context.getCanonicalTagType(
3429 FromMember->getMostRecentCXXRecordDecl());
3430 else
3431 PDiag << FromMember->getQualifier();
3432 return;
3433 }
3434 FromType = FromMember->getPointeeType();
3435 ToType = ToMember->getPointeeType();
3436 }
3437
3438 if (FromType->isPointerType())
3439 FromType = FromType->getPointeeType();
3440 if (ToType->isPointerType())
3441 ToType = ToType->getPointeeType();
3442
3443 // Remove references.
3444 FromType = FromType.getNonReferenceType();
3445 ToType = ToType.getNonReferenceType();
3446
3447 // Don't print extra info for non-specialized template functions.
3448 if (FromType->isInstantiationDependentType() &&
3449 !FromType->getAs<TemplateSpecializationType>()) {
3450 PDiag << ft_default;
3451 return;
3452 }
3453
3454 // No extra info for same types.
3455 if (Context.hasSameType(FromType, ToType)) {
3456 PDiag << ft_default;
3457 return;
3458 }
3459
3460 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3461 *ToFunction = tryGetFunctionProtoType(ToType);
3462
3463 // Both types need to be function types.
3464 if (!FromFunction || !ToFunction) {
3465 PDiag << ft_default;
3466 return;
3467 }
3468
3469 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3470 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3471 << FromFunction->getNumParams();
3472 return;
3473 }
3474
3475 // Handle different parameter types.
3476 unsigned ArgPos;
3477 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3478 PDiag << ft_parameter_mismatch << ArgPos + 1
3479 << ToFunction->getParamType(ArgPos)
3480 << FromFunction->getParamType(ArgPos);
3481 return;
3482 }
3483
3484 // Handle different return type.
3485 if (!Context.hasSameType(FromFunction->getReturnType(),
3486 ToFunction->getReturnType())) {
3487 PDiag << ft_return_type << ToFunction->getReturnType()
3488 << FromFunction->getReturnType();
3489 return;
3490 }
3491
3492 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3493 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3494 << FromFunction->getMethodQuals();
3495 return;
3496 }
3497
3498 // Handle exception specification differences on canonical type (in C++17
3499 // onwards).
3501 ->isNothrow() !=
3502 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3503 ->isNothrow()) {
3504 PDiag << ft_noexcept;
3505 return;
3506 }
3507
3508 // Unable to find a difference, so add no extra info.
3509 PDiag << ft_default;
3510}
3511
3513 ArrayRef<QualType> New, unsigned *ArgPos,
3514 bool Reversed) {
3515 assert(llvm::size(Old) == llvm::size(New) &&
3516 "Can't compare parameters of functions with different number of "
3517 "parameters!");
3518
3519 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3520 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3521 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3522
3523 // Ignore address spaces in pointee type. This is to disallow overloading
3524 // on __ptr32/__ptr64 address spaces.
3525 QualType OldType =
3526 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3527 QualType NewType =
3528 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3529
3530 if (!Context.hasSameType(OldType, NewType)) {
3531 if (ArgPos)
3532 *ArgPos = Idx;
3533 return false;
3534 }
3535 }
3536 return true;
3537}
3538
3540 const FunctionProtoType *NewType,
3541 unsigned *ArgPos, bool Reversed) {
3542 return FunctionParamTypesAreEqual(OldType->param_types(),
3543 NewType->param_types(), ArgPos, Reversed);
3544}
3545
3547 const FunctionDecl *NewFunction,
3548 unsigned *ArgPos,
3549 bool Reversed) {
3550
3551 if (OldFunction->getNumNonObjectParams() !=
3552 NewFunction->getNumNonObjectParams())
3553 return false;
3554
3555 unsigned OldIgnore =
3557 unsigned NewIgnore =
3559
3560 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3561 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3562
3563 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3564 NewPT->param_types().slice(NewIgnore),
3565 ArgPos, Reversed);
3566}
3567
3569 CastKind &Kind,
3570 CXXCastPath& BasePath,
3571 bool IgnoreBaseAccess,
3572 bool Diagnose) {
3573 QualType FromType = From->getType();
3574 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3575
3576 Kind = CK_BitCast;
3577
3578 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3581 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3582 DiagRuntimeBehavior(From->getExprLoc(), From,
3583 PDiag(diag::warn_impcast_bool_to_null_pointer)
3584 << ToType << From->getSourceRange());
3585 else if (!isUnevaluatedContext())
3586 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3587 << ToType << From->getSourceRange();
3588 }
3589 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3590 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3591 QualType FromPointeeType = FromPtrType->getPointeeType(),
3592 ToPointeeType = ToPtrType->getPointeeType();
3593
3594 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3595 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3596 // We must have a derived-to-base conversion. Check an
3597 // ambiguous or inaccessible conversion.
3598 unsigned InaccessibleID = 0;
3599 unsigned AmbiguousID = 0;
3600 if (Diagnose) {
3601 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3602 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3603 }
3605 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3606 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3607 &BasePath, IgnoreBaseAccess))
3608 return true;
3609
3610 // The conversion was successful.
3611 Kind = CK_DerivedToBase;
3612 }
3613
3614 if (Diagnose && !IsCStyleOrFunctionalCast &&
3615 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3616 assert(getLangOpts().MSVCCompat &&
3617 "this should only be possible with MSVCCompat!");
3618 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3619 << From->getSourceRange();
3620 }
3621 }
3622 } else if (const ObjCObjectPointerType *ToPtrType =
3623 ToType->getAs<ObjCObjectPointerType>()) {
3624 if (const ObjCObjectPointerType *FromPtrType =
3625 FromType->getAs<ObjCObjectPointerType>()) {
3626 // Objective-C++ conversions are always okay.
3627 // FIXME: We should have a different class of conversions for the
3628 // Objective-C++ implicit conversions.
3629 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3630 return false;
3631 } else if (FromType->isBlockPointerType()) {
3632 Kind = CK_BlockPointerToObjCPointerCast;
3633 } else {
3634 Kind = CK_CPointerToObjCPointerCast;
3635 }
3636 } else if (ToType->isBlockPointerType()) {
3637 if (!FromType->isBlockPointerType())
3638 Kind = CK_AnyPointerToBlockPointerCast;
3639 }
3640
3641 // We shouldn't fall into this case unless it's valid for other
3642 // reasons.
3644 Kind = CK_NullToPointer;
3645
3646 return false;
3647}
3648
3650 QualType ToType,
3651 bool InOverloadResolution,
3652 QualType &ConvertedType) {
3653 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3654 if (!ToTypePtr)
3655 return false;
3656
3657 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3659 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3661 ConvertedType = ToType;
3662 return true;
3663 }
3664
3665 // Otherwise, both types have to be member pointers.
3666 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3667 if (!FromTypePtr)
3668 return false;
3669
3670 // A pointer to member of B can be converted to a pointer to member of D,
3671 // where D is derived from B (C++ 4.11p2).
3672 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3673 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3674
3675 if (!declaresSameEntity(FromClass, ToClass) &&
3676 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3677 ConvertedType = Context.getMemberPointerType(
3678 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3679 return true;
3680 }
3681
3682 return false;
3683}
3684
3686 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3687 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3688 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3689 // Lock down the inheritance model right now in MS ABI, whether or not the
3690 // pointee types are the same.
3691 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3692 (void)isCompleteType(CheckLoc, FromType);
3693 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3694 }
3695
3696 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3697 if (!FromPtrType) {
3698 // This must be a null pointer to member pointer conversion
3699 Kind = CK_NullToMemberPointer;
3701 }
3702
3703 // T == T, modulo cv
3705 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3706 ToPtrType->getPointeeType()))
3708
3709 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3710 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3711
3712 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3713 const CXXRecordDecl *Cls) {
3714 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3715 PD << Qual;
3716 else
3717 PD << Context.getCanonicalTagType(Cls);
3718 };
3719 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3720 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3721 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3722 return PD;
3723 };
3724
3725 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3727 std::swap(Base, Derived);
3728
3729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3730 /*DetectVirtual=*/true);
3731 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3733
3734 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3735 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3736 PD << int(Direction);
3737 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3738 Diag(CheckLoc, PD);
3740 }
3741
3742 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3743 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3744 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3745 Diag(CheckLoc, PD);
3747 }
3748
3749 // Must be a base to derived member conversion.
3750 BuildBasePathArray(Paths, BasePath);
3752 ? CK_DerivedToBaseMemberPointer
3753 : CK_BaseToDerivedMemberPointer;
3754
3755 if (!IgnoreBaseAccess)
3756 switch (CheckBaseClassAccess(
3757 CheckLoc, Base, Derived, Paths.front(),
3759 ? diag::err_upcast_to_inaccessible_base
3760 : diag::err_downcast_from_inaccessible_base,
3761 [&](PartialDiagnostic &PD) {
3762 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3763 DerivedQual = ToPtrType->getQualifier();
3764 if (Direction == MemberPointerConversionDirection::Upcast)
3765 std::swap(BaseQual, DerivedQual);
3766 DiagCls(PD, DerivedQual, Derived);
3767 DiagCls(PD, BaseQual, Base);
3768 })) {
3770 case Sema::AR_delayed:
3771 case Sema::AR_dependent:
3772 // Optimistically assume that the delayed and dependent cases
3773 // will work out.
3774 break;
3775
3778 }
3779
3781}
3782
3783/// Determine whether the lifetime conversion between the two given
3784/// qualifiers sets is nontrivial.
3786 Qualifiers ToQuals) {
3787 // Converting anything to const __unsafe_unretained is trivial.
3788 if (ToQuals.hasConst() &&
3790 return false;
3791
3792 return true;
3793}
3794
3795/// Perform a single iteration of the loop for checking if a qualification
3796/// conversion is valid.
3797///
3798/// Specifically, check whether any change between the qualifiers of \p
3799/// FromType and \p ToType is permissible, given knowledge about whether every
3800/// outer layer is const-qualified.
3802 bool CStyle, bool IsTopLevel,
3803 bool &PreviousToQualsIncludeConst,
3804 bool &ObjCLifetimeConversion,
3805 const ASTContext &Ctx) {
3806 Qualifiers FromQuals = FromType.getQualifiers();
3807 Qualifiers ToQuals = ToType.getQualifiers();
3808
3809 // Ignore __unaligned qualifier.
3810 FromQuals.removeUnaligned();
3811
3812 // Objective-C ARC:
3813 // Check Objective-C lifetime conversions.
3814 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3815 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3816 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3817 ObjCLifetimeConversion = true;
3818 FromQuals.removeObjCLifetime();
3819 ToQuals.removeObjCLifetime();
3820 } else {
3821 // Qualification conversions cannot cast between different
3822 // Objective-C lifetime qualifiers.
3823 return false;
3824 }
3825 }
3826
3827 // Allow addition/removal of GC attributes but not changing GC attributes.
3828 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3829 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3830 FromQuals.removeObjCGCAttr();
3831 ToQuals.removeObjCGCAttr();
3832 }
3833
3834 // __ptrauth qualifiers must match exactly.
3835 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3836 return false;
3837
3838 // -- for every j > 0, if const is in cv 1,j then const is in cv
3839 // 2,j, and similarly for volatile.
3840 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3841 return false;
3842
3843 // If address spaces mismatch:
3844 // - in top level it is only valid to convert to addr space that is a
3845 // superset in all cases apart from C-style casts where we allow
3846 // conversions between overlapping address spaces.
3847 // - in non-top levels it is not a valid conversion.
3848 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3849 (!IsTopLevel ||
3850 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3851 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3852 return false;
3853
3854 // -- if the cv 1,j and cv 2,j are different, then const is in
3855 // every cv for 0 < k < j.
3856 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3857 !PreviousToQualsIncludeConst)
3858 return false;
3859
3860 // The following wording is from C++20, where the result of the conversion
3861 // is T3, not T2.
3862 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3863 // "array of unknown bound of"
3864 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3865 return false;
3866
3867 // -- if the resulting P3,i is different from P1,i [...], then const is
3868 // added to every cv 3_k for 0 < k < i.
3869 if (!CStyle && FromType->isConstantArrayType() &&
3870 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3871 return false;
3872
3873 // Keep track of whether all prior cv-qualifiers in the "to" type
3874 // include const.
3875 PreviousToQualsIncludeConst =
3876 PreviousToQualsIncludeConst && ToQuals.hasConst();
3877 return true;
3878}
3879
3880bool
3882 bool CStyle, bool &ObjCLifetimeConversion) {
3883 FromType = Context.getCanonicalType(FromType);
3884 ToType = Context.getCanonicalType(ToType);
3885 ObjCLifetimeConversion = false;
3886
3887 // If FromType and ToType are the same type, this is not a
3888 // qualification conversion.
3889 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3890 return false;
3891
3892 // (C++ 4.4p4):
3893 // A conversion can add cv-qualifiers at levels other than the first
3894 // in multi-level pointers, subject to the following rules: [...]
3895 bool PreviousToQualsIncludeConst = true;
3896 bool UnwrappedAnyPointer = false;
3897 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3898 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3899 !UnwrappedAnyPointer,
3900 PreviousToQualsIncludeConst,
3901 ObjCLifetimeConversion, getASTContext()))
3902 return false;
3903 UnwrappedAnyPointer = true;
3904 }
3905
3906 // We are left with FromType and ToType being the pointee types
3907 // after unwrapping the original FromType and ToType the same number
3908 // of times. If we unwrapped any pointers, and if FromType and
3909 // ToType have the same unqualified type (since we checked
3910 // qualifiers above), then this is a qualification conversion.
3911 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3912}
3913
3914/// - Determine whether this is a conversion from a scalar type to an
3915/// atomic type.
3916///
3917/// If successful, updates \c SCS's second and third steps in the conversion
3918/// sequence to finish the conversion.
3919static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3920 bool InOverloadResolution,
3922 bool CStyle) {
3923 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3924 if (!ToAtomic)
3925 return false;
3926
3928 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3929 InOverloadResolution, InnerSCS,
3930 CStyle, /*AllowObjCWritebackConversion=*/false))
3931 return false;
3932
3933 SCS.Second = InnerSCS.Second;
3934 SCS.setToType(1, InnerSCS.getToType(1));
3935 SCS.Third = InnerSCS.Third;
3938 SCS.setToType(2, InnerSCS.getToType(2));
3939 return true;
3940}
3941
3944 QualType Type) {
3945 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3946 if (CtorType->getNumParams() > 0) {
3947 QualType FirstArg = CtorType->getParamType(0);
3948 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3949 return true;
3950 }
3951 return false;
3952}
3953
3954static OverloadingResult
3956 CXXRecordDecl *To,
3958 OverloadCandidateSet &CandidateSet,
3959 bool AllowExplicit) {
3961 for (auto *D : S.LookupConstructors(To)) {
3962 auto Info = getConstructorInfo(D);
3963 if (!Info)
3964 continue;
3965
3966 bool Usable = !Info.Constructor->isInvalidDecl() &&
3967 S.isInitListConstructor(Info.Constructor);
3968 if (Usable) {
3969 bool SuppressUserConversions = false;
3970 if (Info.ConstructorTmpl)
3971 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3972 /*ExplicitArgs*/ nullptr, From,
3973 CandidateSet, SuppressUserConversions,
3974 /*PartialOverloading*/ false,
3975 AllowExplicit);
3976 else
3977 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3978 CandidateSet, SuppressUserConversions,
3979 /*PartialOverloading*/ false, AllowExplicit);
3980 }
3981 }
3982
3983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3984
3986 switch (auto Result =
3987 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3988 case OR_Deleted:
3989 case OR_Success: {
3990 // Record the standard conversion we used and the conversion function.
3992 QualType ThisType = Constructor->getFunctionObjectParameterType();
3993 // Initializer lists don't have conversions as such.
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3997 User.FoundConversionFunction = Best->FoundDecl;
3999 User.After.setFromType(ThisType);
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003
4005 return OR_No_Viable_Function;
4006 case OR_Ambiguous:
4007 return OR_Ambiguous;
4008 }
4009
4010 llvm_unreachable("Invalid OverloadResult!");
4011}
4012
4013/// Determines whether there is a user-defined conversion sequence
4014/// (C++ [over.ics.user]) that converts expression From to the type
4015/// ToType. If such a conversion exists, User will contain the
4016/// user-defined conversion sequence that performs such a conversion
4017/// and this routine will return true. Otherwise, this routine returns
4018/// false and User is unspecified.
4019///
4020/// \param AllowExplicit true if the conversion should consider C++0x
4021/// "explicit" conversion functions as well as non-explicit conversion
4022/// functions (C++0x [class.conv.fct]p2).
4023///
4024/// \param AllowObjCConversionOnExplicit true if the conversion should
4025/// allow an extra Objective-C pointer conversion on uses of explicit
4026/// constructors. Requires \c AllowExplicit to also be set.
4027static OverloadingResult
4030 OverloadCandidateSet &CandidateSet,
4031 AllowedExplicit AllowExplicit,
4032 bool AllowObjCConversionOnExplicit) {
4033 assert(AllowExplicit != AllowedExplicit::None ||
4034 !AllowObjCConversionOnExplicit);
4036
4037 // Whether we will only visit constructors.
4038 bool ConstructorsOnly = false;
4039
4040 // If the type we are conversion to is a class type, enumerate its
4041 // constructors.
4042 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4043 // C++ [over.match.ctor]p1:
4044 // When objects of class type are direct-initialized (8.5), or
4045 // copy-initialized from an expression of the same or a
4046 // derived class type (8.5), overload resolution selects the
4047 // constructor. [...] For copy-initialization, the candidate
4048 // functions are all the converting constructors (12.3.1) of
4049 // that class. The argument list is the expression-list within
4050 // the parentheses of the initializer.
4051 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4052 (From->getType()->isRecordType() &&
4053 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4054 ConstructorsOnly = true;
4055
4056 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4057 // We're not going to find any constructors.
4058 } else if (auto *ToRecordDecl =
4059 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4060 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4061
4062 Expr **Args = &From;
4063 unsigned NumArgs = 1;
4064 bool ListInitializing = false;
4065 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4066 // But first, see if there is an init-list-constructor that will work.
4068 S, From, ToType, ToRecordDecl, User, CandidateSet,
4069 AllowExplicit == AllowedExplicit::All);
4070 if (Result != OR_No_Viable_Function)
4071 return Result;
4072 // Never mind.
4073 CandidateSet.clear(
4075
4076 // If we're list-initializing, we pass the individual elements as
4077 // arguments, not the entire list.
4078 Args = InitList->getInits();
4079 NumArgs = InitList->getNumInits();
4080 ListInitializing = true;
4081 }
4082
4083 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4084 auto Info = getConstructorInfo(D);
4085 if (!Info)
4086 continue;
4087
4088 bool Usable = !Info.Constructor->isInvalidDecl();
4089 if (!ListInitializing)
4090 Usable = Usable && Info.Constructor->isConvertingConstructor(
4091 /*AllowExplicit*/ true);
4092 if (Usable) {
4093 bool SuppressUserConversions = !ConstructorsOnly;
4094 // C++20 [over.best.ics.general]/4.5:
4095 // if the target is the first parameter of a constructor [of class
4096 // X] and the constructor [...] is a candidate by [...] the second
4097 // phase of [over.match.list] when the initializer list has exactly
4098 // one element that is itself an initializer list, [...] and the
4099 // conversion is to X or reference to cv X, user-defined conversion
4100 // sequences are not considered.
4101 if (SuppressUserConversions && ListInitializing) {
4102 SuppressUserConversions =
4103 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4104 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4105 ToType);
4106 }
4107 if (Info.ConstructorTmpl)
4109 Info.ConstructorTmpl, Info.FoundDecl,
4110 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4111 CandidateSet, SuppressUserConversions,
4112 /*PartialOverloading*/ false,
4113 AllowExplicit == AllowedExplicit::All);
4114 else
4115 // Allow one user-defined conversion when user specifies a
4116 // From->ToType conversion via an static cast (c-style, etc).
4117 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4118 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4119 SuppressUserConversions,
4120 /*PartialOverloading*/ false,
4121 AllowExplicit == AllowedExplicit::All);
4122 }
4123 }
4124 }
4125 }
4126
4127 // Enumerate conversion functions, if we're allowed to.
4128 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4129 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4130 // No conversion functions from incomplete types.
4131 } else if (const RecordType *FromRecordType =
4132 From->getType()->getAsCanonical<RecordType>()) {
4133 if (auto *FromRecordDecl =
4134 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4135 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4136 // Add all of the conversion functions as candidates.
4137 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4138 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4139 DeclAccessPair FoundDecl = I.getPair();
4140 NamedDecl *D = FoundDecl.getDecl();
4141 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4142 if (isa<UsingShadowDecl>(D))
4143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4144
4145 CXXConversionDecl *Conv;
4146 FunctionTemplateDecl *ConvTemplate;
4147 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4148 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4149 else
4150 Conv = cast<CXXConversionDecl>(D);
4151
4152 if (ConvTemplate)
4154 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4155 CandidateSet, AllowObjCConversionOnExplicit,
4156 AllowExplicit != AllowedExplicit::None);
4157 else
4158 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4159 CandidateSet, AllowObjCConversionOnExplicit,
4160 AllowExplicit != AllowedExplicit::None);
4161 }
4162 }
4163 }
4164
4165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4166
4168 switch (auto Result =
4169 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4170 case OR_Success:
4171 case OR_Deleted:
4172 // Record the standard conversion we used and the conversion function.
4174 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4175 // C++ [over.ics.user]p1:
4176 // If the user-defined conversion is specified by a
4177 // constructor (12.3.1), the initial standard conversion
4178 // sequence converts the source type to the type required by
4179 // the argument of the constructor.
4180 //
4181 if (isa<InitListExpr>(From)) {
4182 // Initializer lists don't have conversions as such.
4184 User.Before.FromBracedInitList = true;
4185 } else {
4186 if (Best->Conversions[0].isEllipsis())
4187 User.EllipsisConversion = true;
4188 else {
4189 User.Before = Best->Conversions[0].Standard;
4190 User.EllipsisConversion = false;
4191 }
4192 }
4193 User.HadMultipleCandidates = HadMultipleCandidates;
4195 User.FoundConversionFunction = Best->FoundDecl;
4197 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4198 User.After.setAllToTypes(ToType);
4199 return Result;
4200 }
4201 if (CXXConversionDecl *Conversion
4202 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4203
4204 assert(Best->HasFinalConversion);
4205
4206 // C++ [over.ics.user]p1:
4207 //
4208 // [...] If the user-defined conversion is specified by a
4209 // conversion function (12.3.2), the initial standard
4210 // conversion sequence converts the source type to the
4211 // implicit object parameter of the conversion function.
4212 User.Before = Best->Conversions[0].Standard;
4213 User.HadMultipleCandidates = HadMultipleCandidates;
4214 User.ConversionFunction = Conversion;
4215 User.FoundConversionFunction = Best->FoundDecl;
4216 User.EllipsisConversion = false;
4217
4218 // C++ [over.ics.user]p2:
4219 // The second standard conversion sequence converts the
4220 // result of the user-defined conversion to the target type
4221 // for the sequence. Since an implicit conversion sequence
4222 // is an initialization, the special rules for
4223 // initialization by user-defined conversion apply when
4224 // selecting the best user-defined conversion for a
4225 // user-defined conversion sequence (see 13.3.3 and
4226 // 13.3.3.1).
4227 User.After = Best->FinalConversion;
4228 return Result;
4229 }
4230 llvm_unreachable("Not a constructor or conversion function?");
4231
4233 return OR_No_Viable_Function;
4234
4235 case OR_Ambiguous:
4236 return OR_Ambiguous;
4237 }
4238
4239 llvm_unreachable("Invalid OverloadResult!");
4240}
4241
4242bool
4245 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4247 OverloadingResult OvResult =
4248 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4249 CandidateSet, AllowedExplicit::None, false);
4250
4251 if (!(OvResult == OR_Ambiguous ||
4252 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4253 return false;
4254
4255 auto Cands = CandidateSet.CompleteCandidates(
4256 *this,
4258 From);
4259 if (OvResult == OR_Ambiguous)
4260 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4261 << From->getType() << ToType << From->getSourceRange();
4262 else { // OR_No_Viable_Function && !CandidateSet.empty()
4263 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4264 diag::err_typecheck_nonviable_condition_incomplete,
4265 From->getType(), From->getSourceRange()))
4266 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4267 << false << From->getType() << From->getSourceRange() << ToType;
4268 }
4269
4270 CandidateSet.NoteCandidates(
4271 *this, From, Cands);
4272 return true;
4273}
4274
4275// Helper for compareConversionFunctions that gets the FunctionType that the
4276// conversion-operator return value 'points' to, or nullptr.
4277static const FunctionType *
4279 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4280 const PointerType *RetPtrTy =
4281 ConvFuncTy->getReturnType()->getAs<PointerType>();
4282
4283 if (!RetPtrTy)
4284 return nullptr;
4285
4286 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4287}
4288
4289/// Compare the user-defined conversion functions or constructors
4290/// of two user-defined conversion sequences to determine whether any ordering
4291/// is possible.
4294 FunctionDecl *Function2) {
4295 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4296 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4297 if (!Conv1 || !Conv2)
4299
4300 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4302
4303 // Objective-C++:
4304 // If both conversion functions are implicitly-declared conversions from
4305 // a lambda closure type to a function pointer and a block pointer,
4306 // respectively, always prefer the conversion to a function pointer,
4307 // because the function pointer is more lightweight and is more likely
4308 // to keep code working.
4309 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4310 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4311 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4312 if (Block1 != Block2)
4313 return Block1 ? ImplicitConversionSequence::Worse
4315 }
4316
4317 // In order to support multiple calling conventions for the lambda conversion
4318 // operator (such as when the free and member function calling convention is
4319 // different), prefer the 'free' mechanism, followed by the calling-convention
4320 // of operator(). The latter is in place to support the MSVC-like solution of
4321 // defining ALL of the possible conversions in regards to calling-convention.
4322 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4323 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4324
4325 if (Conv1FuncRet && Conv2FuncRet &&
4326 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4327 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4328 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4329
4330 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4331 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4332
4333 CallingConv CallOpCC =
4334 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4336 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4338 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4339
4340 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4341 for (CallingConv CC : PrefOrder) {
4342 if (Conv1CC == CC)
4344 if (Conv2CC == CC)
4346 }
4347 }
4348
4350}
4351
4358
4359/// CompareImplicitConversionSequences - Compare two implicit
4360/// conversion sequences to determine whether one is better than the
4361/// other or if they are indistinguishable (C++ 13.3.3.2).
4364 const ImplicitConversionSequence& ICS1,
4365 const ImplicitConversionSequence& ICS2)
4366{
4367 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4368 // conversion sequences (as defined in 13.3.3.1)
4369 // -- a standard conversion sequence (13.3.3.1.1) is a better
4370 // conversion sequence than a user-defined conversion sequence or
4371 // an ellipsis conversion sequence, and
4372 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4373 // conversion sequence than an ellipsis conversion sequence
4374 // (13.3.3.1.3).
4375 //
4376 // C++0x [over.best.ics]p10:
4377 // For the purpose of ranking implicit conversion sequences as
4378 // described in 13.3.3.2, the ambiguous conversion sequence is
4379 // treated as a user-defined sequence that is indistinguishable
4380 // from any other user-defined conversion sequence.
4381
4382 // String literal to 'char *' conversion has been deprecated in C++03. It has
4383 // been removed from C++11. We still accept this conversion, if it happens at
4384 // the best viable function. Otherwise, this conversion is considered worse
4385 // than ellipsis conversion. Consider this as an extension; this is not in the
4386 // standard. For example:
4387 //
4388 // int &f(...); // #1
4389 // void f(char*); // #2
4390 // void g() { int &r = f("foo"); }
4391 //
4392 // In C++03, we pick #2 as the best viable function.
4393 // In C++11, we pick #1 as the best viable function, because ellipsis
4394 // conversion is better than string-literal to char* conversion (since there
4395 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4396 // convert arguments, #2 would be the best viable function in C++11.
4397 // If the best viable function has this conversion, a warning will be issued
4398 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4399
4400 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4403 // Ill-formedness must not differ
4404 ICS1.isBad() == ICS2.isBad())
4408
4409 if (ICS1.getKindRank() < ICS2.getKindRank())
4411 if (ICS2.getKindRank() < ICS1.getKindRank())
4413
4414 // The following checks require both conversion sequences to be of
4415 // the same kind.
4416 if (ICS1.getKind() != ICS2.getKind())
4418
4421
4422 // Two implicit conversion sequences of the same form are
4423 // indistinguishable conversion sequences unless one of the
4424 // following rules apply: (C++ 13.3.3.2p3):
4425
4426 // List-initialization sequence L1 is a better conversion sequence than
4427 // list-initialization sequence L2 if:
4428 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4429 // if not that,
4430 // — L1 and L2 convert to arrays of the same element type, and either the
4431 // number of elements n_1 initialized by L1 is less than the number of
4432 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4433 // an array of unknown bound and L1 does not,
4434 // even if one of the other rules in this paragraph would otherwise apply.
4435 if (!ICS1.isBad()) {
4436 bool StdInit1 = false, StdInit2 = false;
4439 nullptr);
4442 nullptr);
4443 if (StdInit1 != StdInit2)
4444 return StdInit1 ? ImplicitConversionSequence::Better
4446
4449 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4451 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4453 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4454 CAT2->getElementType())) {
4455 // Both to arrays of the same element type
4456 if (CAT1->getSize() != CAT2->getSize())
4457 // Different sized, the smaller wins
4458 return CAT1->getSize().ult(CAT2->getSize())
4463 // One is incomplete, it loses
4467 }
4468 }
4469 }
4470
4471 if (ICS1.isStandard())
4472 // Standard conversion sequence S1 is a better conversion sequence than
4473 // standard conversion sequence S2 if [...]
4474 Result = CompareStandardConversionSequences(S, Loc,
4475 ICS1.Standard, ICS2.Standard);
4476 else if (ICS1.isUserDefined()) {
4477 // With lazy template loading, it is possible to find non-canonical
4478 // FunctionDecls, depending on when redecl chains are completed. Make sure
4479 // to compare the canonical decls of conversion functions. This avoids
4480 // ambiguity problems for templated conversion operators.
4481 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4482 if (ConvFunc1)
4483 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4484 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4485 if (ConvFunc2)
4486 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4487 // User-defined conversion sequence U1 is a better conversion
4488 // sequence than another user-defined conversion sequence U2 if
4489 // they contain the same user-defined conversion function or
4490 // constructor and if the second standard conversion sequence of
4491 // U1 is better than the second standard conversion sequence of
4492 // U2 (C++ 13.3.3.2p3).
4493 if (ConvFunc1 == ConvFunc2)
4494 Result = CompareStandardConversionSequences(S, Loc,
4495 ICS1.UserDefined.After,
4496 ICS2.UserDefined.After);
4497 else
4498 Result = compareConversionFunctions(S,
4501 }
4502
4503 return Result;
4504}
4505
4506// Per 13.3.3.2p3, compare the given standard conversion sequences to
4507// determine if one is a proper subset of the other.
4510 const StandardConversionSequence& SCS1,
4511 const StandardConversionSequence& SCS2) {
4514
4515 // the identity conversion sequence is considered to be a subsequence of
4516 // any non-identity conversion sequence
4517 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4519 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4521
4522 if (SCS1.Second != SCS2.Second) {
4523 if (SCS1.Second == ICK_Identity)
4525 else if (SCS2.Second == ICK_Identity)
4527 else
4529 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4531
4532 if (SCS1.Third == SCS2.Third) {
4533 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4535 }
4536
4537 if (SCS1.Third == ICK_Identity)
4538 return Result == ImplicitConversionSequence::Worse
4541
4542 if (SCS2.Third == ICK_Identity)
4543 return Result == ImplicitConversionSequence::Better
4546
4548}
4549
4550/// Determine whether one of the given reference bindings is better
4551/// than the other based on what kind of bindings they are.
4552static bool
4554 const StandardConversionSequence &SCS2) {
4555 // C++0x [over.ics.rank]p3b4:
4556 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4557 // implicit object parameter of a non-static member function declared
4558 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4559 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4560 // lvalue reference to a function lvalue and S2 binds an rvalue
4561 // reference*.
4562 //
4563 // FIXME: Rvalue references. We're going rogue with the above edits,
4564 // because the semantics in the current C++0x working paper (N3225 at the
4565 // time of this writing) break the standard definition of std::forward
4566 // and std::reference_wrapper when dealing with references to functions.
4567 // Proposed wording changes submitted to CWG for consideration.
4570 return false;
4571
4572 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4573 SCS2.IsLvalueReference) ||
4576}
4577
4583
4584/// Returns kind of fixed enum promotion the \a SCS uses.
4585static FixedEnumPromotion
4587
4588 if (SCS.Second != ICK_Integral_Promotion)
4590
4591 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4592 if (!Enum)
4594
4595 if (!Enum->isFixed())
4597
4598 QualType UnderlyingType = Enum->getIntegerType();
4599 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4601
4603}
4604
4605/// CompareStandardConversionSequences - Compare two standard
4606/// conversion sequences to determine whether one is better than the
4607/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4610 const StandardConversionSequence& SCS1,
4611 const StandardConversionSequence& SCS2)
4612{
4613 // Standard conversion sequence S1 is a better conversion sequence
4614 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4615
4616 // -- S1 is a proper subsequence of S2 (comparing the conversion
4617 // sequences in the canonical form defined by 13.3.3.1.1,
4618 // excluding any Lvalue Transformation; the identity conversion
4619 // sequence is considered to be a subsequence of any
4620 // non-identity conversion sequence) or, if not that,
4623 return CK;
4624
4625 // -- the rank of S1 is better than the rank of S2 (by the rules
4626 // defined below), or, if not that,
4627 ImplicitConversionRank Rank1 = SCS1.getRank();
4628 ImplicitConversionRank Rank2 = SCS2.getRank();
4629 if (Rank1 < Rank2)
4631 else if (Rank2 < Rank1)
4633
4634 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4635 // are indistinguishable unless one of the following rules
4636 // applies:
4637
4638 // A conversion that is not a conversion of a pointer, or
4639 // pointer to member, to bool is better than another conversion
4640 // that is such a conversion.
4642 return SCS2.isPointerConversionToBool()
4645
4646 // C++14 [over.ics.rank]p4b2:
4647 // This is retroactively applied to C++11 by CWG 1601.
4648 //
4649 // A conversion that promotes an enumeration whose underlying type is fixed
4650 // to its underlying type is better than one that promotes to the promoted
4651 // underlying type, if the two are different.
4654 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4655 FEP1 != FEP2)
4659
4660 // C++ [over.ics.rank]p4b2:
4661 //
4662 // If class B is derived directly or indirectly from class A,
4663 // conversion of B* to A* is better than conversion of B* to
4664 // void*, and conversion of A* to void* is better than conversion
4665 // of B* to void*.
4666 bool SCS1ConvertsToVoid
4668 bool SCS2ConvertsToVoid
4670 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4671 // Exactly one of the conversion sequences is a conversion to
4672 // a void pointer; it's the worse conversion.
4673 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4675 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4676 // Neither conversion sequence converts to a void pointer; compare
4677 // their derived-to-base conversions.
4679 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4680 return DerivedCK;
4681 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4682 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4683 // Both conversion sequences are conversions to void
4684 // pointers. Compare the source types to determine if there's an
4685 // inheritance relationship in their sources.
4686 QualType FromType1 = SCS1.getFromType();
4687 QualType FromType2 = SCS2.getFromType();
4688
4689 // Adjust the types we're converting from via the array-to-pointer
4690 // conversion, if we need to.
4691 if (SCS1.First == ICK_Array_To_Pointer)
4692 FromType1 = S.Context.getArrayDecayedType(FromType1);
4693 if (SCS2.First == ICK_Array_To_Pointer)
4694 FromType2 = S.Context.getArrayDecayedType(FromType2);
4695
4696 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4697 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4698
4699 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4701 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4703
4704 // Objective-C++: If one interface is more specific than the
4705 // other, it is the better one.
4706 const ObjCObjectPointerType* FromObjCPtr1
4707 = FromType1->getAs<ObjCObjectPointerType>();
4708 const ObjCObjectPointerType* FromObjCPtr2
4709 = FromType2->getAs<ObjCObjectPointerType>();
4710 if (FromObjCPtr1 && FromObjCPtr2) {
4711 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4712 FromObjCPtr2);
4713 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4714 FromObjCPtr1);
4715 if (AssignLeft != AssignRight) {
4716 return AssignLeft? ImplicitConversionSequence::Better
4718 }
4719 }
4720 }
4721
4722 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4723 // Check for a better reference binding based on the kind of bindings.
4724 if (isBetterReferenceBindingKind(SCS1, SCS2))
4726 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4728 }
4729
4730 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4731 // bullet 3).
4733 = CompareQualificationConversions(S, SCS1, SCS2))
4734 return QualCK;
4735
4736 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4737 // C++ [over.ics.rank]p3b4:
4738 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4739 // which the references refer are the same type except for
4740 // top-level cv-qualifiers, and the type to which the reference
4741 // initialized by S2 refers is more cv-qualified than the type
4742 // to which the reference initialized by S1 refers.
4743 QualType T1 = SCS1.getToType(2);
4744 QualType T2 = SCS2.getToType(2);
4745 T1 = S.Context.getCanonicalType(T1);
4746 T2 = S.Context.getCanonicalType(T2);
4747 Qualifiers T1Quals, T2Quals;
4748 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4749 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4750 if (UnqualT1 == UnqualT2) {
4751 // Objective-C++ ARC: If the references refer to objects with different
4752 // lifetimes, prefer bindings that don't change lifetime.
4758 }
4759
4760 // If the type is an array type, promote the element qualifiers to the
4761 // type for comparison.
4762 if (isa<ArrayType>(T1) && T1Quals)
4763 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4764 if (isa<ArrayType>(T2) && T2Quals)
4765 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4766 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4768 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4770 }
4771 }
4772
4773 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4774 // floating-to-integral conversion if the integral conversion
4775 // is between types of the same size.
4776 // For example:
4777 // void f(float);
4778 // void f(int);
4779 // int main {
4780 // long a;
4781 // f(a);
4782 // }
4783 // Here, MSVC will call f(int) instead of generating a compile error
4784 // as clang will do in standard mode.
4785 if (S.getLangOpts().MSVCCompat &&
4788 SCS2.Second == ICK_Floating_Integral &&
4789 S.Context.getTypeSize(SCS1.getFromType()) ==
4790 S.Context.getTypeSize(SCS1.getToType(2)))
4792
4793 // Prefer a compatible vector conversion over a lax vector conversion
4794 // For example:
4795 //
4796 // typedef float __v4sf __attribute__((__vector_size__(16)));
4797 // void f(vector float);
4798 // void f(vector signed int);
4799 // int main() {
4800 // __v4sf a;
4801 // f(a);
4802 // }
4803 // Here, we'd like to choose f(vector float) and not
4804 // report an ambiguous call error
4805 if (SCS1.Second == ICK_Vector_Conversion &&
4806 SCS2.Second == ICK_Vector_Conversion) {
4807 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4808 SCS1.getFromType(), SCS1.getToType(2));
4809 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4810 SCS2.getFromType(), SCS2.getToType(2));
4811
4812 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4813 return SCS1IsCompatibleVectorConversion
4816 }
4817
4818 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4820 bool SCS1IsCompatibleSVEVectorConversion =
4821 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4822 bool SCS2IsCompatibleSVEVectorConversion =
4823 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4824
4825 if (SCS1IsCompatibleSVEVectorConversion !=
4826 SCS2IsCompatibleSVEVectorConversion)
4827 return SCS1IsCompatibleSVEVectorConversion
4830 }
4831
4832 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4834 bool SCS1IsCompatibleRVVVectorConversion =
4836 bool SCS2IsCompatibleRVVVectorConversion =
4838
4839 if (SCS1IsCompatibleRVVVectorConversion !=
4840 SCS2IsCompatibleRVVVectorConversion)
4841 return SCS1IsCompatibleRVVVectorConversion
4844 }
4846}
4847
4848/// CompareQualificationConversions - Compares two standard conversion
4849/// sequences to determine whether they can be ranked based on their
4850/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4853 const StandardConversionSequence& SCS1,
4854 const StandardConversionSequence& SCS2) {
4855 // C++ [over.ics.rank]p3:
4856 // -- S1 and S2 differ only in their qualification conversion and
4857 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4858 // [C++98]
4859 // [...] and the cv-qualification signature of type T1 is a proper subset
4860 // of the cv-qualification signature of type T2, and S1 is not the
4861 // deprecated string literal array-to-pointer conversion (4.2).
4862 // [C++2a]
4863 // [...] where T1 can be converted to T2 by a qualification conversion.
4864 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4865 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4867
4868 // FIXME: the example in the standard doesn't use a qualification
4869 // conversion (!)
4870 QualType T1 = SCS1.getToType(2);
4871 QualType T2 = SCS2.getToType(2);
4872 T1 = S.Context.getCanonicalType(T1);
4873 T2 = S.Context.getCanonicalType(T2);
4874 assert(!T1->isReferenceType() && !T2->isReferenceType());
4875 Qualifiers T1Quals, T2Quals;
4876 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4877 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4878
4879 // If the types are the same, we won't learn anything by unwrapping
4880 // them.
4881 if (UnqualT1 == UnqualT2)
4883
4884 // Don't ever prefer a standard conversion sequence that uses the deprecated
4885 // string literal array to pointer conversion.
4886 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4887 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4888
4889 // Objective-C++ ARC:
4890 // Prefer qualification conversions not involving a change in lifetime
4891 // to qualification conversions that do change lifetime.
4894 CanPick1 = false;
4897 CanPick2 = false;
4898
4899 bool ObjCLifetimeConversion;
4900 if (CanPick1 &&
4901 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4902 CanPick1 = false;
4903 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4904 // directions, so we can't short-cut this second check in general.
4905 if (CanPick2 &&
4906 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4907 CanPick2 = false;
4908
4909 if (CanPick1 != CanPick2)
4910 return CanPick1 ? ImplicitConversionSequence::Better
4913}
4914
4915/// CompareDerivedToBaseConversions - Compares two standard conversion
4916/// sequences to determine whether they can be ranked based on their
4917/// various kinds of derived-to-base conversions (C++
4918/// [over.ics.rank]p4b3). As part of these checks, we also look at
4919/// conversions between Objective-C interface types.
4922 const StandardConversionSequence& SCS1,
4923 const StandardConversionSequence& SCS2) {
4924 QualType FromType1 = SCS1.getFromType();
4925 QualType ToType1 = SCS1.getToType(1);
4926 QualType FromType2 = SCS2.getFromType();
4927 QualType ToType2 = SCS2.getToType(1);
4928
4929 // Adjust the types we're converting from via the array-to-pointer
4930 // conversion, if we need to.
4931 if (SCS1.First == ICK_Array_To_Pointer)
4932 FromType1 = S.Context.getArrayDecayedType(FromType1);
4933 if (SCS2.First == ICK_Array_To_Pointer)
4934 FromType2 = S.Context.getArrayDecayedType(FromType2);
4935
4936 // Canonicalize all of the types.
4937 FromType1 = S.Context.getCanonicalType(FromType1);
4938 ToType1 = S.Context.getCanonicalType(ToType1);
4939 FromType2 = S.Context.getCanonicalType(FromType2);
4940 ToType2 = S.Context.getCanonicalType(ToType2);
4941
4942 // C++ [over.ics.rank]p4b3:
4943 //
4944 // If class B is derived directly or indirectly from class A and
4945 // class C is derived directly or indirectly from B,
4946 //
4947 // Compare based on pointer conversions.
4948 if (SCS1.Second == ICK_Pointer_Conversion &&
4950 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4951 FromType1->isPointerType() && FromType2->isPointerType() &&
4952 ToType1->isPointerType() && ToType2->isPointerType()) {
4953 QualType FromPointee1 =
4955 QualType ToPointee1 =
4957 QualType FromPointee2 =
4959 QualType ToPointee2 =
4961
4962 // -- conversion of C* to B* is better than conversion of C* to A*,
4963 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4964 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4966 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4968 }
4969
4970 // -- conversion of B* to A* is better than conversion of C* to A*,
4971 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4972 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4974 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4976 }
4977 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4979 const ObjCObjectPointerType *FromPtr1
4980 = FromType1->getAs<ObjCObjectPointerType>();
4981 const ObjCObjectPointerType *FromPtr2
4982 = FromType2->getAs<ObjCObjectPointerType>();
4983 const ObjCObjectPointerType *ToPtr1
4984 = ToType1->getAs<ObjCObjectPointerType>();
4985 const ObjCObjectPointerType *ToPtr2
4986 = ToType2->getAs<ObjCObjectPointerType>();
4987
4988 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4989 // Apply the same conversion ranking rules for Objective-C pointer types
4990 // that we do for C++ pointers to class types. However, we employ the
4991 // Objective-C pseudo-subtyping relationship used for assignment of
4992 // Objective-C pointer types.
4993 bool FromAssignLeft
4994 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4995 bool FromAssignRight
4996 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4997 bool ToAssignLeft
4998 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4999 bool ToAssignRight
5000 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5001
5002 // A conversion to an a non-id object pointer type or qualified 'id'
5003 // type is better than a conversion to 'id'.
5004 if (ToPtr1->isObjCIdType() &&
5005 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5007 if (ToPtr2->isObjCIdType() &&
5008 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5010
5011 // A conversion to a non-id object pointer type is better than a
5012 // conversion to a qualified 'id' type
5013 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5015 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5017
5018 // A conversion to an a non-Class object pointer type or qualified 'Class'
5019 // type is better than a conversion to 'Class'.
5020 if (ToPtr1->isObjCClassType() &&
5021 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5023 if (ToPtr2->isObjCClassType() &&
5024 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5026
5027 // A conversion to a non-Class object pointer type is better than a
5028 // conversion to a qualified 'Class' type.
5029 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5031 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5033
5034 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5035 if (S.Context.hasSameType(FromType1, FromType2) &&
5036 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5037 (ToAssignLeft != ToAssignRight)) {
5038 if (FromPtr1->isSpecialized()) {
5039 // "conversion of B<A> * to B * is better than conversion of B * to
5040 // C *.
5041 bool IsFirstSame =
5042 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5043 bool IsSecondSame =
5044 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5045 if (IsFirstSame) {
5046 if (!IsSecondSame)
5048 } else if (IsSecondSame)
5050 }
5051 return ToAssignLeft? ImplicitConversionSequence::Worse
5053 }
5054
5055 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5056 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5057 (FromAssignLeft != FromAssignRight))
5058 return FromAssignLeft? ImplicitConversionSequence::Better
5060 }
5061 }
5062
5063 // Ranking of member-pointer types.
5064 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5065 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5066 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5067 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5068 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5069 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5070 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5071 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5072 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5073 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5074 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5075 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5076 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5077 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5079 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5081 }
5082 // conversion of B::* to C::* is better than conversion of A::* to C::*
5083 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5084 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5086 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5088 }
5089 }
5090
5091 if (SCS1.Second == ICK_Derived_To_Base) {
5092 // -- conversion of C to B is better than conversion of C to A,
5093 // -- binding of an expression of type C to a reference of type
5094 // B& is better than binding an expression of type C to a
5095 // reference of type A&,
5096 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5097 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5098 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5100 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5102 }
5103
5104 // -- conversion of B to A is better than conversion of C to A.
5105 // -- binding of an expression of type B to a reference of type
5106 // A& is better than binding an expression of type C to a
5107 // reference of type A&,
5108 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5109 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5110 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5112 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5114 }
5115 }
5116
5118}
5119
5121 if (!T.getQualifiers().hasUnaligned())
5122 return T;
5123
5124 Qualifiers Q;
5125 T = Ctx.getUnqualifiedArrayType(T, Q);
5126 Q.removeUnaligned();
5127 return Ctx.getQualifiedType(T, Q);
5128}
5129
5132 QualType OrigT1, QualType OrigT2,
5133 ReferenceConversions *ConvOut) {
5134 assert(!OrigT1->isReferenceType() &&
5135 "T1 must be the pointee type of the reference type");
5136 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5137
5138 QualType T1 = Context.getCanonicalType(OrigT1);
5139 QualType T2 = Context.getCanonicalType(OrigT2);
5140 Qualifiers T1Quals, T2Quals;
5141 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5142 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5143
5144 ReferenceConversions ConvTmp;
5145 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5146 Conv = ReferenceConversions();
5147
5148 // C++2a [dcl.init.ref]p4:
5149 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5150 // reference-related to "cv2 T2" if T1 is similar to T2, or
5151 // T1 is a base class of T2.
5152 // "cv1 T1" is reference-compatible with "cv2 T2" if
5153 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5154 // "pointer to cv1 T1" via a standard conversion sequence.
5155
5156 // Check for standard conversions we can apply to pointers: derived-to-base
5157 // conversions, ObjC pointer conversions, and function pointer conversions.
5158 // (Qualification conversions are checked last.)
5159 if (UnqualT1 == UnqualT2) {
5160 // Nothing to do.
5161 } else if (isCompleteType(Loc, OrigT2) &&
5162 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5163 Conv |= ReferenceConversions::DerivedToBase;
5164 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5165 UnqualT2->isObjCObjectOrInterfaceType() &&
5166 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5167 Conv |= ReferenceConversions::ObjC;
5168 else if (UnqualT2->isFunctionType() &&
5169 IsFunctionConversion(UnqualT2, UnqualT1)) {
5170 Conv |= ReferenceConversions::Function;
5171 // No need to check qualifiers; function types don't have them.
5172 return Ref_Compatible;
5173 }
5174 bool ConvertedReferent = Conv != 0;
5175
5176 // We can have a qualification conversion. Compute whether the types are
5177 // similar at the same time.
5178 bool PreviousToQualsIncludeConst = true;
5179 bool TopLevel = true;
5180 do {
5181 if (T1 == T2)
5182 break;
5183
5184 // We will need a qualification conversion.
5185 Conv |= ReferenceConversions::Qualification;
5186
5187 // Track whether we performed a qualification conversion anywhere other
5188 // than the top level. This matters for ranking reference bindings in
5189 // overload resolution.
5190 if (!TopLevel)
5191 Conv |= ReferenceConversions::NestedQualification;
5192
5193 // MS compiler ignores __unaligned qualifier for references; do the same.
5194 T1 = withoutUnaligned(Context, T1);
5195 T2 = withoutUnaligned(Context, T2);
5196
5197 // If we find a qualifier mismatch, the types are not reference-compatible,
5198 // but are still be reference-related if they're similar.
5199 bool ObjCLifetimeConversion = false;
5200 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5201 PreviousToQualsIncludeConst,
5202 ObjCLifetimeConversion, getASTContext()))
5203 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5204 ? Ref_Related
5206
5207 // FIXME: Should we track this for any level other than the first?
5208 if (ObjCLifetimeConversion)
5209 Conv |= ReferenceConversions::ObjCLifetime;
5210
5211 TopLevel = false;
5212 } while (Context.UnwrapSimilarTypes(T1, T2));
5213
5214 // At this point, if the types are reference-related, we must either have the
5215 // same inner type (ignoring qualifiers), or must have already worked out how
5216 // to convert the referent.
5217 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5220}
5221
5222/// Look for a user-defined conversion to a value reference-compatible
5223/// with DeclType. Return true if something definite is found.
5224static bool
5226 QualType DeclType, SourceLocation DeclLoc,
5227 Expr *Init, QualType T2, bool AllowRvalues,
5228 bool AllowExplicit) {
5229 assert(T2->isRecordType() && "Can only find conversions of record types.");
5230 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5231 OverloadCandidateSet CandidateSet(
5233 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5234 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5235 NamedDecl *D = *I;
5237 if (isa<UsingShadowDecl>(D))
5238 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5239
5240 FunctionTemplateDecl *ConvTemplate
5241 = dyn_cast<FunctionTemplateDecl>(D);
5242 CXXConversionDecl *Conv;
5243 if (ConvTemplate)
5244 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5245 else
5246 Conv = cast<CXXConversionDecl>(D);
5247
5248 if (AllowRvalues) {
5249 // If we are initializing an rvalue reference, don't permit conversion
5250 // functions that return lvalues.
5251 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5252 const ReferenceType *RefType
5254 if (RefType && !RefType->getPointeeType()->isFunctionType())
5255 continue;
5256 }
5257
5258 if (!ConvTemplate &&
5260 DeclLoc,
5261 Conv->getConversionType()
5266 continue;
5267 } else {
5268 // If the conversion function doesn't return a reference type,
5269 // it can't be considered for this conversion. An rvalue reference
5270 // is only acceptable if its referencee is a function type.
5271
5272 const ReferenceType *RefType =
5274 if (!RefType ||
5275 (!RefType->isLValueReferenceType() &&
5276 !RefType->getPointeeType()->isFunctionType()))
5277 continue;
5278 }
5279
5280 if (ConvTemplate)
5282 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5283 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5284 else
5286 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5287 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5288 }
5289
5290 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5291
5293 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5294 case OR_Success:
5295
5296 assert(Best->HasFinalConversion);
5297
5298 // C++ [over.ics.ref]p1:
5299 //
5300 // [...] If the parameter binds directly to the result of
5301 // applying a conversion function to the argument
5302 // expression, the implicit conversion sequence is a
5303 // user-defined conversion sequence (13.3.3.1.2), with the
5304 // second standard conversion sequence either an identity
5305 // conversion or, if the conversion function returns an
5306 // entity of a type that is a derived class of the parameter
5307 // type, a derived-to-base Conversion.
5308 if (!Best->FinalConversion.DirectBinding)
5309 return false;
5310
5311 ICS.setUserDefined();
5312 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5313 ICS.UserDefined.After = Best->FinalConversion;
5314 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5315 ICS.UserDefined.ConversionFunction = Best->Function;
5316 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5317 ICS.UserDefined.EllipsisConversion = false;
5318 assert(ICS.UserDefined.After.ReferenceBinding &&
5320 "Expected a direct reference binding!");
5321 return true;
5322
5323 case OR_Ambiguous:
5324 ICS.setAmbiguous();
5325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5326 Cand != CandidateSet.end(); ++Cand)
5327 if (Cand->Best)
5328 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5329 return true;
5330
5332 case OR_Deleted:
5333 // There was no suitable conversion, or we found a deleted
5334 // conversion; continue with other checks.
5335 return false;
5336 }
5337
5338 llvm_unreachable("Invalid OverloadResult!");
5339}
5340
5341/// Compute an implicit conversion sequence for reference
5342/// initialization.
5343static ImplicitConversionSequence
5345 SourceLocation DeclLoc,
5346 bool SuppressUserConversions,
5347 bool AllowExplicit) {
5348 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5349
5350 // Most paths end in a failed conversion.
5353
5354 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5355 QualType T2 = Init->getType();
5356
5357 // If the initializer is the address of an overloaded function, try
5358 // to resolve the overloaded function. If all goes well, T2 is the
5359 // type of the resulting function.
5360 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5363 false, Found))
5364 T2 = Fn->getType();
5365 }
5366
5367 // Compute some basic properties of the types and the initializer.
5368 bool isRValRef = DeclType->isRValueReferenceType();
5369 Expr::Classification InitCategory = Init->Classify(S.Context);
5370
5372 Sema::ReferenceCompareResult RefRelationship =
5373 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5374
5375 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5376 ICS.setStandard();
5378 // FIXME: A reference binding can be a function conversion too. We should
5379 // consider that when ordering reference-to-function bindings.
5380 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5382 : (RefConv & Sema::ReferenceConversions::ObjC)
5384 : ICK_Identity;
5386 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5387 // a reference binding that performs a non-top-level qualification
5388 // conversion as a qualification conversion, not as an identity conversion.
5389 ICS.Standard.Third = (RefConv &
5390 Sema::ReferenceConversions::NestedQualification)
5392 : ICK_Identity;
5393 ICS.Standard.setFromType(T2);
5394 ICS.Standard.setToType(0, T2);
5395 ICS.Standard.setToType(1, T1);
5396 ICS.Standard.setToType(2, T1);
5397 ICS.Standard.ReferenceBinding = true;
5398 ICS.Standard.DirectBinding = BindsDirectly;
5399 ICS.Standard.IsLvalueReference = !isRValRef;
5401 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5404 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5405 ICS.Standard.FromBracedInitList = false;
5406 ICS.Standard.CopyConstructor = nullptr;
5408 };
5409
5410 // C++0x [dcl.init.ref]p5:
5411 // A reference to type "cv1 T1" is initialized by an expression
5412 // of type "cv2 T2" as follows:
5413
5414 // -- If reference is an lvalue reference and the initializer expression
5415 if (!isRValRef) {
5416 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5417 // reference-compatible with "cv2 T2," or
5418 //
5419 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5420 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5421 // C++ [over.ics.ref]p1:
5422 // When a parameter of reference type binds directly (8.5.3)
5423 // to an argument expression, the implicit conversion sequence
5424 // is the identity conversion, unless the argument expression
5425 // has a type that is a derived class of the parameter type,
5426 // in which case the implicit conversion sequence is a
5427 // derived-to-base Conversion (13.3.3.1).
5428 SetAsReferenceBinding(/*BindsDirectly=*/true);
5429
5430 // Nothing more to do: the inaccessibility/ambiguity check for
5431 // derived-to-base conversions is suppressed when we're
5432 // computing the implicit conversion sequence (C++
5433 // [over.best.ics]p2).
5434 return ICS;
5435 }
5436
5437 // -- has a class type (i.e., T2 is a class type), where T1 is
5438 // not reference-related to T2, and can be implicitly
5439 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5440 // is reference-compatible with "cv3 T3" 92) (this
5441 // conversion is selected by enumerating the applicable
5442 // conversion functions (13.3.1.6) and choosing the best
5443 // one through overload resolution (13.3)),
5444 if (!SuppressUserConversions && T2->isRecordType() &&
5445 S.isCompleteType(DeclLoc, T2) &&
5446 RefRelationship == Sema::Ref_Incompatible) {
5447 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5448 Init, T2, /*AllowRvalues=*/false,
5449 AllowExplicit))
5450 return ICS;
5451 }
5452 }
5453
5454 // -- Otherwise, the reference shall be an lvalue reference to a
5455 // non-volatile const type (i.e., cv1 shall be const), or the reference
5456 // shall be an rvalue reference.
5457 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5458 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5460 return ICS;
5461 }
5462
5463 // -- If the initializer expression
5464 //
5465 // -- is an xvalue, class prvalue, array prvalue or function
5466 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5467 if (RefRelationship == Sema::Ref_Compatible &&
5468 (InitCategory.isXValue() ||
5469 (InitCategory.isPRValue() &&
5470 (T2->isRecordType() || T2->isArrayType())) ||
5471 (InitCategory.isLValue() && T2->isFunctionType()))) {
5472 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5473 // binding unless we're binding to a class prvalue.
5474 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5475 // allow the use of rvalue references in C++98/03 for the benefit of
5476 // standard library implementors; therefore, we need the xvalue check here.
5477 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5478 !(InitCategory.isPRValue() || T2->isRecordType()));
5479 return ICS;
5480 }
5481
5482 // -- has a class type (i.e., T2 is a class type), where T1 is not
5483 // reference-related to T2, and can be implicitly converted to
5484 // an xvalue, class prvalue, or function lvalue of type
5485 // "cv3 T3", where "cv1 T1" is reference-compatible with
5486 // "cv3 T3",
5487 //
5488 // then the reference is bound to the value of the initializer
5489 // expression in the first case and to the result of the conversion
5490 // in the second case (or, in either case, to an appropriate base
5491 // class subobject).
5492 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5493 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5494 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5495 Init, T2, /*AllowRvalues=*/true,
5496 AllowExplicit)) {
5497 // In the second case, if the reference is an rvalue reference
5498 // and the second standard conversion sequence of the
5499 // user-defined conversion sequence includes an lvalue-to-rvalue
5500 // conversion, the program is ill-formed.
5501 if (ICS.isUserDefined() && isRValRef &&
5504
5505 return ICS;
5506 }
5507
5508 // A temporary of function type cannot be created; don't even try.
5509 if (T1->isFunctionType())
5510 return ICS;
5511
5512 // -- Otherwise, a temporary of type "cv1 T1" is created and
5513 // initialized from the initializer expression using the
5514 // rules for a non-reference copy initialization (8.5). The
5515 // reference is then bound to the temporary. If T1 is
5516 // reference-related to T2, cv1 must be the same
5517 // cv-qualification as, or greater cv-qualification than,
5518 // cv2; otherwise, the program is ill-formed.
5519 if (RefRelationship == Sema::Ref_Related) {
5520 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5521 // we would be reference-compatible or reference-compatible with
5522 // added qualification. But that wasn't the case, so the reference
5523 // initialization fails.
5524 //
5525 // Note that we only want to check address spaces and cvr-qualifiers here.
5526 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5527 Qualifiers T1Quals = T1.getQualifiers();
5528 Qualifiers T2Quals = T2.getQualifiers();
5529 T1Quals.removeObjCGCAttr();
5530 T1Quals.removeObjCLifetime();
5531 T2Quals.removeObjCGCAttr();
5532 T2Quals.removeObjCLifetime();
5533 // MS compiler ignores __unaligned qualifier for references; do the same.
5534 T1Quals.removeUnaligned();
5535 T2Quals.removeUnaligned();
5536 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5537 return ICS;
5538 }
5539
5540 // If at least one of the types is a class type, the types are not
5541 // related, and we aren't allowed any user conversions, the
5542 // reference binding fails. This case is important for breaking
5543 // recursion, since TryImplicitConversion below will attempt to
5544 // create a temporary through the use of a copy constructor.
5545 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5546 (T1->isRecordType() || T2->isRecordType()))
5547 return ICS;
5548
5549 // If T1 is reference-related to T2 and the reference is an rvalue
5550 // reference, the initializer expression shall not be an lvalue.
5551 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5552 Init->Classify(S.Context).isLValue()) {
5554 return ICS;
5555 }
5556
5557 // C++ [over.ics.ref]p2:
5558 // When a parameter of reference type is not bound directly to
5559 // an argument expression, the conversion sequence is the one
5560 // required to convert the argument expression to the
5561 // underlying type of the reference according to
5562 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5563 // to copy-initializing a temporary of the underlying type with
5564 // the argument expression. Any difference in top-level
5565 // cv-qualification is subsumed by the initialization itself
5566 // and does not constitute a conversion.
5567 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5568 AllowedExplicit::None,
5569 /*InOverloadResolution=*/false,
5570 /*CStyle=*/false,
5571 /*AllowObjCWritebackConversion=*/false,
5572 /*AllowObjCConversionOnExplicit=*/false);
5573
5574 // Of course, that's still a reference binding.
5575 if (ICS.isStandard()) {
5576 ICS.Standard.ReferenceBinding = true;
5577 ICS.Standard.IsLvalueReference = !isRValRef;
5578 ICS.Standard.BindsToFunctionLvalue = false;
5579 ICS.Standard.BindsToRvalue = true;
5582 } else if (ICS.isUserDefined()) {
5583 const ReferenceType *LValRefType =
5586
5587 // C++ [over.ics.ref]p3:
5588 // Except for an implicit object parameter, for which see 13.3.1, a
5589 // standard conversion sequence cannot be formed if it requires [...]
5590 // binding an rvalue reference to an lvalue other than a function
5591 // lvalue.
5592 // Note that the function case is not possible here.
5593 if (isRValRef && LValRefType) {
5595 return ICS;
5596 }
5597
5599 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5601 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5605 }
5606
5607 return ICS;
5608}
5609
5610static ImplicitConversionSequence
5611TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5612 bool SuppressUserConversions,
5613 bool InOverloadResolution,
5614 bool AllowObjCWritebackConversion,
5615 bool AllowExplicit = false);
5616
5617/// TryListConversion - Try to copy-initialize a value of type ToType from the
5618/// initializer list From.
5619static ImplicitConversionSequence
5621 bool SuppressUserConversions,
5622 bool InOverloadResolution,
5623 bool AllowObjCWritebackConversion) {
5624 // C++11 [over.ics.list]p1:
5625 // When an argument is an initializer list, it is not an expression and
5626 // special rules apply for converting it to a parameter type.
5627
5629 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5630
5631 // We need a complete type for what follows. With one C++20 exception,
5632 // incomplete types can never be initialized from init lists.
5633 QualType InitTy = ToType;
5634 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5635 if (AT && S.getLangOpts().CPlusPlus20)
5636 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5637 // C++20 allows list initialization of an incomplete array type.
5638 InitTy = IAT->getElementType();
5639 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5640 return Result;
5641
5642 // C++20 [over.ics.list]/2:
5643 // If the initializer list is a designated-initializer-list, a conversion
5644 // is only possible if the parameter has an aggregate type
5645 //
5646 // FIXME: The exception for reference initialization here is not part of the
5647 // language rules, but follow other compilers in adding it as a tentative DR
5648 // resolution.
5649 bool IsDesignatedInit = From->hasDesignatedInit();
5650 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5651 IsDesignatedInit)
5652 return Result;
5653
5654 // Per DR1467 and DR2137:
5655 // If the parameter type is an aggregate class X and the initializer list
5656 // has a single element of type cv U, where U is X or a class derived from
5657 // X, the implicit conversion sequence is the one required to convert the
5658 // element to the parameter type.
5659 //
5660 // Otherwise, if the parameter type is a character array [... ]
5661 // and the initializer list has a single element that is an
5662 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5663 // implicit conversion sequence is the identity conversion.
5664 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5665 if (ToType->isRecordType() && ToType->isAggregateType()) {
5666 QualType InitType = From->getInit(0)->getType();
5667 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5668 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5669 return TryCopyInitialization(S, From->getInit(0), ToType,
5670 SuppressUserConversions,
5671 InOverloadResolution,
5672 AllowObjCWritebackConversion);
5673 }
5674
5675 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5676 InitializedEntity Entity =
5678 /*Consumed=*/false);
5679 if (S.CanPerformCopyInitialization(Entity, From)) {
5680 Result.setStandard();
5681 Result.Standard.setAsIdentityConversion();
5682 Result.Standard.setFromType(ToType);
5683 Result.Standard.setAllToTypes(ToType);
5684 return Result;
5685 }
5686 }
5687 }
5688
5689 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5690 // C++11 [over.ics.list]p2:
5691 // If the parameter type is std::initializer_list<X> or "array of X" and
5692 // all the elements can be implicitly converted to X, the implicit
5693 // conversion sequence is the worst conversion necessary to convert an
5694 // element of the list to X.
5695 //
5696 // C++14 [over.ics.list]p3:
5697 // Otherwise, if the parameter type is "array of N X", if the initializer
5698 // list has exactly N elements or if it has fewer than N elements and X is
5699 // default-constructible, and if all the elements of the initializer list
5700 // can be implicitly converted to X, the implicit conversion sequence is
5701 // the worst conversion necessary to convert an element of the list to X.
5702 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5703 unsigned e = From->getNumInits();
5706 QualType());
5707 QualType ContTy = ToType;
5708 bool IsUnbounded = false;
5709 if (AT) {
5710 InitTy = AT->getElementType();
5711 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5712 if (CT->getSize().ult(e)) {
5713 // Too many inits, fatally bad
5715 ToType);
5716 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5717 return Result;
5718 }
5719 if (CT->getSize().ugt(e)) {
5720 // Need an init from empty {}, is there one?
5721 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5722 From->getEndLoc());
5723 EmptyList.setType(S.Context.VoidTy);
5724 DfltElt = TryListConversion(
5725 S, &EmptyList, InitTy, SuppressUserConversions,
5726 InOverloadResolution, AllowObjCWritebackConversion);
5727 if (DfltElt.isBad()) {
5728 // No {} init, fatally bad
5730 ToType);
5731 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5732 return Result;
5733 }
5734 }
5735 } else {
5736 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5737 IsUnbounded = true;
5738 if (!e) {
5739 // Cannot convert to zero-sized.
5741 ToType);
5742 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5743 return Result;
5744 }
5745 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5746 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5748 }
5749 }
5750
5751 Result.setStandard();
5752 Result.Standard.setAsIdentityConversion();
5753 Result.Standard.setFromType(InitTy);
5754 Result.Standard.setAllToTypes(InitTy);
5755 for (unsigned i = 0; i < e; ++i) {
5756 Expr *Init = From->getInit(i);
5758 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5759 AllowObjCWritebackConversion);
5760
5761 // Keep the worse conversion seen so far.
5762 // FIXME: Sequences are not totally ordered, so 'worse' can be
5763 // ambiguous. CWG has been informed.
5765 Result) ==
5767 Result = ICS;
5768 // Bail as soon as we find something unconvertible.
5769 if (Result.isBad()) {
5770 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5771 return Result;
5772 }
5773 }
5774 }
5775
5776 // If we needed any implicit {} initialization, compare that now.
5777 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5778 // has been informed that this might not be the best thing.
5779 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5780 S, From->getEndLoc(), DfltElt, Result) ==
5782 Result = DfltElt;
5783 // Record the type being initialized so that we may compare sequences
5784 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5785 return Result;
5786 }
5787
5788 // C++14 [over.ics.list]p4:
5789 // C++11 [over.ics.list]p3:
5790 // Otherwise, if the parameter is a non-aggregate class X and overload
5791 // resolution chooses a single best constructor [...] the implicit
5792 // conversion sequence is a user-defined conversion sequence. If multiple
5793 // constructors are viable but none is better than the others, the
5794 // implicit conversion sequence is a user-defined conversion sequence.
5795 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5796 // This function can deal with initializer lists.
5797 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5798 AllowedExplicit::None,
5799 InOverloadResolution, /*CStyle=*/false,
5800 AllowObjCWritebackConversion,
5801 /*AllowObjCConversionOnExplicit=*/false);
5802 }
5803
5804 // C++14 [over.ics.list]p5:
5805 // C++11 [over.ics.list]p4:
5806 // Otherwise, if the parameter has an aggregate type which can be
5807 // initialized from the initializer list [...] the implicit conversion
5808 // sequence is a user-defined conversion sequence.
5809 if (ToType->isAggregateType()) {
5810 // Type is an aggregate, argument is an init list. At this point it comes
5811 // down to checking whether the initialization works.
5812 // FIXME: Find out whether this parameter is consumed or not.
5813 InitializedEntity Entity =
5815 /*Consumed=*/false);
5817 From)) {
5818 Result.setUserDefined();
5819 Result.UserDefined.Before.setAsIdentityConversion();
5820 // Initializer lists don't have a type.
5821 Result.UserDefined.Before.setFromType(QualType());
5822 Result.UserDefined.Before.setAllToTypes(QualType());
5823
5824 Result.UserDefined.After.setAsIdentityConversion();
5825 Result.UserDefined.After.setFromType(ToType);
5826 Result.UserDefined.After.setAllToTypes(ToType);
5827 Result.UserDefined.ConversionFunction = nullptr;
5828 }
5829 return Result;
5830 }
5831
5832 // C++14 [over.ics.list]p6:
5833 // C++11 [over.ics.list]p5:
5834 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5835 if (ToType->isReferenceType()) {
5836 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5837 // mention initializer lists in any way. So we go by what list-
5838 // initialization would do and try to extrapolate from that.
5839
5840 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5841
5842 // If the initializer list has a single element that is reference-related
5843 // to the parameter type, we initialize the reference from that.
5844 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5845 Expr *Init = From->getInit(0);
5846
5847 QualType T2 = Init->getType();
5848
5849 // If the initializer is the address of an overloaded function, try
5850 // to resolve the overloaded function. If all goes well, T2 is the
5851 // type of the resulting function.
5852 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5855 Init, ToType, false, Found))
5856 T2 = Fn->getType();
5857 }
5858
5859 // Compute some basic properties of the types and the initializer.
5860 Sema::ReferenceCompareResult RefRelationship =
5861 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5862
5863 if (RefRelationship >= Sema::Ref_Related) {
5864 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5865 SuppressUserConversions,
5866 /*AllowExplicit=*/false);
5867 }
5868 }
5869
5870 // Otherwise, we bind the reference to a temporary created from the
5871 // initializer list.
5872 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5873 InOverloadResolution,
5874 AllowObjCWritebackConversion);
5875 if (Result.isFailure())
5876 return Result;
5877 assert(!Result.isEllipsis() &&
5878 "Sub-initialization cannot result in ellipsis conversion.");
5879
5880 // Can we even bind to a temporary?
5881 if (ToType->isRValueReferenceType() ||
5882 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5883 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5884 Result.UserDefined.After;
5885 SCS.ReferenceBinding = true;
5887 SCS.BindsToRvalue = true;
5888 SCS.BindsToFunctionLvalue = false;
5891 SCS.FromBracedInitList = false;
5892
5893 } else
5895 From, ToType);
5896 return Result;
5897 }
5898
5899 // C++14 [over.ics.list]p7:
5900 // C++11 [over.ics.list]p6:
5901 // Otherwise, if the parameter type is not a class:
5902 if (!ToType->isRecordType()) {
5903 // - if the initializer list has one element that is not itself an
5904 // initializer list, the implicit conversion sequence is the one
5905 // required to convert the element to the parameter type.
5906 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5907 // single integer.
5908 unsigned NumInits = From->getNumInits();
5909 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5910 !isa<EmbedExpr>(From->getInit(0))) {
5911 Result = TryCopyInitialization(
5912 S, From->getInit(0), ToType, SuppressUserConversions,
5913 InOverloadResolution, AllowObjCWritebackConversion);
5914 if (Result.isStandard())
5915 Result.Standard.FromBracedInitList = true;
5916 }
5917 // - if the initializer list has no elements, the implicit conversion
5918 // sequence is the identity conversion.
5919 else if (NumInits == 0) {
5920 Result.setStandard();
5921 Result.Standard.setAsIdentityConversion();
5922 Result.Standard.setFromType(ToType);
5923 Result.Standard.setAllToTypes(ToType);
5924 }
5925 return Result;
5926 }
5927
5928 // C++14 [over.ics.list]p8:
5929 // C++11 [over.ics.list]p7:
5930 // In all cases other than those enumerated above, no conversion is possible
5931 return Result;
5932}
5933
5934/// TryCopyInitialization - Try to copy-initialize a value of type
5935/// ToType from the expression From. Return the implicit conversion
5936/// sequence required to pass this argument, which may be a bad
5937/// conversion sequence (meaning that the argument cannot be passed to
5938/// a parameter of this type). If @p SuppressUserConversions, then we
5939/// do not permit any user-defined conversion sequences.
5940static ImplicitConversionSequence
5942 bool SuppressUserConversions,
5943 bool InOverloadResolution,
5944 bool AllowObjCWritebackConversion,
5945 bool AllowExplicit) {
5946 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5947 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5948 InOverloadResolution,AllowObjCWritebackConversion);
5949
5950 if (ToType->isReferenceType())
5951 return TryReferenceInit(S, From, ToType,
5952 /*FIXME:*/ From->getBeginLoc(),
5953 SuppressUserConversions, AllowExplicit);
5954
5955 return TryImplicitConversion(S, From, ToType,
5956 SuppressUserConversions,
5957 AllowedExplicit::None,
5958 InOverloadResolution,
5959 /*CStyle=*/false,
5960 AllowObjCWritebackConversion,
5961 /*AllowObjCConversionOnExplicit=*/false);
5962}
5963
5964static bool TryCopyInitialization(const CanQualType FromQTy,
5965 const CanQualType ToQTy,
5966 Sema &S,
5967 SourceLocation Loc,
5968 ExprValueKind FromVK) {
5969 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5971 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5972
5973 return !ICS.isBad();
5974}
5975
5976/// TryObjectArgumentInitialization - Try to initialize the object
5977/// parameter of the given member function (@c Method) from the
5978/// expression @p From.
5980 Sema &S, SourceLocation Loc, QualType FromType,
5981 Expr::Classification FromClassification, CXXMethodDecl *Method,
5982 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5983 QualType ExplicitParameterType = QualType(),
5984 bool SuppressUserConversion = false) {
5985
5986 // We need to have an object of class type.
5987 if (const auto *PT = FromType->getAs<PointerType>()) {
5988 FromType = PT->getPointeeType();
5989
5990 // When we had a pointer, it's implicitly dereferenced, so we
5991 // better have an lvalue.
5992 assert(FromClassification.isLValue());
5993 }
5994
5995 auto ValueKindFromClassification = [](Expr::Classification C) {
5996 if (C.isPRValue())
5997 return clang::VK_PRValue;
5998 if (C.isXValue())
5999 return VK_XValue;
6000 return clang::VK_LValue;
6001 };
6002
6003 if (Method->isExplicitObjectMemberFunction()) {
6004 if (ExplicitParameterType.isNull())
6005 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6006 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6007 ValueKindFromClassification(FromClassification));
6009 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6010 /*InOverloadResolution=*/true, false);
6011 if (ICS.isBad())
6012 ICS.Bad.FromExpr = nullptr;
6013 return ICS;
6014 }
6015
6016 assert(FromType->isRecordType());
6017
6018 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6019 // C++98 [class.dtor]p2:
6020 // A destructor can be invoked for a const, volatile or const volatile
6021 // object.
6022 // C++98 [over.match.funcs]p4:
6023 // For static member functions, the implicit object parameter is considered
6024 // to match any object (since if the function is selected, the object is
6025 // discarded).
6026 Qualifiers Quals = Method->getMethodQualifiers();
6027 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6028 Quals.addConst();
6029 Quals.addVolatile();
6030 }
6031
6032 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6033
6034 // Set up the conversion sequence as a "bad" conversion, to allow us
6035 // to exit early.
6037
6038 // C++0x [over.match.funcs]p4:
6039 // For non-static member functions, the type of the implicit object
6040 // parameter is
6041 //
6042 // - "lvalue reference to cv X" for functions declared without a
6043 // ref-qualifier or with the & ref-qualifier
6044 // - "rvalue reference to cv X" for functions declared with the &&
6045 // ref-qualifier
6046 //
6047 // where X is the class of which the function is a member and cv is the
6048 // cv-qualification on the member function declaration.
6049 //
6050 // However, when finding an implicit conversion sequence for the argument, we
6051 // are not allowed to perform user-defined conversions
6052 // (C++ [over.match.funcs]p5). We perform a simplified version of
6053 // reference binding here, that allows class rvalues to bind to
6054 // non-constant references.
6055
6056 // First check the qualifiers.
6057 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6058 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6059 if (ImplicitParamType.getCVRQualifiers() !=
6060 FromTypeCanon.getLocalCVRQualifiers() &&
6061 !ImplicitParamType.isAtLeastAsQualifiedAs(
6062 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6064 FromType, ImplicitParamType);
6065 return ICS;
6066 }
6067
6068 if (FromTypeCanon.hasAddressSpace()) {
6069 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6070 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6071 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6072 S.getASTContext())) {
6074 FromType, ImplicitParamType);
6075 return ICS;
6076 }
6077 }
6078
6079 // Check that we have either the same type or a derived type. It
6080 // affects the conversion rank.
6081 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6082 ImplicitConversionKind SecondKind;
6083 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6084 SecondKind = ICK_Identity;
6085 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6086 SecondKind = ICK_Derived_To_Base;
6087 } else if (!Method->isExplicitObjectMemberFunction()) {
6089 FromType, ImplicitParamType);
6090 return ICS;
6091 }
6092
6093 // Check the ref-qualifier.
6094 switch (Method->getRefQualifier()) {
6095 case RQ_None:
6096 // Do nothing; we don't care about lvalueness or rvalueness.
6097 break;
6098
6099 case RQ_LValue:
6100 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6101 // non-const lvalue reference cannot bind to an rvalue
6103 ImplicitParamType);
6104 return ICS;
6105 }
6106 break;
6107
6108 case RQ_RValue:
6109 if (!FromClassification.isRValue()) {
6110 // rvalue reference cannot bind to an lvalue
6112 ImplicitParamType);
6113 return ICS;
6114 }
6115 break;
6116 }
6117
6118 // Success. Mark this as a reference binding.
6119 ICS.setStandard();
6121 ICS.Standard.Second = SecondKind;
6122 ICS.Standard.setFromType(FromType);
6123 ICS.Standard.setAllToTypes(ImplicitParamType);
6124 ICS.Standard.ReferenceBinding = true;
6125 ICS.Standard.DirectBinding = true;
6126 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6127 ICS.Standard.BindsToFunctionLvalue = false;
6128 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6129 ICS.Standard.FromBracedInitList = false;
6131 = (Method->getRefQualifier() == RQ_None);
6132 return ICS;
6133}
6134
6135/// PerformObjectArgumentInitialization - Perform initialization of
6136/// the implicit object parameter for the given Method with the given
6137/// expression.
6139 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6141 QualType FromRecordType, DestType;
6142 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6143
6144 Expr::Classification FromClassification;
6145 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6146 FromRecordType = PT->getPointeeType();
6147 DestType = Method->getThisType();
6148 FromClassification = Expr::Classification::makeSimpleLValue();
6149 } else {
6150 FromRecordType = From->getType();
6151 DestType = ImplicitParamRecordType;
6152 FromClassification = From->Classify(Context);
6153
6154 // CWG2813 [expr.call]p6:
6155 // If the function is an implicit object member function, the object
6156 // expression of the class member access shall be a glvalue [...]
6157 if (From->isPRValue()) {
6158 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6159 Method->getRefQualifier() !=
6161 }
6162 }
6163
6164 // Note that we always use the true parent context when performing
6165 // the actual argument initialization.
6167 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6168 Method->getParent());
6169 if (ICS.isBad()) {
6170 switch (ICS.Bad.Kind) {
6172 Qualifiers FromQs = FromRecordType.getQualifiers();
6173 Qualifiers ToQs = DestType.getQualifiers();
6174 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6175 if (CVR) {
6176 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6177 << Method->getDeclName() << FromRecordType << (CVR - 1)
6178 << From->getSourceRange();
6179 Diag(Method->getLocation(), diag::note_previous_decl)
6180 << Method->getDeclName();
6181 return ExprError();
6182 }
6183 break;
6184 }
6185
6188 bool IsRValueQualified =
6189 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6190 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6191 << Method->getDeclName() << FromClassification.isRValue()
6192 << IsRValueQualified;
6193 Diag(Method->getLocation(), diag::note_previous_decl)
6194 << Method->getDeclName();
6195 return ExprError();
6196 }
6197
6200 break;
6201
6204 llvm_unreachable("Lists are not objects");
6205 }
6206
6207 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6208 << ImplicitParamRecordType << FromRecordType
6209 << From->getSourceRange();
6210 }
6211
6212 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6213 ExprResult FromRes =
6214 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6215 if (FromRes.isInvalid())
6216 return ExprError();
6217 From = FromRes.get();
6218 }
6219
6220 if (!Context.hasSameType(From->getType(), DestType)) {
6221 CastKind CK;
6222 QualType PteeTy = DestType->getPointeeType();
6223 LangAS DestAS =
6224 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6225 if (FromRecordType.getAddressSpace() != DestAS)
6226 CK = CK_AddressSpaceConversion;
6227 else
6228 CK = CK_NoOp;
6229 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6230 }
6231 return From;
6232}
6233
6234/// TryContextuallyConvertToBool - Attempt to contextually convert the
6235/// expression From to bool (C++0x [conv]p3).
6238 // C++ [dcl.init]/17.8:
6239 // - Otherwise, if the initialization is direct-initialization, the source
6240 // type is std::nullptr_t, and the destination type is bool, the initial
6241 // value of the object being initialized is false.
6242 if (From->getType()->isNullPtrType())
6244 S.Context.BoolTy,
6245 From->isGLValue());
6246
6247 // All other direct-initialization of bool is equivalent to an implicit
6248 // conversion to bool in which explicit conversions are permitted.
6249 return TryImplicitConversion(S, From, S.Context.BoolTy,
6250 /*SuppressUserConversions=*/false,
6251 AllowedExplicit::Conversions,
6252 /*InOverloadResolution=*/false,
6253 /*CStyle=*/false,
6254 /*AllowObjCWritebackConversion=*/false,
6255 /*AllowObjCConversionOnExplicit=*/false);
6256}
6257
6259 if (checkPlaceholderForOverload(*this, From))
6260 return ExprError();
6261
6263 if (!ICS.isBad())
6264 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6266
6268 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6269 << From->getType() << From->getSourceRange();
6270 return ExprError();
6271}
6272
6273/// Check that the specified conversion is permitted in a converted constant
6274/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6275/// is acceptable.
6278 // Since we know that the target type is an integral or unscoped enumeration
6279 // type, most conversion kinds are impossible. All possible First and Third
6280 // conversions are fine.
6281 switch (SCS.Second) {
6282 case ICK_Identity:
6284 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6286 return true;
6287
6289 // Conversion from an integral or unscoped enumeration type to bool is
6290 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6291 // conversion, so we allow it in a converted constant expression.
6292 //
6293 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6294 // a lot of popular code. We should at least add a warning for this
6295 // (non-conforming) extension.
6297 SCS.getToType(2)->isBooleanType();
6298
6300 case ICK_Pointer_Member:
6301 // C++1z: null pointer conversions and null member pointer conversions are
6302 // only permitted if the source type is std::nullptr_t.
6303 return SCS.getFromType()->isNullPtrType();
6304
6317 case ICK_Vector_Splat:
6318 case ICK_Complex_Real:
6328 return false;
6329
6334 llvm_unreachable("found a first conversion kind in Second");
6335
6337 case ICK_Qualification:
6338 llvm_unreachable("found a third conversion kind in Second");
6339
6341 break;
6342 }
6343
6344 llvm_unreachable("unknown conversion kind");
6345}
6346
6347/// BuildConvertedConstantExpression - Check that the expression From is a
6348/// converted constant expression of type T, perform the conversion but
6349/// does not evaluate the expression
6351 QualType T, CCEKind CCE,
6352 NamedDecl *Dest,
6353 APValue &PreNarrowingValue) {
6354 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6356 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6357 "converted constant expression outside C++11 or TTP matching");
6358
6359 if (checkPlaceholderForOverload(S, From))
6360 return ExprError();
6361
6362 // C++1z [expr.const]p3:
6363 // A converted constant expression of type T is an expression,
6364 // implicitly converted to type T, where the converted
6365 // expression is a constant expression and the implicit conversion
6366 // sequence contains only [... list of conversions ...].
6368 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6370 : TryCopyInitialization(S, From, T,
6371 /*SuppressUserConversions=*/false,
6372 /*InOverloadResolution=*/false,
6373 /*AllowObjCWritebackConversion=*/false,
6374 /*AllowExplicit=*/false);
6375 StandardConversionSequence *SCS = nullptr;
6376 switch (ICS.getKind()) {
6378 SCS = &ICS.Standard;
6379 break;
6381 if (T->isRecordType())
6382 SCS = &ICS.UserDefined.Before;
6383 else
6384 SCS = &ICS.UserDefined.After;
6385 break;
6389 return S.Diag(From->getBeginLoc(),
6390 diag::err_typecheck_converted_constant_expression)
6391 << From->getType() << From->getSourceRange() << T;
6392 return ExprError();
6393
6396 llvm_unreachable("bad conversion in converted constant expression");
6397 }
6398
6399 // Check that we would only use permitted conversions.
6400 if (!CheckConvertedConstantConversions(S, *SCS)) {
6401 return S.Diag(From->getBeginLoc(),
6402 diag::err_typecheck_converted_constant_expression_disallowed)
6403 << From->getType() << From->getSourceRange() << T;
6404 }
6405 // [...] and where the reference binding (if any) binds directly.
6406 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6407 return S.Diag(From->getBeginLoc(),
6408 diag::err_typecheck_converted_constant_expression_indirect)
6409 << From->getType() << From->getSourceRange() << T;
6410 }
6411 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6412 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6413 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6414 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6415 // case explicitly.
6416 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6417 return S.Diag(From->getBeginLoc(),
6418 diag::err_reference_bind_to_bitfield_in_cce)
6419 << From->getSourceRange();
6420 }
6421
6422 // Usually we can simply apply the ImplicitConversionSequence we formed
6423 // earlier, but that's not guaranteed to work when initializing an object of
6424 // class type.
6425 ExprResult Result;
6426 bool IsTemplateArgument =
6428 if (T->isRecordType()) {
6429 assert(IsTemplateArgument &&
6430 "unexpected class type converted constant expr");
6431 Result = S.PerformCopyInitialization(
6434 SourceLocation(), From);
6435 } else {
6436 Result =
6438 }
6439 if (Result.isInvalid())
6440 return Result;
6441
6442 // C++2a [intro.execution]p5:
6443 // A full-expression is [...] a constant-expression [...]
6444 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6445 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6446 IsTemplateArgument);
6447 if (Result.isInvalid())
6448 return Result;
6449
6450 // Check for a narrowing implicit conversion.
6451 bool ReturnPreNarrowingValue = false;
6452 QualType PreNarrowingType;
6453 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6454 PreNarrowingType)) {
6456 // Implicit conversion to a narrower type, and the value is not a constant
6457 // expression. We'll diagnose this in a moment.
6458 case NK_Not_Narrowing:
6459 break;
6460
6462 if (CCE == CCEKind::ArrayBound &&
6463 PreNarrowingType->isIntegralOrEnumerationType() &&
6464 PreNarrowingValue.isInt()) {
6465 // Don't diagnose array bound narrowing here; we produce more precise
6466 // errors by allowing the un-narrowed value through.
6467 ReturnPreNarrowingValue = true;
6468 break;
6469 }
6470 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6471 << CCE << /*Constant*/ 1
6472 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6473 break;
6474
6476 // Implicit conversion to a narrower type, but the expression is
6477 // value-dependent so we can't tell whether it's actually narrowing.
6478 // For matching the parameters of a TTP, the conversion is ill-formed
6479 // if it may narrow.
6480 if (CCE != CCEKind::TempArgStrict)
6481 break;
6482 [[fallthrough]];
6483 case NK_Type_Narrowing:
6484 // FIXME: It would be better to diagnose that the expression is not a
6485 // constant expression.
6486 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6487 << CCE << /*Constant*/ 0 << From->getType() << T;
6488 break;
6489 }
6490 if (!ReturnPreNarrowingValue)
6491 PreNarrowingValue = {};
6492
6493 return Result;
6494}
6495
6496/// CheckConvertedConstantExpression - Check that the expression From is a
6497/// converted constant expression of type T, perform the conversion and produce
6498/// the converted expression, per C++11 [expr.const]p3.
6501 CCEKind CCE, bool RequireInt,
6502 NamedDecl *Dest) {
6503
6504 APValue PreNarrowingValue;
6505 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6506 PreNarrowingValue);
6507 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6508 Value = APValue();
6509 return Result;
6510 }
6511 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6512 RequireInt, PreNarrowingValue);
6513}
6514
6516 CCEKind CCE,
6517 NamedDecl *Dest) {
6518 APValue PreNarrowingValue;
6519 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6520 PreNarrowingValue);
6521}
6522
6524 APValue &Value, CCEKind CCE,
6525 NamedDecl *Dest) {
6526 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6527 Dest);
6528}
6529
6531 llvm::APSInt &Value,
6532 CCEKind CCE) {
6533 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6534
6535 APValue V;
6536 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6537 /*Dest=*/nullptr);
6538 if (!R.isInvalid() && !R.get()->isValueDependent())
6539 Value = V.getInt();
6540 return R;
6541}
6542
6545 CCEKind CCE, bool RequireInt,
6546 const APValue &PreNarrowingValue) {
6547
6548 ExprResult Result = E;
6549 // Check the expression is a constant expression.
6551 Expr::EvalResult Eval;
6552 Eval.Diag = &Notes;
6553
6554 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6555
6556 ConstantExprKind Kind;
6557 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6558 Kind = ConstantExprKind::ClassTemplateArgument;
6559 else if (CCE == CCEKind::TemplateArg)
6560 Kind = ConstantExprKind::NonClassTemplateArgument;
6561 else
6562 Kind = ConstantExprKind::Normal;
6563
6564 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6565 (RequireInt && !Eval.Val.isInt())) {
6566 // The expression can't be folded, so we can't keep it at this position in
6567 // the AST.
6568 Result = ExprError();
6569 } else {
6570 Value = Eval.Val;
6571
6572 if (Notes.empty()) {
6573 // It's a constant expression.
6574 Expr *E = Result.get();
6575 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6576 // We expect a ConstantExpr to have a value associated with it
6577 // by this point.
6578 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6579 "ConstantExpr has no value associated with it");
6580 (void)CE;
6581 } else {
6583 }
6584 if (!PreNarrowingValue.isAbsent())
6585 Value = std::move(PreNarrowingValue);
6586 return E;
6587 }
6588 }
6589
6590 // It's not a constant expression. Produce an appropriate diagnostic.
6591 if (Notes.size() == 1 &&
6592 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6593 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6594 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6595 diag::note_constexpr_invalid_template_arg) {
6596 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6597 for (unsigned I = 0; I < Notes.size(); ++I)
6598 Diag(Notes[I].first, Notes[I].second);
6599 } else {
6600 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6601 << CCE << E->getSourceRange();
6602 for (unsigned I = 0; I < Notes.size(); ++I)
6603 Diag(Notes[I].first, Notes[I].second);
6604 }
6605 return ExprError();
6606}
6607
6608/// dropPointerConversions - If the given standard conversion sequence
6609/// involves any pointer conversions, remove them. This may change
6610/// the result type of the conversion sequence.
6612 if (SCS.Second == ICK_Pointer_Conversion) {
6613 SCS.Second = ICK_Identity;
6614 SCS.Dimension = ICK_Identity;
6615 SCS.Third = ICK_Identity;
6616 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6617 }
6618}
6619
6620/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6621/// convert the expression From to an Objective-C pointer type.
6622static ImplicitConversionSequence
6624 // Do an implicit conversion to 'id'.
6627 = TryImplicitConversion(S, From, Ty,
6628 // FIXME: Are these flags correct?
6629 /*SuppressUserConversions=*/false,
6630 AllowedExplicit::Conversions,
6631 /*InOverloadResolution=*/false,
6632 /*CStyle=*/false,
6633 /*AllowObjCWritebackConversion=*/false,
6634 /*AllowObjCConversionOnExplicit=*/true);
6635
6636 // Strip off any final conversions to 'id'.
6637 switch (ICS.getKind()) {
6642 break;
6643
6646 break;
6647
6650 break;
6651 }
6652
6653 return ICS;
6654}
6655
6657 if (checkPlaceholderForOverload(*this, From))
6658 return ExprError();
6659
6660 QualType Ty = Context.getObjCIdType();
6663 if (!ICS.isBad())
6664 return PerformImplicitConversion(From, Ty, ICS,
6666 return ExprResult();
6667}
6668
6669static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6670 const Expr *Base = nullptr;
6671 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6672 "expected a member expression");
6673
6674 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6675 M && !M->isImplicitAccess())
6676 Base = M->getBase();
6677 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6678 M && !M->isImplicitAccess())
6679 Base = M->getBase();
6680
6681 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6682
6683 if (T->isPointerType())
6684 T = T->getPointeeType();
6685
6686 return T;
6687}
6688
6690 const FunctionDecl *Fun) {
6691 QualType ObjType = Obj->getType();
6692 if (ObjType->isPointerType()) {
6693 ObjType = ObjType->getPointeeType();
6694 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6696 /*CanOverflow=*/false, FPOptionsOverride());
6697 }
6698 return Obj;
6699}
6700
6708
6710 Expr *Object, MultiExprArg &Args,
6711 SmallVectorImpl<Expr *> &NewArgs) {
6712 assert(Method->isExplicitObjectMemberFunction() &&
6713 "Method is not an explicit member function");
6714 assert(NewArgs.empty() && "NewArgs should be empty");
6715
6716 NewArgs.reserve(Args.size() + 1);
6717 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6718 NewArgs.push_back(This);
6719 NewArgs.append(Args.begin(), Args.end());
6720 Args = NewArgs;
6722 Method, Object->getBeginLoc());
6723}
6724
6725/// Determine whether the provided type is an integral type, or an enumeration
6726/// type of a permitted flavor.
6728 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6729 : T->isIntegralOrUnscopedEnumerationType();
6730}
6731
6732static ExprResult
6735 QualType T, UnresolvedSetImpl &ViableConversions) {
6736
6737 if (Converter.Suppress)
6738 return ExprError();
6739
6740 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6741 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6742 CXXConversionDecl *Conv =
6743 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6745 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6746 }
6747 return From;
6748}
6749
6750static bool
6753 QualType T, bool HadMultipleCandidates,
6754 UnresolvedSetImpl &ExplicitConversions) {
6755 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6756 DeclAccessPair Found = ExplicitConversions[0];
6757 CXXConversionDecl *Conversion =
6758 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6759
6760 // The user probably meant to invoke the given explicit
6761 // conversion; use it.
6762 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6763 std::string TypeStr;
6764 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6765
6766 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6768 "static_cast<" + TypeStr + ">(")
6770 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6771 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6772
6773 // If we aren't in a SFINAE context, build a call to the
6774 // explicit conversion function.
6775 if (SemaRef.isSFINAEContext())
6776 return true;
6777
6778 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6779 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6780 HadMultipleCandidates);
6781 if (Result.isInvalid())
6782 return true;
6783
6784 // Replace the conversion with a RecoveryExpr, so we don't try to
6785 // instantiate it later, but can further diagnose here.
6786 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6787 From, Result.get()->getType());
6788 if (Result.isInvalid())
6789 return true;
6790 From = Result.get();
6791 }
6792 return false;
6793}
6794
6795static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6797 QualType T, bool HadMultipleCandidates,
6799 CXXConversionDecl *Conversion =
6800 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6801 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6802
6803 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6804 if (!Converter.SuppressConversion) {
6805 if (SemaRef.isSFINAEContext())
6806 return true;
6807
6808 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6809 << From->getSourceRange();
6810 }
6811
6812 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6813 HadMultipleCandidates);
6814 if (Result.isInvalid())
6815 return true;
6816 // Record usage of conversion in an implicit cast.
6817 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6818 CK_UserDefinedConversion, Result.get(),
6819 nullptr, Result.get()->getValueKind(),
6820 SemaRef.CurFPFeatureOverrides());
6821 return false;
6822}
6823
6825 Sema &SemaRef, SourceLocation Loc, Expr *From,
6827 if (!Converter.match(From->getType()) && !Converter.Suppress)
6828 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6829 << From->getSourceRange();
6830
6831 return SemaRef.DefaultLvalueConversion(From);
6832}
6833
6834static void
6836 UnresolvedSetImpl &ViableConversions,
6837 OverloadCandidateSet &CandidateSet) {
6838 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6839 NamedDecl *D = FoundDecl.getDecl();
6840 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6841 if (isa<UsingShadowDecl>(D))
6842 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6843
6844 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6846 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6847 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6848 continue;
6849 }
6851 SemaRef.AddConversionCandidate(
6852 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6853 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6854 }
6855}
6856
6857/// Attempt to convert the given expression to a type which is accepted
6858/// by the given converter.
6859///
6860/// This routine will attempt to convert an expression of class type to a
6861/// type accepted by the specified converter. In C++11 and before, the class
6862/// must have a single non-explicit conversion function converting to a matching
6863/// type. In C++1y, there can be multiple such conversion functions, but only
6864/// one target type.
6865///
6866/// \param Loc The source location of the construct that requires the
6867/// conversion.
6868///
6869/// \param From The expression we're converting from.
6870///
6871/// \param Converter Used to control and diagnose the conversion process.
6872///
6873/// \returns The expression, converted to an integral or enumeration type if
6874/// successful.
6876 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6877 // We can't perform any more checking for type-dependent expressions.
6878 if (From->isTypeDependent())
6879 return From;
6880
6881 // Process placeholders immediately.
6882 if (From->hasPlaceholderType()) {
6883 ExprResult result = CheckPlaceholderExpr(From);
6884 if (result.isInvalid())
6885 return result;
6886 From = result.get();
6887 }
6888
6889 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6890 ExprResult Converted = DefaultLvalueConversion(From);
6891 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6892 // If the expression already has a matching type, we're golden.
6893 if (Converter.match(T))
6894 return Converted;
6895
6896 // FIXME: Check for missing '()' if T is a function type?
6897
6898 // We can only perform contextual implicit conversions on objects of class
6899 // type.
6900 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6901 if (!RecordTy || !getLangOpts().CPlusPlus) {
6902 if (!Converter.Suppress)
6903 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6904 return From;
6905 }
6906
6907 // We must have a complete class type.
6908 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6909 ContextualImplicitConverter &Converter;
6910 Expr *From;
6911
6912 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6913 : Converter(Converter), From(From) {}
6914
6915 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6916 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6917 }
6918 } IncompleteDiagnoser(Converter, From);
6919
6920 if (Converter.Suppress ? !isCompleteType(Loc, T)
6921 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6922 return From;
6923
6924 // Look for a conversion to an integral or enumeration type.
6926 ViableConversions; // These are *potentially* viable in C++1y.
6927 UnresolvedSet<4> ExplicitConversions;
6928 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6929 ->getDefinitionOrSelf()
6930 ->getVisibleConversionFunctions();
6931
6932 bool HadMultipleCandidates =
6933 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6934
6935 // To check that there is only one target type, in C++1y:
6936 QualType ToType;
6937 bool HasUniqueTargetType = true;
6938
6939 // Collect explicit or viable (potentially in C++1y) conversions.
6940 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6941 NamedDecl *D = (*I)->getUnderlyingDecl();
6942 CXXConversionDecl *Conversion;
6943 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6944 if (ConvTemplate) {
6946 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6947 else
6948 continue; // C++11 does not consider conversion operator templates(?).
6949 } else
6950 Conversion = cast<CXXConversionDecl>(D);
6951
6952 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6953 "Conversion operator templates are considered potentially "
6954 "viable in C++1y");
6955
6956 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6957 if (Converter.match(CurToType) || ConvTemplate) {
6958
6959 if (Conversion->isExplicit()) {
6960 // FIXME: For C++1y, do we need this restriction?
6961 // cf. diagnoseNoViableConversion()
6962 if (!ConvTemplate)
6963 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6964 } else {
6965 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6966 if (ToType.isNull())
6967 ToType = CurToType.getUnqualifiedType();
6968 else if (HasUniqueTargetType &&
6969 (CurToType.getUnqualifiedType() != ToType))
6970 HasUniqueTargetType = false;
6971 }
6972 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6973 }
6974 }
6975 }
6976
6977 if (getLangOpts().CPlusPlus14) {
6978 // C++1y [conv]p6:
6979 // ... An expression e of class type E appearing in such a context
6980 // is said to be contextually implicitly converted to a specified
6981 // type T and is well-formed if and only if e can be implicitly
6982 // converted to a type T that is determined as follows: E is searched
6983 // for conversion functions whose return type is cv T or reference to
6984 // cv T such that T is allowed by the context. There shall be
6985 // exactly one such T.
6986
6987 // If no unique T is found:
6988 if (ToType.isNull()) {
6989 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6990 HadMultipleCandidates,
6991 ExplicitConversions))
6992 return ExprError();
6993 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6994 }
6995
6996 // If more than one unique Ts are found:
6997 if (!HasUniqueTargetType)
6998 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6999 ViableConversions);
7000
7001 // If one unique T is found:
7002 // First, build a candidate set from the previously recorded
7003 // potentially viable conversions.
7005 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7006 CandidateSet);
7007
7008 // Then, perform overload resolution over the candidate set.
7010 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7011 case OR_Success: {
7012 // Apply this conversion.
7014 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7015 if (recordConversion(*this, Loc, From, Converter, T,
7016 HadMultipleCandidates, Found))
7017 return ExprError();
7018 break;
7019 }
7020 case OR_Ambiguous:
7021 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7022 ViableConversions);
7024 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7025 HadMultipleCandidates,
7026 ExplicitConversions))
7027 return ExprError();
7028 [[fallthrough]];
7029 case OR_Deleted:
7030 // We'll complain below about a non-integral condition type.
7031 break;
7032 }
7033 } else {
7034 switch (ViableConversions.size()) {
7035 case 0: {
7036 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7037 HadMultipleCandidates,
7038 ExplicitConversions))
7039 return ExprError();
7040
7041 // We'll complain below about a non-integral condition type.
7042 break;
7043 }
7044 case 1: {
7045 // Apply this conversion.
7046 DeclAccessPair Found = ViableConversions[0];
7047 if (recordConversion(*this, Loc, From, Converter, T,
7048 HadMultipleCandidates, Found))
7049 return ExprError();
7050 break;
7051 }
7052 default:
7053 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7054 ViableConversions);
7055 }
7056 }
7057
7058 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7059}
7060
7061/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7062/// an acceptable non-member overloaded operator for a call whose
7063/// arguments have types T1 (and, if non-empty, T2). This routine
7064/// implements the check in C++ [over.match.oper]p3b2 concerning
7065/// enumeration types.
7067 FunctionDecl *Fn,
7068 ArrayRef<Expr *> Args) {
7069 QualType T1 = Args[0]->getType();
7070 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7071
7072 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7073 return true;
7074
7075 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7076 return true;
7077
7078 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7079 if (Proto->getNumParams() < 1)
7080 return false;
7081
7082 if (T1->isEnumeralType()) {
7083 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7084 if (Context.hasSameUnqualifiedType(T1, ArgType))
7085 return true;
7086 }
7087
7088 if (Proto->getNumParams() < 2)
7089 return false;
7090
7091 if (!T2.isNull() && T2->isEnumeralType()) {
7092 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7093 if (Context.hasSameUnqualifiedType(T2, ArgType))
7094 return true;
7095 }
7096
7097 return false;
7098}
7099
7102 return false;
7103
7104 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7105 return FD->isTargetMultiVersion();
7106
7107 if (!FD->isMultiVersion())
7108 return false;
7109
7110 // Among multiple target versions consider either the default,
7111 // or the first non-default in the absence of default version.
7112 unsigned SeenAt = 0;
7113 unsigned I = 0;
7114 bool HasDefault = false;
7116 FD, [&](const FunctionDecl *CurFD) {
7117 if (FD == CurFD)
7118 SeenAt = I;
7119 else if (CurFD->isTargetMultiVersionDefault())
7120 HasDefault = true;
7121 ++I;
7122 });
7123 return HasDefault || SeenAt != 0;
7124}
7125
7128 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7129 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7130 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7131 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7132 bool StrictPackMatch) {
7133 const FunctionProtoType *Proto
7134 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7135 assert(Proto && "Functions without a prototype cannot be overloaded");
7136 assert(!Function->getDescribedFunctionTemplate() &&
7137 "Use AddTemplateOverloadCandidate for function templates");
7138
7139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7141 // If we get here, it's because we're calling a member function
7142 // that is named without a member access expression (e.g.,
7143 // "this->f") that was either written explicitly or created
7144 // implicitly. This can happen with a qualified call to a member
7145 // function, e.g., X::f(). We use an empty type for the implied
7146 // object argument (C++ [over.call.func]p3), and the acting context
7147 // is irrelevant.
7148 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7150 CandidateSet, SuppressUserConversions,
7151 PartialOverloading, EarlyConversions, PO,
7152 StrictPackMatch);
7153 return;
7154 }
7155 // We treat a constructor like a non-member function, since its object
7156 // argument doesn't participate in overload resolution.
7157 }
7158
7159 if (!CandidateSet.isNewCandidate(Function, PO))
7160 return;
7161
7162 // C++11 [class.copy]p11: [DR1402]
7163 // A defaulted move constructor that is defined as deleted is ignored by
7164 // overload resolution.
7165 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7166 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7167 Constructor->isMoveConstructor())
7168 return;
7169
7170 // Overload resolution is always an unevaluated context.
7173
7174 // C++ [over.match.oper]p3:
7175 // if no operand has a class type, only those non-member functions in the
7176 // lookup set that have a first parameter of type T1 or "reference to
7177 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7178 // is a right operand) a second parameter of type T2 or "reference to
7179 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7180 // candidate functions.
7181 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7183 return;
7184
7185 // Add this candidate
7186 OverloadCandidate &Candidate =
7187 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7188 Candidate.FoundDecl = FoundDecl;
7189 Candidate.Function = Function;
7190 Candidate.Viable = true;
7191 Candidate.RewriteKind =
7192 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7193 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7194 Candidate.ExplicitCallArguments = Args.size();
7195 Candidate.StrictPackMatch = StrictPackMatch;
7196
7197 // Explicit functions are not actually candidates at all if we're not
7198 // allowing them in this context, but keep them around so we can point
7199 // to them in diagnostics.
7200 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7201 Candidate.Viable = false;
7202 Candidate.FailureKind = ovl_fail_explicit;
7203 return;
7204 }
7205
7206 // Functions with internal linkage are only viable in the same module unit.
7207 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7208 /// FIXME: Currently, the semantics of linkage in clang is slightly
7209 /// different from the semantics in C++ spec. In C++ spec, only names
7210 /// have linkage. So that all entities of the same should share one
7211 /// linkage. But in clang, different entities of the same could have
7212 /// different linkage.
7213 const NamedDecl *ND = Function;
7214 bool IsImplicitlyInstantiated = false;
7215 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7216 ND = SpecInfo->getTemplate();
7217 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7219 }
7220
7221 /// Don't remove inline functions with internal linkage from the overload
7222 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7223 /// However:
7224 /// - Inline functions with internal linkage are a common pattern in
7225 /// headers to avoid ODR issues.
7226 /// - The global module is meant to be a transition mechanism for C and C++
7227 /// headers, and the current rules as written work against that goal.
7228 const bool IsInlineFunctionInGMF =
7229 Function->isFromGlobalModule() &&
7230 (IsImplicitlyInstantiated || Function->isInlined());
7231
7232 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7233 Candidate.Viable = false;
7235 return;
7236 }
7237 }
7238
7240 Candidate.Viable = false;
7242 return;
7243 }
7244
7245 if (Constructor) {
7246 // C++ [class.copy]p3:
7247 // A member function template is never instantiated to perform the copy
7248 // of a class object to an object of its class type.
7249 CanQualType ClassType =
7250 Context.getCanonicalTagType(Constructor->getParent());
7251 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7252 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7253 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7254 ClassType))) {
7255 Candidate.Viable = false;
7257 return;
7258 }
7259
7260 // C++ [over.match.funcs]p8: (proposed DR resolution)
7261 // A constructor inherited from class type C that has a first parameter
7262 // of type "reference to P" (including such a constructor instantiated
7263 // from a template) is excluded from the set of candidate functions when
7264 // constructing an object of type cv D if the argument list has exactly
7265 // one argument and D is reference-related to P and P is reference-related
7266 // to C.
7267 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7268 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7269 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7270 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7271 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7272 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7273 SourceLocation Loc = Args.front()->getExprLoc();
7274 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7275 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7276 Candidate.Viable = false;
7278 return;
7279 }
7280 }
7281
7282 // Check that the constructor is capable of constructing an object in the
7283 // destination address space.
7285 Constructor->getMethodQualifiers().getAddressSpace(),
7286 CandidateSet.getDestAS(), getASTContext())) {
7287 Candidate.Viable = false;
7289 }
7290 }
7291
7292 unsigned NumParams = Proto->getNumParams();
7293
7294 // (C++ 13.3.2p2): A candidate function having fewer than m
7295 // parameters is viable only if it has an ellipsis in its parameter
7296 // list (8.3.5).
7297 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7298 !Proto->isVariadic() &&
7299 shouldEnforceArgLimit(PartialOverloading, Function)) {
7300 Candidate.Viable = false;
7302 return;
7303 }
7304
7305 // (C++ 13.3.2p2): A candidate function having more than m parameters
7306 // is viable only if the (m+1)st parameter has a default argument
7307 // (8.3.6). For the purposes of overload resolution, the
7308 // parameter list is truncated on the right, so that there are
7309 // exactly m parameters.
7310 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7311 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7312 !PartialOverloading) {
7313 // Not enough arguments.
7314 Candidate.Viable = false;
7316 return;
7317 }
7318
7319 // (CUDA B.1): Check for invalid calls between targets.
7320 if (getLangOpts().CUDA) {
7321 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7322 // Skip the check for callers that are implicit members, because in this
7323 // case we may not yet know what the member's target is; the target is
7324 // inferred for the member automatically, based on the bases and fields of
7325 // the class.
7326 if (!(Caller && Caller->isImplicit()) &&
7327 !CUDA().IsAllowedCall(Caller, Function)) {
7328 Candidate.Viable = false;
7329 Candidate.FailureKind = ovl_fail_bad_target;
7330 return;
7331 }
7332 }
7333
7334 if (Function->getTrailingRequiresClause()) {
7335 ConstraintSatisfaction Satisfaction;
7336 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7337 /*ForOverloadResolution*/ true) ||
7338 !Satisfaction.IsSatisfied) {
7339 Candidate.Viable = false;
7341 return;
7342 }
7343 }
7344
7345 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7346 // Determine the implicit conversion sequences for each of the
7347 // arguments.
7348 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7349 unsigned ConvIdx =
7350 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7351 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7352 // We already formed a conversion sequence for this parameter during
7353 // template argument deduction.
7354 } else if (ArgIdx < NumParams) {
7355 // (C++ 13.3.2p3): for F to be a viable function, there shall
7356 // exist for each argument an implicit conversion sequence
7357 // (13.3.3.1) that converts that argument to the corresponding
7358 // parameter of F.
7359 QualType ParamType = Proto->getParamType(ArgIdx);
7360 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7361 if (ParamABI == ParameterABI::HLSLOut ||
7362 ParamABI == ParameterABI::HLSLInOut)
7363 ParamType = ParamType.getNonReferenceType();
7364 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7365 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7366 /*InOverloadResolution=*/true,
7367 /*AllowObjCWritebackConversion=*/
7368 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7369 if (Candidate.Conversions[ConvIdx].isBad()) {
7370 Candidate.Viable = false;
7372 return;
7373 }
7374 } else {
7375 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7376 // argument for which there is no corresponding parameter is
7377 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7378 Candidate.Conversions[ConvIdx].setEllipsis();
7379 }
7380 }
7381
7382 if (EnableIfAttr *FailedAttr =
7383 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7384 Candidate.Viable = false;
7385 Candidate.FailureKind = ovl_fail_enable_if;
7386 Candidate.DeductionFailure.Data = FailedAttr;
7387 return;
7388 }
7389}
7390
7394 if (Methods.size() <= 1)
7395 return nullptr;
7396
7397 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7398 bool Match = true;
7399 ObjCMethodDecl *Method = Methods[b];
7400 unsigned NumNamedArgs = Sel.getNumArgs();
7401 // Method might have more arguments than selector indicates. This is due
7402 // to addition of c-style arguments in method.
7403 if (Method->param_size() > NumNamedArgs)
7404 NumNamedArgs = Method->param_size();
7405 if (Args.size() < NumNamedArgs)
7406 continue;
7407
7408 for (unsigned i = 0; i < NumNamedArgs; i++) {
7409 // We can't do any type-checking on a type-dependent argument.
7410 if (Args[i]->isTypeDependent()) {
7411 Match = false;
7412 break;
7413 }
7414
7415 ParmVarDecl *param = Method->parameters()[i];
7416 Expr *argExpr = Args[i];
7417 assert(argExpr && "SelectBestMethod(): missing expression");
7418
7419 // Strip the unbridged-cast placeholder expression off unless it's
7420 // a consumed argument.
7421 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7422 !param->hasAttr<CFConsumedAttr>())
7423 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7424
7425 // If the parameter is __unknown_anytype, move on to the next method.
7426 if (param->getType() == Context.UnknownAnyTy) {
7427 Match = false;
7428 break;
7429 }
7430
7431 ImplicitConversionSequence ConversionState
7432 = TryCopyInitialization(*this, argExpr, param->getType(),
7433 /*SuppressUserConversions*/false,
7434 /*InOverloadResolution=*/true,
7435 /*AllowObjCWritebackConversion=*/
7436 getLangOpts().ObjCAutoRefCount,
7437 /*AllowExplicit*/false);
7438 // This function looks for a reasonably-exact match, so we consider
7439 // incompatible pointer conversions to be a failure here.
7440 if (ConversionState.isBad() ||
7441 (ConversionState.isStandard() &&
7442 ConversionState.Standard.Second ==
7444 Match = false;
7445 break;
7446 }
7447 }
7448 // Promote additional arguments to variadic methods.
7449 if (Match && Method->isVariadic()) {
7450 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7451 if (Args[i]->isTypeDependent()) {
7452 Match = false;
7453 break;
7454 }
7456 Args[i], VariadicCallType::Method, nullptr);
7457 if (Arg.isInvalid()) {
7458 Match = false;
7459 break;
7460 }
7461 }
7462 } else {
7463 // Check for extra arguments to non-variadic methods.
7464 if (Args.size() != NumNamedArgs)
7465 Match = false;
7466 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7467 // Special case when selectors have no argument. In this case, select
7468 // one with the most general result type of 'id'.
7469 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7470 QualType ReturnT = Methods[b]->getReturnType();
7471 if (ReturnT->isObjCIdType())
7472 return Methods[b];
7473 }
7474 }
7475 }
7476
7477 if (Match)
7478 return Method;
7479 }
7480 return nullptr;
7481}
7482
7484 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7485 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7486 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7487 if (ThisArg) {
7488 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7489 assert(!isa<CXXConstructorDecl>(Method) &&
7490 "Shouldn't have `this` for ctors!");
7491 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7493 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7494 if (R.isInvalid())
7495 return false;
7496 ConvertedThis = R.get();
7497 } else {
7498 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7499 (void)MD;
7500 assert((MissingImplicitThis || MD->isStatic() ||
7502 "Expected `this` for non-ctor instance methods");
7503 }
7504 ConvertedThis = nullptr;
7505 }
7506
7507 // Ignore any variadic arguments. Converting them is pointless, since the
7508 // user can't refer to them in the function condition.
7509 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7510
7511 // Convert the arguments.
7512 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7513 ExprResult R;
7515 S.Context, Function->getParamDecl(I)),
7516 SourceLocation(), Args[I]);
7517
7518 if (R.isInvalid())
7519 return false;
7520
7521 ConvertedArgs.push_back(R.get());
7522 }
7523
7524 if (Trap.hasErrorOccurred())
7525 return false;
7526
7527 // Push default arguments if needed.
7528 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7529 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7530 ParmVarDecl *P = Function->getParamDecl(i);
7531 if (!P->hasDefaultArg())
7532 return false;
7533 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7534 if (R.isInvalid())
7535 return false;
7536 ConvertedArgs.push_back(R.get());
7537 }
7538
7539 if (Trap.hasErrorOccurred())
7540 return false;
7541 }
7542 return true;
7543}
7544
7546 SourceLocation CallLoc,
7547 ArrayRef<Expr *> Args,
7548 bool MissingImplicitThis) {
7549 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7550 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7551 return nullptr;
7552
7553 SFINAETrap Trap(*this);
7554 // Perform the access checking immediately so any access diagnostics are
7555 // caught by the SFINAE trap.
7556 llvm::scope_exit UndelayDiags(
7557 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7558 DelayedDiagnostics.popUndelayed(CurrentState);
7559 });
7560 SmallVector<Expr *, 16> ConvertedArgs;
7561 // FIXME: We should look into making enable_if late-parsed.
7562 Expr *DiscardedThis;
7564 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7565 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7566 return *EnableIfAttrs.begin();
7567
7568 for (auto *EIA : EnableIfAttrs) {
7570 // FIXME: This doesn't consider value-dependent cases, because doing so is
7571 // very difficult. Ideally, we should handle them more gracefully.
7572 if (EIA->getCond()->isValueDependent() ||
7573 !EIA->getCond()->EvaluateWithSubstitution(
7574 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7575 return EIA;
7576
7577 if (!Result.isInt() || !Result.getInt().getBoolValue())
7578 return EIA;
7579 }
7580 return nullptr;
7581}
7582
7583template <typename CheckFn>
7585 bool ArgDependent, SourceLocation Loc,
7586 CheckFn &&IsSuccessful) {
7588 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7589 if (ArgDependent == DIA->getArgDependent())
7590 Attrs.push_back(DIA);
7591 }
7592
7593 // Common case: No diagnose_if attributes, so we can quit early.
7594 if (Attrs.empty())
7595 return false;
7596
7597 auto WarningBegin = std::stable_partition(
7598 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7599 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7600 DIA->getWarningGroup().empty();
7601 });
7602
7603 // Note that diagnose_if attributes are late-parsed, so they appear in the
7604 // correct order (unlike enable_if attributes).
7605 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7606 IsSuccessful);
7607 if (ErrAttr != WarningBegin) {
7608 const DiagnoseIfAttr *DIA = *ErrAttr;
7609 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7610 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7611 << DIA->getParent() << DIA->getCond()->getSourceRange();
7612 return true;
7613 }
7614
7615 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7616 switch (Sev) {
7617 case DiagnoseIfAttr::DS_warning:
7619 case DiagnoseIfAttr::DS_error:
7620 return diag::Severity::Error;
7621 }
7622 llvm_unreachable("Fully covered switch above!");
7623 };
7624
7625 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7626 if (IsSuccessful(DIA)) {
7627 if (DIA->getWarningGroup().empty() &&
7628 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7629 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7630 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7631 << DIA->getParent() << DIA->getCond()->getSourceRange();
7632 } else {
7633 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7634 DIA->getWarningGroup());
7635 assert(DiagGroup);
7636 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7637 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7638 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7639 S.Diag(Loc, DiagID) << DIA->getMessage();
7640 }
7641 }
7642
7643 return false;
7644}
7645
7647 const Expr *ThisArg,
7649 SourceLocation Loc) {
7651 *this, Function, /*ArgDependent=*/true, Loc,
7652 [&](const DiagnoseIfAttr *DIA) {
7654 // It's sane to use the same Args for any redecl of this function, since
7655 // EvaluateWithSubstitution only cares about the position of each
7656 // argument in the arg list, not the ParmVarDecl* it maps to.
7657 if (!DIA->getCond()->EvaluateWithSubstitution(
7658 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7659 return false;
7660 return Result.isInt() && Result.getInt().getBoolValue();
7661 });
7662}
7663
7665 SourceLocation Loc) {
7667 *this, ND, /*ArgDependent=*/false, Loc,
7668 [&](const DiagnoseIfAttr *DIA) {
7669 bool Result;
7670 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7671 Result;
7672 });
7673}
7674
7676 ArrayRef<Expr *> Args,
7677 OverloadCandidateSet &CandidateSet,
7678 TemplateArgumentListInfo *ExplicitTemplateArgs,
7679 bool SuppressUserConversions,
7680 bool PartialOverloading,
7681 bool FirstArgumentIsBase) {
7682 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7683 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7684 ArrayRef<Expr *> FunctionArgs = Args;
7685
7686 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7687 FunctionDecl *FD =
7688 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7689
7690 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7691 QualType ObjectType;
7692 Expr::Classification ObjectClassification;
7693 if (Args.size() > 0) {
7694 if (Expr *E = Args[0]) {
7695 // Use the explicit base to restrict the lookup:
7696 ObjectType = E->getType();
7697 // Pointers in the object arguments are implicitly dereferenced, so we
7698 // always classify them as l-values.
7699 if (!ObjectType.isNull() && ObjectType->isPointerType())
7700 ObjectClassification = Expr::Classification::makeSimpleLValue();
7701 else
7702 ObjectClassification = E->Classify(Context);
7703 } // .. else there is an implicit base.
7704 FunctionArgs = Args.slice(1);
7705 }
7706 if (FunTmpl) {
7708 FunTmpl, F.getPair(),
7710 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7711 FunctionArgs, CandidateSet, SuppressUserConversions,
7712 PartialOverloading);
7713 } else {
7714 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7715 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7716 ObjectClassification, FunctionArgs, CandidateSet,
7717 SuppressUserConversions, PartialOverloading);
7718 }
7719 } else {
7720 // This branch handles both standalone functions and static methods.
7721
7722 // Slice the first argument (which is the base) when we access
7723 // static method as non-static.
7724 if (Args.size() > 0 &&
7725 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7726 !isa<CXXConstructorDecl>(FD)))) {
7727 assert(cast<CXXMethodDecl>(FD)->isStatic());
7728 FunctionArgs = Args.slice(1);
7729 }
7730 if (FunTmpl) {
7731 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7732 ExplicitTemplateArgs, FunctionArgs,
7733 CandidateSet, SuppressUserConversions,
7734 PartialOverloading);
7735 } else {
7736 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7737 SuppressUserConversions, PartialOverloading);
7738 }
7739 }
7740 }
7741}
7742
7744 Expr::Classification ObjectClassification,
7745 ArrayRef<Expr *> Args,
7746 OverloadCandidateSet &CandidateSet,
7747 bool SuppressUserConversions,
7749 NamedDecl *Decl = FoundDecl.getDecl();
7751
7753 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7754
7755 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7756 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7757 "Expected a member function template");
7758 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7759 /*ExplicitArgs*/ nullptr, ObjectType,
7760 ObjectClassification, Args, CandidateSet,
7761 SuppressUserConversions, false, PO);
7762 } else {
7763 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7764 ObjectType, ObjectClassification, Args, CandidateSet,
7765 SuppressUserConversions, false, {}, PO);
7766 }
7767}
7768
7771 CXXRecordDecl *ActingContext, QualType ObjectType,
7772 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7773 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7774 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7775 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7776 const FunctionProtoType *Proto
7777 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7778 assert(Proto && "Methods without a prototype cannot be overloaded");
7780 "Use AddOverloadCandidate for constructors");
7781
7782 if (!CandidateSet.isNewCandidate(Method, PO))
7783 return;
7784
7785 // C++11 [class.copy]p23: [DR1402]
7786 // A defaulted move assignment operator that is defined as deleted is
7787 // ignored by overload resolution.
7788 if (Method->isDefaulted() && Method->isDeleted() &&
7789 Method->isMoveAssignmentOperator())
7790 return;
7791
7792 // Overload resolution is always an unevaluated context.
7795
7796 bool IgnoreExplicitObject =
7797 (Method->isExplicitObjectMemberFunction() &&
7798 CandidateSet.getKind() ==
7800 bool ImplicitObjectMethodTreatedAsStatic =
7801 CandidateSet.getKind() ==
7803 Method->isImplicitObjectMemberFunction();
7804
7805 unsigned ExplicitOffset =
7806 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7807
7808 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7809 int(ImplicitObjectMethodTreatedAsStatic);
7810
7811 unsigned ExtraArgs =
7813 ? 0
7814 : 1;
7815
7816 // Add this candidate
7817 OverloadCandidate &Candidate =
7818 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7819 Candidate.FoundDecl = FoundDecl;
7820 Candidate.Function = Method;
7821 Candidate.RewriteKind =
7822 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7823 Candidate.TookAddressOfOverload =
7825 Candidate.ExplicitCallArguments = Args.size();
7826 Candidate.StrictPackMatch = StrictPackMatch;
7827
7828 // (C++ 13.3.2p2): A candidate function having fewer than m
7829 // parameters is viable only if it has an ellipsis in its parameter
7830 // list (8.3.5).
7831 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7832 !Proto->isVariadic() &&
7833 shouldEnforceArgLimit(PartialOverloading, Method)) {
7834 Candidate.Viable = false;
7836 return;
7837 }
7838
7839 // (C++ 13.3.2p2): A candidate function having more than m parameters
7840 // is viable only if the (m+1)st parameter has a default argument
7841 // (8.3.6). For the purposes of overload resolution, the
7842 // parameter list is truncated on the right, so that there are
7843 // exactly m parameters.
7844 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7845 ExplicitOffset +
7846 int(ImplicitObjectMethodTreatedAsStatic);
7847
7848 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7849 // Not enough arguments.
7850 Candidate.Viable = false;
7852 return;
7853 }
7854
7855 Candidate.Viable = true;
7856
7857 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7858 if (!IgnoreExplicitObject) {
7859 if (ObjectType.isNull())
7860 Candidate.IgnoreObjectArgument = true;
7861 else if (Method->isStatic()) {
7862 // [over.best.ics.general]p8
7863 // When the parameter is the implicit object parameter of a static member
7864 // function, the implicit conversion sequence is a standard conversion
7865 // sequence that is neither better nor worse than any other standard
7866 // conversion sequence.
7867 //
7868 // This is a rule that was introduced in C++23 to support static lambdas.
7869 // We apply it retroactively because we want to support static lambdas as
7870 // an extension and it doesn't hurt previous code.
7871 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7872 } else {
7873 // Determine the implicit conversion sequence for the object
7874 // parameter.
7875 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7876 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7877 Method, ActingContext, /*InOverloadResolution=*/true);
7878 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7879 Candidate.Viable = false;
7881 return;
7882 }
7883 }
7884 }
7885
7886 // (CUDA B.1): Check for invalid calls between targets.
7887 if (getLangOpts().CUDA)
7888 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7889 Method)) {
7890 Candidate.Viable = false;
7891 Candidate.FailureKind = ovl_fail_bad_target;
7892 return;
7893 }
7894
7895 if (Method->getTrailingRequiresClause()) {
7896 ConstraintSatisfaction Satisfaction;
7897 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7898 /*ForOverloadResolution*/ true) ||
7899 !Satisfaction.IsSatisfied) {
7900 Candidate.Viable = false;
7902 return;
7903 }
7904 }
7905
7906 // Determine the implicit conversion sequences for each of the
7907 // arguments.
7908 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7909 unsigned ConvIdx =
7910 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7911 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7912 // We already formed a conversion sequence for this parameter during
7913 // template argument deduction.
7914 } else if (ArgIdx < NumParams) {
7915 // (C++ 13.3.2p3): for F to be a viable function, there shall
7916 // exist for each argument an implicit conversion sequence
7917 // (13.3.3.1) that converts that argument to the corresponding
7918 // parameter of F.
7919 QualType ParamType;
7920 if (ImplicitObjectMethodTreatedAsStatic) {
7921 ParamType = ArgIdx == 0
7922 ? Method->getFunctionObjectParameterReferenceType()
7923 : Proto->getParamType(ArgIdx - 1);
7924 } else {
7925 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7926 }
7927 Candidate.Conversions[ConvIdx]
7928 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7929 SuppressUserConversions,
7930 /*InOverloadResolution=*/true,
7931 /*AllowObjCWritebackConversion=*/
7932 getLangOpts().ObjCAutoRefCount);
7933 if (Candidate.Conversions[ConvIdx].isBad()) {
7934 Candidate.Viable = false;
7936 return;
7937 }
7938 } else {
7939 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7940 // argument for which there is no corresponding parameter is
7941 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7942 Candidate.Conversions[ConvIdx].setEllipsis();
7943 }
7944 }
7945
7946 if (EnableIfAttr *FailedAttr =
7947 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7948 Candidate.Viable = false;
7949 Candidate.FailureKind = ovl_fail_enable_if;
7950 Candidate.DeductionFailure.Data = FailedAttr;
7951 return;
7952 }
7953
7955 Candidate.Viable = false;
7957 }
7958}
7959
7961 Sema &S, OverloadCandidateSet &CandidateSet,
7962 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7963 CXXRecordDecl *ActingContext,
7964 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7965 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7966 bool SuppressUserConversions, bool PartialOverloading,
7968
7969 // C++ [over.match.funcs]p7:
7970 // In each case where a candidate is a function template, candidate
7971 // function template specializations are generated using template argument
7972 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7973 // candidate functions in the usual way.113) A given name can refer to one
7974 // or more function templates and also to a set of overloaded non-template
7975 // functions. In such a case, the candidate functions generated from each
7976 // function template are combined with the set of non-template candidate
7977 // functions.
7978 TemplateDeductionInfo Info(CandidateSet.getLocation());
7979 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7980 FunctionDecl *Specialization = nullptr;
7981 ConversionSequenceList Conversions;
7983 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7984 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7985 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7986 CandidateSet.getKind() ==
7988 [&](ArrayRef<QualType> ParamTypes,
7989 bool OnlyInitializeNonUserDefinedConversions) {
7990 return S.CheckNonDependentConversions(
7991 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7992 Sema::CheckNonDependentConversionsFlag(
7993 SuppressUserConversions,
7994 OnlyInitializeNonUserDefinedConversions),
7995 ActingContext, ObjectType, ObjectClassification, PO);
7996 });
7998 OverloadCandidate &Candidate =
7999 CandidateSet.addCandidate(Conversions.size(), Conversions);
8000 Candidate.FoundDecl = FoundDecl;
8001 Candidate.Function = Method;
8002 Candidate.Viable = false;
8003 Candidate.RewriteKind =
8004 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8005 Candidate.IsSurrogate = false;
8006 Candidate.TookAddressOfOverload =
8007 CandidateSet.getKind() ==
8009
8010 Candidate.IgnoreObjectArgument =
8011 Method->isStatic() ||
8012 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8013 Candidate.ExplicitCallArguments = Args.size();
8016 else {
8018 Candidate.DeductionFailure =
8019 MakeDeductionFailureInfo(S.Context, Result, Info);
8020 }
8021 return;
8022 }
8023
8024 // Add the function template specialization produced by template argument
8025 // deduction as a candidate.
8026 assert(Specialization && "Missing member function template specialization?");
8028 "Specialization is not a member function?");
8030 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8031 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8032 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8033}
8034
8036 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8037 CXXRecordDecl *ActingContext,
8038 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8039 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8040 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8041 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8042 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8043 return;
8044
8045 if (ExplicitTemplateArgs ||
8048 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8049 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8050 SuppressUserConversions, PartialOverloading, PO);
8051 return;
8052 }
8053
8055 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8056 Args, SuppressUserConversions, PartialOverloading, PO);
8057}
8058
8059/// Determine whether a given function template has a simple explicit specifier
8060/// or a non-value-dependent explicit-specification that evaluates to true.
8064
8069
8071 Sema &S, OverloadCandidateSet &CandidateSet,
8073 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8074 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8076 bool AggregateCandidateDeduction) {
8077
8078 // If the function template has a non-dependent explicit specification,
8079 // exclude it now if appropriate; we are not permitted to perform deduction
8080 // and substitution in this case.
8081 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8082 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8083 Candidate.FoundDecl = FoundDecl;
8084 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8085 Candidate.Viable = false;
8086 Candidate.FailureKind = ovl_fail_explicit;
8087 return;
8088 }
8089
8090 // C++ [over.match.funcs]p7:
8091 // In each case where a candidate is a function template, candidate
8092 // function template specializations are generated using template argument
8093 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8094 // candidate functions in the usual way.113) A given name can refer to one
8095 // or more function templates and also to a set of overloaded non-template
8096 // functions. In such a case, the candidate functions generated from each
8097 // function template are combined with the set of non-template candidate
8098 // functions.
8099 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8100 FunctionTemplate->getTemplateDepth());
8101 FunctionDecl *Specialization = nullptr;
8102 ConversionSequenceList Conversions;
8104 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8105 PartialOverloading, AggregateCandidateDeduction,
8106 /*PartialOrdering=*/false,
8107 /*ObjectType=*/QualType(),
8108 /*ObjectClassification=*/Expr::Classification(),
8109 CandidateSet.getKind() ==
8111 [&](ArrayRef<QualType> ParamTypes,
8112 bool OnlyInitializeNonUserDefinedConversions) {
8113 return S.CheckNonDependentConversions(
8114 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8115 Sema::CheckNonDependentConversionsFlag(
8116 SuppressUserConversions,
8117 OnlyInitializeNonUserDefinedConversions),
8118 nullptr, QualType(), {}, PO);
8119 });
8121 OverloadCandidate &Candidate =
8122 CandidateSet.addCandidate(Conversions.size(), Conversions);
8123 Candidate.FoundDecl = FoundDecl;
8124 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8125 Candidate.Viable = false;
8126 Candidate.RewriteKind =
8127 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8128 Candidate.IsSurrogate = false;
8129 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8130 // Ignore the object argument if there is one, since we don't have an object
8131 // type.
8132 Candidate.TookAddressOfOverload =
8133 CandidateSet.getKind() ==
8135
8136 Candidate.IgnoreObjectArgument =
8137 isa<CXXMethodDecl>(Candidate.Function) &&
8138 !cast<CXXMethodDecl>(Candidate.Function)
8139 ->isExplicitObjectMemberFunction() &&
8141
8142 Candidate.ExplicitCallArguments = Args.size();
8145 else {
8147 Candidate.DeductionFailure =
8149 }
8150 return;
8151 }
8152
8153 // Add the function template specialization produced by template argument
8154 // deduction as a candidate.
8155 assert(Specialization && "Missing function template specialization?");
8157 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8158 PartialOverloading, AllowExplicit,
8159 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8160 Info.AggregateDeductionCandidateHasMismatchedArity,
8161 Info.hasStrictPackMatch());
8162}
8163
8166 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8167 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8168 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8169 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8170 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8171 return;
8172
8173 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8174
8175 if (ExplicitTemplateArgs ||
8177 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8178 DependentExplicitSpecifier)) {
8179
8181 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8182 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8183 IsADLCandidate, PO, AggregateCandidateDeduction);
8184
8185 if (DependentExplicitSpecifier)
8187 return;
8188 }
8189
8190 CandidateSet.AddDeferredTemplateCandidate(
8191 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8192 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8193 AggregateCandidateDeduction);
8194}
8195
8198 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8200 CheckNonDependentConversionsFlag UserConversionFlag,
8201 CXXRecordDecl *ActingContext, QualType ObjectType,
8202 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8203 // FIXME: The cases in which we allow explicit conversions for constructor
8204 // arguments never consider calling a constructor template. It's not clear
8205 // that is correct.
8206 const bool AllowExplicit = false;
8207
8208 bool ForOverloadSetAddressResolution =
8210 auto *FD = FunctionTemplate->getTemplatedDecl();
8211 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8212 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8214 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8215
8216 if (Conversions.empty())
8217 Conversions =
8218 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8219
8220 // Overload resolution is always an unevaluated context.
8223
8224 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8225 // require that, but this check should never result in a hard error, and
8226 // overload resolution is permitted to sidestep instantiations.
8227 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8228 !ObjectType.isNull()) {
8229 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8230 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8231 !ParamTypes[0]->isDependentType()) {
8233 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8234 Method, ActingContext, /*InOverloadResolution=*/true,
8235 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8236 : QualType());
8237 if (Conversions[ConvIdx].isBad())
8238 return true;
8239 }
8240 }
8241
8242 // A speculative workaround for self-dependent constraint bugs that manifest
8243 // after CWG2369.
8244 // FIXME: Add references to the standard once P3606 is adopted.
8245 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8246 QualType ArgType) {
8247 ParamType = ParamType.getNonReferenceType();
8248 ArgType = ArgType.getNonReferenceType();
8249 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8250 if (PointerConv) {
8251 ParamType = ParamType->getPointeeType();
8252 ArgType = ArgType->getPointeeType();
8253 }
8254
8255 if (auto *RD = ParamType->getAsCXXRecordDecl();
8256 RD && RD->hasDefinition() &&
8257 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8258 auto Info = getConstructorInfo(ND);
8259 if (!Info)
8260 return false;
8261 CXXConstructorDecl *Ctor = Info.Constructor;
8262 /// isConvertingConstructor takes copy/move constructors into
8263 /// account!
8264 return !Ctor->isCopyOrMoveConstructor() &&
8266 /*AllowExplicit=*/true);
8267 }))
8268 return true;
8269 if (auto *RD = ArgType->getAsCXXRecordDecl();
8270 RD && RD->hasDefinition() &&
8271 !RD->getVisibleConversionFunctions().empty())
8272 return true;
8273
8274 return false;
8275 };
8276
8277 unsigned Offset =
8278 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8279 : 0;
8280
8281 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8282 I != N; ++I) {
8283 QualType ParamType = ParamTypes[I + Offset];
8284 if (!ParamType->isDependentType()) {
8285 unsigned ConvIdx;
8287 ConvIdx = Args.size() - 1 - I;
8288 assert(Args.size() + ThisConversions == 2 &&
8289 "number of args (including 'this') must be exactly 2 for "
8290 "reversed order");
8291 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8292 // would also be 0. 'this' got ConvIdx = 1 previously.
8293 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8294 } else {
8295 // For members, 'this' got ConvIdx = 0 previously.
8296 ConvIdx = ThisConversions + I;
8297 }
8298 if (Conversions[ConvIdx].isInitialized())
8299 continue;
8300 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8301 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8302 continue;
8304 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8305 /*InOverloadResolution=*/true,
8306 /*AllowObjCWritebackConversion=*/
8307 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8308 if (Conversions[ConvIdx].isBad())
8309 return true;
8310 }
8311 }
8312
8313 return false;
8314}
8315
8316/// Determine whether this is an allowable conversion from the result
8317/// of an explicit conversion operator to the expected type, per C++
8318/// [over.match.conv]p1 and [over.match.ref]p1.
8319///
8320/// \param ConvType The return type of the conversion function.
8321///
8322/// \param ToType The type we are converting to.
8323///
8324/// \param AllowObjCPointerConversion Allow a conversion from one
8325/// Objective-C pointer to another.
8326///
8327/// \returns true if the conversion is allowable, false otherwise.
8329 QualType ConvType, QualType ToType,
8330 bool AllowObjCPointerConversion) {
8331 QualType ToNonRefType = ToType.getNonReferenceType();
8332
8333 // Easy case: the types are the same.
8334 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8335 return true;
8336
8337 // Allow qualification conversions.
8338 bool ObjCLifetimeConversion;
8339 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8340 ObjCLifetimeConversion))
8341 return true;
8342
8343 // If we're not allowed to consider Objective-C pointer conversions,
8344 // we're done.
8345 if (!AllowObjCPointerConversion)
8346 return false;
8347
8348 // Is this an Objective-C pointer conversion?
8349 bool IncompatibleObjC = false;
8350 QualType ConvertedType;
8351 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8352 IncompatibleObjC);
8353}
8354
8356 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8357 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8358 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8359 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8360 assert(!Conversion->getDescribedFunctionTemplate() &&
8361 "Conversion function templates use AddTemplateConversionCandidate");
8362 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8363 if (!CandidateSet.isNewCandidate(Conversion))
8364 return;
8365
8366 // If the conversion function has an undeduced return type, trigger its
8367 // deduction now.
8368 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8369 if (DeduceReturnType(Conversion, From->getExprLoc()))
8370 return;
8371 ConvType = Conversion->getConversionType().getNonReferenceType();
8372 }
8373
8374 // If we don't allow any conversion of the result type, ignore conversion
8375 // functions that don't convert to exactly (possibly cv-qualified) T.
8376 if (!AllowResultConversion &&
8377 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8378 return;
8379
8380 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8381 // operator is only a candidate if its return type is the target type or
8382 // can be converted to the target type with a qualification conversion.
8383 //
8384 // FIXME: Include such functions in the candidate list and explain why we
8385 // can't select them.
8386 if (Conversion->isExplicit() &&
8387 !isAllowableExplicitConversion(*this, ConvType, ToType,
8388 AllowObjCConversionOnExplicit))
8389 return;
8390
8391 // Overload resolution is always an unevaluated context.
8394
8395 // Add this candidate
8396 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8397 Candidate.FoundDecl = FoundDecl;
8398 Candidate.Function = Conversion;
8400 Candidate.FinalConversion.setFromType(ConvType);
8401 Candidate.FinalConversion.setAllToTypes(ToType);
8402 Candidate.HasFinalConversion = true;
8403 Candidate.Viable = true;
8404 Candidate.ExplicitCallArguments = 1;
8405 Candidate.StrictPackMatch = StrictPackMatch;
8406
8407 // Explicit functions are not actually candidates at all if we're not
8408 // allowing them in this context, but keep them around so we can point
8409 // to them in diagnostics.
8410 if (!AllowExplicit && Conversion->isExplicit()) {
8411 Candidate.Viable = false;
8412 Candidate.FailureKind = ovl_fail_explicit;
8413 return;
8414 }
8415
8416 // C++ [over.match.funcs]p4:
8417 // For conversion functions, the function is considered to be a member of
8418 // the class of the implicit implied object argument for the purpose of
8419 // defining the type of the implicit object parameter.
8420 //
8421 // Determine the implicit conversion sequence for the implicit
8422 // object parameter.
8423 QualType ObjectType = From->getType();
8424 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8425 ObjectType = FromPtrType->getPointeeType();
8426 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8427 // C++23 [over.best.ics.general]
8428 // However, if the target is [...]
8429 // - the object parameter of a user-defined conversion function
8430 // [...] user-defined conversion sequences are not considered.
8432 *this, CandidateSet.getLocation(), From->getType(),
8433 From->Classify(Context), Conversion, ConversionContext,
8434 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8435 /*SuppressUserConversion*/ true);
8436
8437 if (Candidate.Conversions[0].isBad()) {
8438 Candidate.Viable = false;
8440 return;
8441 }
8442
8443 if (Conversion->getTrailingRequiresClause()) {
8444 ConstraintSatisfaction Satisfaction;
8445 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8446 !Satisfaction.IsSatisfied) {
8447 Candidate.Viable = false;
8449 return;
8450 }
8451 }
8452
8453 // We won't go through a user-defined type conversion function to convert a
8454 // derived to base as such conversions are given Conversion Rank. They only
8455 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8456 QualType FromCanon
8457 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8458 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8459 if (FromCanon == ToCanon ||
8460 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8461 Candidate.Viable = false;
8463 return;
8464 }
8465
8466 // To determine what the conversion from the result of calling the
8467 // conversion function to the type we're eventually trying to
8468 // convert to (ToType), we need to synthesize a call to the
8469 // conversion function and attempt copy initialization from it. This
8470 // makes sure that we get the right semantics with respect to
8471 // lvalues/rvalues and the type. Fortunately, we can allocate this
8472 // call on the stack and we don't need its arguments to be
8473 // well-formed.
8474 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8475 VK_LValue, From->getBeginLoc());
8477 Context.getPointerType(Conversion->getType()),
8478 CK_FunctionToPointerDecay, &ConversionRef,
8480
8481 QualType ConversionType = Conversion->getConversionType();
8482 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8483 Candidate.Viable = false;
8485 return;
8486 }
8487
8488 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8489
8490 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8491
8492 // Introduce a temporary expression with the right type and value category
8493 // that we can use for deduction purposes.
8494 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8495
8497 TryCopyInitialization(*this, &FakeCall, ToType,
8498 /*SuppressUserConversions=*/true,
8499 /*InOverloadResolution=*/false,
8500 /*AllowObjCWritebackConversion=*/false);
8501
8502 switch (ICS.getKind()) {
8504 Candidate.FinalConversion = ICS.Standard;
8505 Candidate.HasFinalConversion = true;
8506
8507 // C++ [over.ics.user]p3:
8508 // If the user-defined conversion is specified by a specialization of a
8509 // conversion function template, the second standard conversion sequence
8510 // shall have exact match rank.
8511 if (Conversion->getPrimaryTemplate() &&
8513 Candidate.Viable = false;
8515 return;
8516 }
8517
8518 // C++0x [dcl.init.ref]p5:
8519 // In the second case, if the reference is an rvalue reference and
8520 // the second standard conversion sequence of the user-defined
8521 // conversion sequence includes an lvalue-to-rvalue conversion, the
8522 // program is ill-formed.
8523 if (ToType->isRValueReferenceType() &&
8525 Candidate.Viable = false;
8527 return;
8528 }
8529 break;
8530
8532 Candidate.Viable = false;
8534 return;
8535
8536 default:
8537 llvm_unreachable(
8538 "Can only end up with a standard conversion sequence or failure");
8539 }
8540
8541 if (EnableIfAttr *FailedAttr =
8542 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8543 Candidate.Viable = false;
8544 Candidate.FailureKind = ovl_fail_enable_if;
8545 Candidate.DeductionFailure.Data = FailedAttr;
8546 return;
8547 }
8548
8549 if (isNonViableMultiVersionOverload(Conversion)) {
8550 Candidate.Viable = false;
8552 }
8553}
8554
8556 Sema &S, OverloadCandidateSet &CandidateSet,
8558 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8559 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8560 bool AllowResultConversion) {
8561
8562 // If the function template has a non-dependent explicit specification,
8563 // exclude it now if appropriate; we are not permitted to perform deduction
8564 // and substitution in this case.
8565 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8566 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8567 Candidate.FoundDecl = FoundDecl;
8568 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8569 Candidate.Viable = false;
8570 Candidate.FailureKind = ovl_fail_explicit;
8571 return;
8572 }
8573
8574 QualType ObjectType = From->getType();
8575 Expr::Classification ObjectClassification = From->Classify(S.Context);
8576
8577 TemplateDeductionInfo Info(CandidateSet.getLocation());
8580 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8581 Specialization, Info);
8583 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8584 Candidate.FoundDecl = FoundDecl;
8585 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8586 Candidate.Viable = false;
8588 Candidate.ExplicitCallArguments = 1;
8589 Candidate.DeductionFailure =
8590 MakeDeductionFailureInfo(S.Context, Result, Info);
8591 return;
8592 }
8593
8594 // Add the conversion function template specialization produced by
8595 // template argument deduction as a candidate.
8596 assert(Specialization && "Missing function template specialization?");
8597 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8598 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8599 AllowExplicit, AllowResultConversion,
8600 Info.hasStrictPackMatch());
8601}
8602
8605 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8606 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8607 bool AllowExplicit, bool AllowResultConversion) {
8608 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8609 "Only conversion function templates permitted here");
8610
8611 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8612 return;
8613
8615 CandidateSet.getKind() ==
8619 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8620 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8621 AllowResultConversion);
8622
8624 return;
8625 }
8626
8628 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8629 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8630}
8631
8633 DeclAccessPair FoundDecl,
8634 CXXRecordDecl *ActingContext,
8635 const FunctionProtoType *Proto,
8636 Expr *Object,
8637 ArrayRef<Expr *> Args,
8638 OverloadCandidateSet& CandidateSet) {
8639 if (!CandidateSet.isNewCandidate(Conversion))
8640 return;
8641
8642 // Overload resolution is always an unevaluated context.
8645
8646 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8647 Candidate.FoundDecl = FoundDecl;
8648 Candidate.Function = nullptr;
8649 Candidate.Surrogate = Conversion;
8650 Candidate.IsSurrogate = true;
8651 Candidate.Viable = true;
8652 Candidate.ExplicitCallArguments = Args.size();
8653
8654 // Determine the implicit conversion sequence for the implicit
8655 // object parameter.
8656 ImplicitConversionSequence ObjectInit;
8657 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8658 ObjectInit = TryCopyInitialization(*this, Object,
8659 Conversion->getParamDecl(0)->getType(),
8660 /*SuppressUserConversions=*/false,
8661 /*InOverloadResolution=*/true, false);
8662 } else {
8664 *this, CandidateSet.getLocation(), Object->getType(),
8665 Object->Classify(Context), Conversion, ActingContext);
8666 }
8667
8668 if (ObjectInit.isBad()) {
8669 Candidate.Viable = false;
8671 Candidate.Conversions[0] = ObjectInit;
8672 return;
8673 }
8674
8675 // The first conversion is actually a user-defined conversion whose
8676 // first conversion is ObjectInit's standard conversion (which is
8677 // effectively a reference binding). Record it as such.
8678 Candidate.Conversions[0].setUserDefined();
8679 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8680 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8681 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8682 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8683 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8684 Candidate.Conversions[0].UserDefined.After
8685 = Candidate.Conversions[0].UserDefined.Before;
8686 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8687
8688 // Find the
8689 unsigned NumParams = Proto->getNumParams();
8690
8691 // (C++ 13.3.2p2): A candidate function having fewer than m
8692 // parameters is viable only if it has an ellipsis in its parameter
8693 // list (8.3.5).
8694 if (Args.size() > NumParams && !Proto->isVariadic()) {
8695 Candidate.Viable = false;
8697 return;
8698 }
8699
8700 // Function types don't have any default arguments, so just check if
8701 // we have enough arguments.
8702 if (Args.size() < NumParams) {
8703 // Not enough arguments.
8704 Candidate.Viable = false;
8706 return;
8707 }
8708
8709 // Determine the implicit conversion sequences for each of the
8710 // arguments.
8711 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8712 if (ArgIdx < NumParams) {
8713 // (C++ 13.3.2p3): for F to be a viable function, there shall
8714 // exist for each argument an implicit conversion sequence
8715 // (13.3.3.1) that converts that argument to the corresponding
8716 // parameter of F.
8717 QualType ParamType = Proto->getParamType(ArgIdx);
8718 Candidate.Conversions[ArgIdx + 1]
8719 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8720 /*SuppressUserConversions=*/false,
8721 /*InOverloadResolution=*/false,
8722 /*AllowObjCWritebackConversion=*/
8723 getLangOpts().ObjCAutoRefCount);
8724 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8725 Candidate.Viable = false;
8727 return;
8728 }
8729 } else {
8730 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8731 // argument for which there is no corresponding parameter is
8732 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8733 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8734 }
8735 }
8736
8737 if (Conversion->getTrailingRequiresClause()) {
8738 ConstraintSatisfaction Satisfaction;
8739 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8740 /*ForOverloadResolution*/ true) ||
8741 !Satisfaction.IsSatisfied) {
8742 Candidate.Viable = false;
8744 return;
8745 }
8746 }
8747
8748 if (EnableIfAttr *FailedAttr =
8749 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8750 Candidate.Viable = false;
8751 Candidate.FailureKind = ovl_fail_enable_if;
8752 Candidate.DeductionFailure.Data = FailedAttr;
8753 return;
8754 }
8755}
8756
8758 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8759 OverloadCandidateSet &CandidateSet,
8760 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8761 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8762 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8763 ArrayRef<Expr *> FunctionArgs = Args;
8764
8765 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8766 FunctionDecl *FD =
8767 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8768
8769 // Don't consider rewritten functions if we're not rewriting.
8770 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8771 continue;
8772
8773 assert(!isa<CXXMethodDecl>(FD) &&
8774 "unqualified operator lookup found a member function");
8775
8776 if (FunTmpl) {
8777 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8778 FunctionArgs, CandidateSet);
8779 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8780
8781 // As template candidates are not deduced immediately,
8782 // persist the array in the overload set.
8784 FunctionArgs[1], FunctionArgs[0]);
8785 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8786 Reversed, CandidateSet, false, false, true,
8787 ADLCallKind::NotADL,
8789 }
8790 } else {
8791 if (ExplicitTemplateArgs)
8792 continue;
8793 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8794 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8795 AddOverloadCandidate(FD, F.getPair(),
8796 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8797 false, false, true, false, ADLCallKind::NotADL, {},
8799 }
8800 }
8801}
8802
8804 SourceLocation OpLoc,
8805 ArrayRef<Expr *> Args,
8806 OverloadCandidateSet &CandidateSet,
8808 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8809
8810 // C++ [over.match.oper]p3:
8811 // For a unary operator @ with an operand of a type whose
8812 // cv-unqualified version is T1, and for a binary operator @ with
8813 // a left operand of a type whose cv-unqualified version is T1 and
8814 // a right operand of a type whose cv-unqualified version is T2,
8815 // three sets of candidate functions, designated member
8816 // candidates, non-member candidates and built-in candidates, are
8817 // constructed as follows:
8818 QualType T1 = Args[0]->getType();
8819
8820 // -- If T1 is a complete class type or a class currently being
8821 // defined, the set of member candidates is the result of the
8822 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8823 // the set of member candidates is empty.
8824 if (T1->isRecordType()) {
8825 bool IsComplete = isCompleteType(OpLoc, T1);
8826 auto *T1RD = T1->getAsCXXRecordDecl();
8827 // Complete the type if it can be completed.
8828 // If the type is neither complete nor being defined, bail out now.
8829 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8830 return;
8831
8832 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8833 LookupQualifiedName(Operators, T1RD);
8834 Operators.suppressAccessDiagnostics();
8835
8836 for (LookupResult::iterator Oper = Operators.begin(),
8837 OperEnd = Operators.end();
8838 Oper != OperEnd; ++Oper) {
8839 if (Oper->getAsFunction() &&
8841 !CandidateSet.getRewriteInfo().shouldAddReversed(
8842 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8843 continue;
8844 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8845 Args[0]->Classify(Context), Args.slice(1),
8846 CandidateSet, /*SuppressUserConversion=*/false, PO);
8847 }
8848 }
8849}
8850
8852 OverloadCandidateSet& CandidateSet,
8853 bool IsAssignmentOperator,
8854 unsigned NumContextualBoolArguments) {
8855 // Overload resolution is always an unevaluated context.
8858
8859 // Add this candidate
8860 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8861 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8862 Candidate.Function = nullptr;
8863 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8864
8865 // Determine the implicit conversion sequences for each of the
8866 // arguments.
8867 Candidate.Viable = true;
8868 Candidate.ExplicitCallArguments = Args.size();
8869 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8870 // C++ [over.match.oper]p4:
8871 // For the built-in assignment operators, conversions of the
8872 // left operand are restricted as follows:
8873 // -- no temporaries are introduced to hold the left operand, and
8874 // -- no user-defined conversions are applied to the left
8875 // operand to achieve a type match with the left-most
8876 // parameter of a built-in candidate.
8877 //
8878 // We block these conversions by turning off user-defined
8879 // conversions, since that is the only way that initialization of
8880 // a reference to a non-class type can occur from something that
8881 // is not of the same type.
8882 if (ArgIdx < NumContextualBoolArguments) {
8883 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8884 "Contextual conversion to bool requires bool type");
8885 Candidate.Conversions[ArgIdx]
8886 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8887 } else {
8888 Candidate.Conversions[ArgIdx]
8889 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8890 ArgIdx == 0 && IsAssignmentOperator,
8891 /*InOverloadResolution=*/false,
8892 /*AllowObjCWritebackConversion=*/
8893 getLangOpts().ObjCAutoRefCount);
8894 }
8895 if (Candidate.Conversions[ArgIdx].isBad()) {
8896 Candidate.Viable = false;
8898 break;
8899 }
8900 }
8901}
8902
8903namespace {
8904
8905/// BuiltinCandidateTypeSet - A set of types that will be used for the
8906/// candidate operator functions for built-in operators (C++
8907/// [over.built]). The types are separated into pointer types and
8908/// enumeration types.
8909class BuiltinCandidateTypeSet {
8910 /// TypeSet - A set of types.
8911 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8912
8913 /// PointerTypes - The set of pointer types that will be used in the
8914 /// built-in candidates.
8915 TypeSet PointerTypes;
8916
8917 /// MemberPointerTypes - The set of member pointer types that will be
8918 /// used in the built-in candidates.
8919 TypeSet MemberPointerTypes;
8920
8921 /// EnumerationTypes - The set of enumeration types that will be
8922 /// used in the built-in candidates.
8923 TypeSet EnumerationTypes;
8924
8925 /// The set of vector types that will be used in the built-in
8926 /// candidates.
8927 TypeSet VectorTypes;
8928
8929 /// The set of matrix types that will be used in the built-in
8930 /// candidates.
8931 TypeSet MatrixTypes;
8932
8933 /// The set of _BitInt types that will be used in the built-in candidates.
8934 TypeSet BitIntTypes;
8935
8936 /// A flag indicating non-record types are viable candidates
8937 bool HasNonRecordTypes;
8938
8939 /// A flag indicating whether either arithmetic or enumeration types
8940 /// were present in the candidate set.
8941 bool HasArithmeticOrEnumeralTypes;
8942
8943 /// A flag indicating whether the nullptr type was present in the
8944 /// candidate set.
8945 bool HasNullPtrType;
8946
8947 /// Sema - The semantic analysis instance where we are building the
8948 /// candidate type set.
8949 Sema &SemaRef;
8950
8951 /// Context - The AST context in which we will build the type sets.
8952 ASTContext &Context;
8953
8954 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8955 const Qualifiers &VisibleQuals);
8956 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8957
8958public:
8959 /// iterator - Iterates through the types that are part of the set.
8960 typedef TypeSet::iterator iterator;
8961
8962 BuiltinCandidateTypeSet(Sema &SemaRef)
8963 : HasNonRecordTypes(false),
8964 HasArithmeticOrEnumeralTypes(false),
8965 HasNullPtrType(false),
8966 SemaRef(SemaRef),
8967 Context(SemaRef.Context) { }
8968
8969 void AddTypesConvertedFrom(QualType Ty,
8970 SourceLocation Loc,
8971 bool AllowUserConversions,
8972 bool AllowExplicitConversions,
8973 const Qualifiers &VisibleTypeConversionsQuals);
8974
8975 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8976 llvm::iterator_range<iterator> member_pointer_types() {
8977 return MemberPointerTypes;
8978 }
8979 llvm::iterator_range<iterator> enumeration_types() {
8980 return EnumerationTypes;
8981 }
8982 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8983 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8984 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8985
8986 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8987 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8988 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8989 bool hasNullPtrType() const { return HasNullPtrType; }
8990};
8991
8992} // end anonymous namespace
8993
8994/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8995/// the set of pointer types along with any more-qualified variants of
8996/// that type. For example, if @p Ty is "int const *", this routine
8997/// will add "int const *", "int const volatile *", "int const
8998/// restrict *", and "int const volatile restrict *" to the set of
8999/// pointer types. Returns true if the add of @p Ty itself succeeded,
9000/// false otherwise.
9001///
9002/// FIXME: what to do about extended qualifiers?
9003bool
9004BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9005 const Qualifiers &VisibleQuals) {
9006
9007 // Insert this type.
9008 if (!PointerTypes.insert(Ty))
9009 return false;
9010
9011 QualType PointeeTy;
9012 const PointerType *PointerTy = Ty->getAs<PointerType>();
9013 bool buildObjCPtr = false;
9014 if (!PointerTy) {
9015 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9016 PointeeTy = PTy->getPointeeType();
9017 buildObjCPtr = true;
9018 } else {
9019 PointeeTy = PointerTy->getPointeeType();
9020 }
9021
9022 // Don't add qualified variants of arrays. For one, they're not allowed
9023 // (the qualifier would sink to the element type), and for another, the
9024 // only overload situation where it matters is subscript or pointer +- int,
9025 // and those shouldn't have qualifier variants anyway.
9026 if (PointeeTy->isArrayType())
9027 return true;
9028
9029 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9030 bool hasVolatile = VisibleQuals.hasVolatile();
9031 bool hasRestrict = VisibleQuals.hasRestrict();
9032
9033 // Iterate through all strict supersets of BaseCVR.
9034 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9035 if ((CVR | BaseCVR) != CVR) continue;
9036 // Skip over volatile if no volatile found anywhere in the types.
9037 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9038
9039 // Skip over restrict if no restrict found anywhere in the types, or if
9040 // the type cannot be restrict-qualified.
9041 if ((CVR & Qualifiers::Restrict) &&
9042 (!hasRestrict ||
9043 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9044 continue;
9045
9046 // Build qualified pointee type.
9047 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9048
9049 // Build qualified pointer type.
9050 QualType QPointerTy;
9051 if (!buildObjCPtr)
9052 QPointerTy = Context.getPointerType(QPointeeTy);
9053 else
9054 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9055
9056 // Insert qualified pointer type.
9057 PointerTypes.insert(QPointerTy);
9058 }
9059
9060 return true;
9061}
9062
9063/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9064/// to the set of pointer types along with any more-qualified variants of
9065/// that type. For example, if @p Ty is "int const *", this routine
9066/// will add "int const *", "int const volatile *", "int const
9067/// restrict *", and "int const volatile restrict *" to the set of
9068/// pointer types. Returns true if the add of @p Ty itself succeeded,
9069/// false otherwise.
9070///
9071/// FIXME: what to do about extended qualifiers?
9072bool
9073BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9074 QualType Ty) {
9075 // Insert this type.
9076 if (!MemberPointerTypes.insert(Ty))
9077 return false;
9078
9079 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9080 assert(PointerTy && "type was not a member pointer type!");
9081
9082 QualType PointeeTy = PointerTy->getPointeeType();
9083 // Don't add qualified variants of arrays. For one, they're not allowed
9084 // (the qualifier would sink to the element type), and for another, the
9085 // only overload situation where it matters is subscript or pointer +- int,
9086 // and those shouldn't have qualifier variants anyway.
9087 if (PointeeTy->isArrayType())
9088 return true;
9089 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9090
9091 // Iterate through all strict supersets of the pointee type's CVR
9092 // qualifiers.
9093 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9094 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9095 if ((CVR | BaseCVR) != CVR) continue;
9096
9097 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9098 MemberPointerTypes.insert(Context.getMemberPointerType(
9099 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9100 }
9101
9102 return true;
9103}
9104
9105/// AddTypesConvertedFrom - Add each of the types to which the type @p
9106/// Ty can be implicit converted to the given set of @p Types. We're
9107/// primarily interested in pointer types and enumeration types. We also
9108/// take member pointer types, for the conditional operator.
9109/// AllowUserConversions is true if we should look at the conversion
9110/// functions of a class type, and AllowExplicitConversions if we
9111/// should also include the explicit conversion functions of a class
9112/// type.
9113void
9114BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9115 SourceLocation Loc,
9116 bool AllowUserConversions,
9117 bool AllowExplicitConversions,
9118 const Qualifiers &VisibleQuals) {
9119 // Only deal with canonical types.
9120 Ty = Context.getCanonicalType(Ty);
9121
9122 // Look through reference types; they aren't part of the type of an
9123 // expression for the purposes of conversions.
9124 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9125 Ty = RefTy->getPointeeType();
9126
9127 // If we're dealing with an array type, decay to the pointer.
9128 if (Ty->isArrayType())
9129 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9130
9131 // Otherwise, we don't care about qualifiers on the type.
9132 Ty = Ty.getLocalUnqualifiedType();
9133
9134 // Flag if we ever add a non-record type.
9135 bool TyIsRec = Ty->isRecordType();
9136 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9137
9138 // Flag if we encounter an arithmetic type.
9139 HasArithmeticOrEnumeralTypes =
9140 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9141
9142 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9143 PointerTypes.insert(Ty);
9144 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9145 // Insert our type, and its more-qualified variants, into the set
9146 // of types.
9147 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9148 return;
9149 } else if (Ty->isMemberPointerType()) {
9150 // Member pointers are far easier, since the pointee can't be converted.
9151 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9152 return;
9153 } else if (Ty->isEnumeralType()) {
9154 HasArithmeticOrEnumeralTypes = true;
9155 EnumerationTypes.insert(Ty);
9156 } else if (Ty->isBitIntType()) {
9157 HasArithmeticOrEnumeralTypes = true;
9158 BitIntTypes.insert(Ty);
9159 } else if (Ty->isVectorType()) {
9160 // We treat vector types as arithmetic types in many contexts as an
9161 // extension.
9162 HasArithmeticOrEnumeralTypes = true;
9163 VectorTypes.insert(Ty);
9164 } else if (Ty->isMatrixType()) {
9165 // Similar to vector types, we treat vector types as arithmetic types in
9166 // many contexts as an extension.
9167 HasArithmeticOrEnumeralTypes = true;
9168 MatrixTypes.insert(Ty);
9169 } else if (Ty->isNullPtrType()) {
9170 HasNullPtrType = true;
9171 } else if (AllowUserConversions && TyIsRec) {
9172 // No conversion functions in incomplete types.
9173 if (!SemaRef.isCompleteType(Loc, Ty))
9174 return;
9175
9176 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9177 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9178 if (isa<UsingShadowDecl>(D))
9179 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9180
9181 // Skip conversion function templates; they don't tell us anything
9182 // about which builtin types we can convert to.
9184 continue;
9185
9186 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9187 if (AllowExplicitConversions || !Conv->isExplicit()) {
9188 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9189 VisibleQuals);
9190 }
9191 }
9192 }
9193}
9194/// Helper function for adjusting address spaces for the pointer or reference
9195/// operands of builtin operators depending on the argument.
9200
9201/// Helper function for AddBuiltinOperatorCandidates() that adds
9202/// the volatile- and non-volatile-qualified assignment operators for the
9203/// given type to the candidate set.
9205 QualType T,
9206 ArrayRef<Expr *> Args,
9207 OverloadCandidateSet &CandidateSet) {
9208 QualType ParamTypes[2];
9209
9210 // T& operator=(T&, T)
9211 ParamTypes[0] = S.Context.getLValueReferenceType(
9213 ParamTypes[1] = T;
9214 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9215 /*IsAssignmentOperator=*/true);
9216
9218 // volatile T& operator=(volatile T&, T)
9219 ParamTypes[0] = S.Context.getLValueReferenceType(
9221 Args[0]));
9222 ParamTypes[1] = T;
9223 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9224 /*IsAssignmentOperator=*/true);
9225 }
9226}
9227
9228/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9229/// if any, found in visible type conversion functions found in ArgExpr's type.
9230static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9231 Qualifiers VRQuals;
9232 CXXRecordDecl *ClassDecl;
9233 if (const MemberPointerType *RHSMPType =
9234 ArgExpr->getType()->getAs<MemberPointerType>())
9235 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9236 else
9237 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9238 if (!ClassDecl) {
9239 // Just to be safe, assume the worst case.
9240 VRQuals.addVolatile();
9241 VRQuals.addRestrict();
9242 return VRQuals;
9243 }
9244 if (!ClassDecl->hasDefinition())
9245 return VRQuals;
9246
9247 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9248 if (isa<UsingShadowDecl>(D))
9249 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9250 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9251 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9252 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9253 CanTy = ResTypeRef->getPointeeType();
9254 // Need to go down the pointer/mempointer chain and add qualifiers
9255 // as see them.
9256 bool done = false;
9257 while (!done) {
9258 if (CanTy.isRestrictQualified())
9259 VRQuals.addRestrict();
9260 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9261 CanTy = ResTypePtr->getPointeeType();
9262 else if (const MemberPointerType *ResTypeMPtr =
9263 CanTy->getAs<MemberPointerType>())
9264 CanTy = ResTypeMPtr->getPointeeType();
9265 else
9266 done = true;
9267 if (CanTy.isVolatileQualified())
9268 VRQuals.addVolatile();
9269 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9270 return VRQuals;
9271 }
9272 }
9273 }
9274 return VRQuals;
9275}
9276
9277// Note: We're currently only handling qualifiers that are meaningful for the
9278// LHS of compound assignment overloading.
9280 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9281 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9282 // _Atomic
9283 if (Available.hasAtomic()) {
9284 Available.removeAtomic();
9285 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9286 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9287 return;
9288 }
9289
9290 // volatile
9291 if (Available.hasVolatile()) {
9292 Available.removeVolatile();
9293 assert(!Applied.hasVolatile());
9294 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9295 Callback);
9296 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9297 return;
9298 }
9299
9300 Callback(Applied);
9301}
9302
9304 QualifiersAndAtomic Quals,
9305 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9307 Callback);
9308}
9309
9311 QualifiersAndAtomic Quals,
9312 Sema &S) {
9313 if (Quals.hasAtomic())
9315 if (Quals.hasVolatile())
9318}
9319
9320namespace {
9321
9322/// Helper class to manage the addition of builtin operator overload
9323/// candidates. It provides shared state and utility methods used throughout
9324/// the process, as well as a helper method to add each group of builtin
9325/// operator overloads from the standard to a candidate set.
9326class BuiltinOperatorOverloadBuilder {
9327 // Common instance state available to all overload candidate addition methods.
9328 Sema &S;
9329 ArrayRef<Expr *> Args;
9330 QualifiersAndAtomic VisibleTypeConversionsQuals;
9331 bool HasArithmeticOrEnumeralCandidateType;
9332 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9333 OverloadCandidateSet &CandidateSet;
9334
9335 static constexpr int ArithmeticTypesCap = 26;
9336 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9337
9338 // Define some indices used to iterate over the arithmetic types in
9339 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9340 // types are that preserved by promotion (C++ [over.built]p2).
9341 unsigned FirstIntegralType,
9342 LastIntegralType;
9343 unsigned FirstPromotedIntegralType,
9344 LastPromotedIntegralType;
9345 unsigned FirstPromotedArithmeticType,
9346 LastPromotedArithmeticType;
9347 unsigned NumArithmeticTypes;
9348
9349 void InitArithmeticTypes() {
9350 // Start of promoted types.
9351 FirstPromotedArithmeticType = 0;
9352 ArithmeticTypes.push_back(S.Context.FloatTy);
9353 ArithmeticTypes.push_back(S.Context.DoubleTy);
9354 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9356 ArithmeticTypes.push_back(S.Context.Float128Ty);
9358 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9359
9360 // Start of integral types.
9361 FirstIntegralType = ArithmeticTypes.size();
9362 FirstPromotedIntegralType = ArithmeticTypes.size();
9363 ArithmeticTypes.push_back(S.Context.IntTy);
9364 ArithmeticTypes.push_back(S.Context.LongTy);
9365 ArithmeticTypes.push_back(S.Context.LongLongTy);
9369 ArithmeticTypes.push_back(S.Context.Int128Ty);
9370 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9371 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9372 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9376 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9377
9378 /// We add candidates for the unique, unqualified _BitInt types present in
9379 /// the candidate type set. The candidate set already handled ensuring the
9380 /// type is unqualified and canonical, but because we're adding from N
9381 /// different sets, we need to do some extra work to unique things. Insert
9382 /// the candidates into a unique set, then move from that set into the list
9383 /// of arithmetic types.
9384 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9385 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9386 for (QualType BitTy : Candidate.bitint_types())
9387 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9388 }
9389 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9390 LastPromotedIntegralType = ArithmeticTypes.size();
9391 LastPromotedArithmeticType = ArithmeticTypes.size();
9392 // End of promoted types.
9393
9394 ArithmeticTypes.push_back(S.Context.BoolTy);
9395 ArithmeticTypes.push_back(S.Context.CharTy);
9396 ArithmeticTypes.push_back(S.Context.WCharTy);
9397 if (S.Context.getLangOpts().Char8)
9398 ArithmeticTypes.push_back(S.Context.Char8Ty);
9399 ArithmeticTypes.push_back(S.Context.Char16Ty);
9400 ArithmeticTypes.push_back(S.Context.Char32Ty);
9401 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9402 ArithmeticTypes.push_back(S.Context.ShortTy);
9403 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9404 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9405 LastIntegralType = ArithmeticTypes.size();
9406 NumArithmeticTypes = ArithmeticTypes.size();
9407 // End of integral types.
9408 // FIXME: What about complex? What about half?
9409
9410 // We don't know for sure how many bit-precise candidates were involved, so
9411 // we subtract those from the total when testing whether we're under the
9412 // cap or not.
9413 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9414 ArithmeticTypesCap &&
9415 "Enough inline storage for all arithmetic types.");
9416 }
9417
9418 /// Helper method to factor out the common pattern of adding overloads
9419 /// for '++' and '--' builtin operators.
9420 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9421 bool HasVolatile,
9422 bool HasRestrict) {
9423 QualType ParamTypes[2] = {
9424 S.Context.getLValueReferenceType(CandidateTy),
9425 S.Context.IntTy
9426 };
9427
9428 // Non-volatile version.
9429 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9430
9431 // Use a heuristic to reduce number of builtin candidates in the set:
9432 // add volatile version only if there are conversions to a volatile type.
9433 if (HasVolatile) {
9434 ParamTypes[0] =
9436 S.Context.getVolatileType(CandidateTy));
9437 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9438 }
9439
9440 // Add restrict version only if there are conversions to a restrict type
9441 // and our candidate type is a non-restrict-qualified pointer.
9442 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9443 !CandidateTy.isRestrictQualified()) {
9444 ParamTypes[0]
9447 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9448
9449 if (HasVolatile) {
9450 ParamTypes[0]
9452 S.Context.getCVRQualifiedType(CandidateTy,
9455 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9456 }
9457 }
9458
9459 }
9460
9461 /// Helper to add an overload candidate for a binary builtin with types \p L
9462 /// and \p R.
9463 void AddCandidate(QualType L, QualType R) {
9464 QualType LandR[2] = {L, R};
9465 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9466 }
9467
9468public:
9469 BuiltinOperatorOverloadBuilder(
9470 Sema &S, ArrayRef<Expr *> Args,
9471 QualifiersAndAtomic VisibleTypeConversionsQuals,
9472 bool HasArithmeticOrEnumeralCandidateType,
9473 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9474 OverloadCandidateSet &CandidateSet)
9475 : S(S), Args(Args),
9476 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9477 HasArithmeticOrEnumeralCandidateType(
9478 HasArithmeticOrEnumeralCandidateType),
9479 CandidateTypes(CandidateTypes),
9480 CandidateSet(CandidateSet) {
9481
9482 InitArithmeticTypes();
9483 }
9484
9485 // Increment is deprecated for bool since C++17.
9486 //
9487 // C++ [over.built]p3:
9488 //
9489 // For every pair (T, VQ), where T is an arithmetic type other
9490 // than bool, and VQ is either volatile or empty, there exist
9491 // candidate operator functions of the form
9492 //
9493 // VQ T& operator++(VQ T&);
9494 // T operator++(VQ T&, int);
9495 //
9496 // C++ [over.built]p4:
9497 //
9498 // For every pair (T, VQ), where T is an arithmetic type other
9499 // than bool, and VQ is either volatile or empty, there exist
9500 // candidate operator functions of the form
9501 //
9502 // VQ T& operator--(VQ T&);
9503 // T operator--(VQ T&, int);
9504 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9505 if (!HasArithmeticOrEnumeralCandidateType)
9506 return;
9507
9508 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9509 const auto TypeOfT = ArithmeticTypes[Arith];
9510 if (TypeOfT == S.Context.BoolTy) {
9511 if (Op == OO_MinusMinus)
9512 continue;
9513 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9514 continue;
9515 }
9516 addPlusPlusMinusMinusStyleOverloads(
9517 TypeOfT,
9518 VisibleTypeConversionsQuals.hasVolatile(),
9519 VisibleTypeConversionsQuals.hasRestrict());
9520 }
9521 }
9522
9523 // C++ [over.built]p5:
9524 //
9525 // For every pair (T, VQ), where T is a cv-qualified or
9526 // cv-unqualified object type, and VQ is either volatile or
9527 // empty, there exist candidate operator functions of the form
9528 //
9529 // T*VQ& operator++(T*VQ&);
9530 // T*VQ& operator--(T*VQ&);
9531 // T* operator++(T*VQ&, int);
9532 // T* operator--(T*VQ&, int);
9533 void addPlusPlusMinusMinusPointerOverloads() {
9534 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9535 // Skip pointer types that aren't pointers to object types.
9536 if (!PtrTy->getPointeeType()->isObjectType())
9537 continue;
9538
9539 addPlusPlusMinusMinusStyleOverloads(
9540 PtrTy,
9541 (!PtrTy.isVolatileQualified() &&
9542 VisibleTypeConversionsQuals.hasVolatile()),
9543 (!PtrTy.isRestrictQualified() &&
9544 VisibleTypeConversionsQuals.hasRestrict()));
9545 }
9546 }
9547
9548 // C++ [over.built]p6:
9549 // For every cv-qualified or cv-unqualified object type T, there
9550 // exist candidate operator functions of the form
9551 //
9552 // T& operator*(T*);
9553 //
9554 // C++ [over.built]p7:
9555 // For every function type T that does not have cv-qualifiers or a
9556 // ref-qualifier, there exist candidate operator functions of the form
9557 // T& operator*(T*);
9558 void addUnaryStarPointerOverloads() {
9559 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9560 QualType PointeeTy = ParamTy->getPointeeType();
9561 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9562 continue;
9563
9564 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9565 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9566 continue;
9567
9568 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9569 }
9570 }
9571
9572 // C++ [over.built]p9:
9573 // For every promoted arithmetic type T, there exist candidate
9574 // operator functions of the form
9575 //
9576 // T operator+(T);
9577 // T operator-(T);
9578 void addUnaryPlusOrMinusArithmeticOverloads() {
9579 if (!HasArithmeticOrEnumeralCandidateType)
9580 return;
9581
9582 for (unsigned Arith = FirstPromotedArithmeticType;
9583 Arith < LastPromotedArithmeticType; ++Arith) {
9584 QualType ArithTy = ArithmeticTypes[Arith];
9585 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9586 }
9587
9588 // Extension: We also add these operators for vector types.
9589 for (QualType VecTy : CandidateTypes[0].vector_types())
9590 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9591 }
9592
9593 // C++ [over.built]p8:
9594 // For every type T, there exist candidate operator functions of
9595 // the form
9596 //
9597 // T* operator+(T*);
9598 void addUnaryPlusPointerOverloads() {
9599 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9600 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9601 }
9602
9603 // C++ [over.built]p10:
9604 // For every promoted integral type T, there exist candidate
9605 // operator functions of the form
9606 //
9607 // T operator~(T);
9608 void addUnaryTildePromotedIntegralOverloads() {
9609 if (!HasArithmeticOrEnumeralCandidateType)
9610 return;
9611
9612 for (unsigned Int = FirstPromotedIntegralType;
9613 Int < LastPromotedIntegralType; ++Int) {
9614 QualType IntTy = ArithmeticTypes[Int];
9615 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9616 }
9617
9618 // Extension: We also add this operator for vector types.
9619 for (QualType VecTy : CandidateTypes[0].vector_types())
9620 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9621 }
9622
9623 // C++ [over.match.oper]p16:
9624 // For every pointer to member type T or type std::nullptr_t, there
9625 // exist candidate operator functions of the form
9626 //
9627 // bool operator==(T,T);
9628 // bool operator!=(T,T);
9629 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9630 /// Set of (canonical) types that we've already handled.
9631 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9632
9633 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9634 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9635 // Don't add the same builtin candidate twice.
9636 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9637 continue;
9638
9639 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9641 }
9642
9643 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9645 if (AddedTypes.insert(NullPtrTy).second) {
9646 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9647 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9648 }
9649 }
9650 }
9651 }
9652
9653 // C++ [over.built]p15:
9654 //
9655 // For every T, where T is an enumeration type or a pointer type,
9656 // there exist candidate operator functions of the form
9657 //
9658 // bool operator<(T, T);
9659 // bool operator>(T, T);
9660 // bool operator<=(T, T);
9661 // bool operator>=(T, T);
9662 // bool operator==(T, T);
9663 // bool operator!=(T, T);
9664 // R operator<=>(T, T)
9665 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9666 // C++ [over.match.oper]p3:
9667 // [...]the built-in candidates include all of the candidate operator
9668 // functions defined in 13.6 that, compared to the given operator, [...]
9669 // do not have the same parameter-type-list as any non-template non-member
9670 // candidate.
9671 //
9672 // Note that in practice, this only affects enumeration types because there
9673 // aren't any built-in candidates of record type, and a user-defined operator
9674 // must have an operand of record or enumeration type. Also, the only other
9675 // overloaded operator with enumeration arguments, operator=,
9676 // cannot be overloaded for enumeration types, so this is the only place
9677 // where we must suppress candidates like this.
9678 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9679 UserDefinedBinaryOperators;
9680
9681 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9682 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9683 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9684 CEnd = CandidateSet.end();
9685 C != CEnd; ++C) {
9686 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9687 continue;
9688
9689 if (C->Function->isFunctionTemplateSpecialization())
9690 continue;
9691
9692 // We interpret "same parameter-type-list" as applying to the
9693 // "synthesized candidate, with the order of the two parameters
9694 // reversed", not to the original function.
9695 bool Reversed = C->isReversed();
9696 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9697 ->getType()
9698 .getUnqualifiedType();
9699 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9700 ->getType()
9701 .getUnqualifiedType();
9702
9703 // Skip if either parameter isn't of enumeral type.
9704 if (!FirstParamType->isEnumeralType() ||
9705 !SecondParamType->isEnumeralType())
9706 continue;
9707
9708 // Add this operator to the set of known user-defined operators.
9709 UserDefinedBinaryOperators.insert(
9710 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9711 S.Context.getCanonicalType(SecondParamType)));
9712 }
9713 }
9714 }
9715
9716 /// Set of (canonical) types that we've already handled.
9717 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9718
9719 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9720 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9721 // Don't add the same builtin candidate twice.
9722 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9723 continue;
9724 if (IsSpaceship && PtrTy->isFunctionPointerType())
9725 continue;
9726
9727 QualType ParamTypes[2] = {PtrTy, PtrTy};
9728 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9729 }
9730 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9731 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9732
9733 // Don't add the same builtin candidate twice, or if a user defined
9734 // candidate exists.
9735 if (!AddedTypes.insert(CanonType).second ||
9736 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9737 CanonType)))
9738 continue;
9739 QualType ParamTypes[2] = {EnumTy, EnumTy};
9740 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9741 }
9742 }
9743 }
9744
9745 // C++ [over.built]p13:
9746 //
9747 // For every cv-qualified or cv-unqualified object type T
9748 // there exist candidate operator functions of the form
9749 //
9750 // T* operator+(T*, ptrdiff_t);
9751 // T& operator[](T*, ptrdiff_t); [BELOW]
9752 // T* operator-(T*, ptrdiff_t);
9753 // T* operator+(ptrdiff_t, T*);
9754 // T& operator[](ptrdiff_t, T*); [BELOW]
9755 //
9756 // C++ [over.built]p14:
9757 //
9758 // For every T, where T is a pointer to object type, there
9759 // exist candidate operator functions of the form
9760 //
9761 // ptrdiff_t operator-(T, T);
9762 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9763 /// Set of (canonical) types that we've already handled.
9764 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9765
9766 for (int Arg = 0; Arg < 2; ++Arg) {
9767 QualType AsymmetricParamTypes[2] = {
9770 };
9771 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9772 QualType PointeeTy = PtrTy->getPointeeType();
9773 if (!PointeeTy->isObjectType())
9774 continue;
9775
9776 AsymmetricParamTypes[Arg] = PtrTy;
9777 if (Arg == 0 || Op == OO_Plus) {
9778 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9779 // T* operator+(ptrdiff_t, T*);
9780 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9781 }
9782 if (Op == OO_Minus) {
9783 // ptrdiff_t operator-(T, T);
9784 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9785 continue;
9786
9787 QualType ParamTypes[2] = {PtrTy, PtrTy};
9788 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9789 }
9790 }
9791 }
9792 }
9793
9794 // C++ [over.built]p12:
9795 //
9796 // For every pair of promoted arithmetic types L and R, there
9797 // exist candidate operator functions of the form
9798 //
9799 // LR operator*(L, R);
9800 // LR operator/(L, R);
9801 // LR operator+(L, R);
9802 // LR operator-(L, R);
9803 // bool operator<(L, R);
9804 // bool operator>(L, R);
9805 // bool operator<=(L, R);
9806 // bool operator>=(L, R);
9807 // bool operator==(L, R);
9808 // bool operator!=(L, R);
9809 //
9810 // where LR is the result of the usual arithmetic conversions
9811 // between types L and R.
9812 //
9813 // C++ [over.built]p24:
9814 //
9815 // For every pair of promoted arithmetic types L and R, there exist
9816 // candidate operator functions of the form
9817 //
9818 // LR operator?(bool, L, R);
9819 //
9820 // where LR is the result of the usual arithmetic conversions
9821 // between types L and R.
9822 // Our candidates ignore the first parameter.
9823 void addGenericBinaryArithmeticOverloads() {
9824 if (!HasArithmeticOrEnumeralCandidateType)
9825 return;
9826
9827 for (unsigned Left = FirstPromotedArithmeticType;
9828 Left < LastPromotedArithmeticType; ++Left) {
9829 for (unsigned Right = FirstPromotedArithmeticType;
9830 Right < LastPromotedArithmeticType; ++Right) {
9831 QualType LandR[2] = { ArithmeticTypes[Left],
9832 ArithmeticTypes[Right] };
9833 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9834 }
9835 }
9836
9837 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9838 // conditional operator for vector types.
9839 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9840 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9841 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9842 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9843 }
9844 }
9845
9846 /// Add binary operator overloads for each candidate matrix type M1, M2:
9847 /// * (M1, M1) -> M1
9848 /// * (M1, M1.getElementType()) -> M1
9849 /// * (M2.getElementType(), M2) -> M2
9850 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9851 void addMatrixBinaryArithmeticOverloads() {
9852 if (!HasArithmeticOrEnumeralCandidateType)
9853 return;
9854
9855 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9856 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9857 AddCandidate(M1, M1);
9858 }
9859
9860 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9861 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9862 if (!CandidateTypes[0].containsMatrixType(M2))
9863 AddCandidate(M2, M2);
9864 }
9865 }
9866
9867 // C++2a [over.built]p14:
9868 //
9869 // For every integral type T there exists a candidate operator function
9870 // of the form
9871 //
9872 // std::strong_ordering operator<=>(T, T)
9873 //
9874 // C++2a [over.built]p15:
9875 //
9876 // For every pair of floating-point types L and R, there exists a candidate
9877 // operator function of the form
9878 //
9879 // std::partial_ordering operator<=>(L, R);
9880 //
9881 // FIXME: The current specification for integral types doesn't play nice with
9882 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9883 // comparisons. Under the current spec this can lead to ambiguity during
9884 // overload resolution. For example:
9885 //
9886 // enum A : int {a};
9887 // auto x = (a <=> (long)42);
9888 //
9889 // error: call is ambiguous for arguments 'A' and 'long'.
9890 // note: candidate operator<=>(int, int)
9891 // note: candidate operator<=>(long, long)
9892 //
9893 // To avoid this error, this function deviates from the specification and adds
9894 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9895 // arithmetic types (the same as the generic relational overloads).
9896 //
9897 // For now this function acts as a placeholder.
9898 void addThreeWayArithmeticOverloads() {
9899 addGenericBinaryArithmeticOverloads();
9900 }
9901
9902 // C++ [over.built]p17:
9903 //
9904 // For every pair of promoted integral types L and R, there
9905 // exist candidate operator functions of the form
9906 //
9907 // LR operator%(L, R);
9908 // LR operator&(L, R);
9909 // LR operator^(L, R);
9910 // LR operator|(L, R);
9911 // L operator<<(L, R);
9912 // L operator>>(L, R);
9913 //
9914 // where LR is the result of the usual arithmetic conversions
9915 // between types L and R.
9916 void addBinaryBitwiseArithmeticOverloads() {
9917 if (!HasArithmeticOrEnumeralCandidateType)
9918 return;
9919
9920 for (unsigned Left = FirstPromotedIntegralType;
9921 Left < LastPromotedIntegralType; ++Left) {
9922 for (unsigned Right = FirstPromotedIntegralType;
9923 Right < LastPromotedIntegralType; ++Right) {
9924 QualType LandR[2] = { ArithmeticTypes[Left],
9925 ArithmeticTypes[Right] };
9926 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9927 }
9928 }
9929 }
9930
9931 // C++ [over.built]p20:
9932 //
9933 // For every pair (T, VQ), where T is an enumeration or
9934 // pointer to member type and VQ is either volatile or
9935 // empty, there exist candidate operator functions of the form
9936 //
9937 // VQ T& operator=(VQ T&, T);
9938 void addAssignmentMemberPointerOrEnumeralOverloads() {
9939 /// Set of (canonical) types that we've already handled.
9940 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9941
9942 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9943 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9944 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9945 continue;
9946
9947 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9948 }
9949
9950 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9951 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9952 continue;
9953
9954 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9955 }
9956 }
9957 }
9958
9959 // C++ [over.built]p19:
9960 //
9961 // For every pair (T, VQ), where T is any type and VQ is either
9962 // volatile or empty, there exist candidate operator functions
9963 // of the form
9964 //
9965 // T*VQ& operator=(T*VQ&, T*);
9966 //
9967 // C++ [over.built]p21:
9968 //
9969 // For every pair (T, VQ), where T is a cv-qualified or
9970 // cv-unqualified object type and VQ is either volatile or
9971 // empty, there exist candidate operator functions of the form
9972 //
9973 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9974 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9975 void addAssignmentPointerOverloads(bool isEqualOp) {
9976 /// Set of (canonical) types that we've already handled.
9977 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9978
9979 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9980 // If this is operator=, keep track of the builtin candidates we added.
9981 if (isEqualOp)
9982 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9983 else if (!PtrTy->getPointeeType()->isObjectType())
9984 continue;
9985
9986 // non-volatile version
9987 QualType ParamTypes[2] = {
9989 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9990 };
9991 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9992 /*IsAssignmentOperator=*/ isEqualOp);
9993
9994 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9995 VisibleTypeConversionsQuals.hasVolatile();
9996 if (NeedVolatile) {
9997 // volatile version
9998 ParamTypes[0] =
10000 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10001 /*IsAssignmentOperator=*/isEqualOp);
10002 }
10003
10004 if (!PtrTy.isRestrictQualified() &&
10005 VisibleTypeConversionsQuals.hasRestrict()) {
10006 // restrict version
10007 ParamTypes[0] =
10009 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10010 /*IsAssignmentOperator=*/isEqualOp);
10011
10012 if (NeedVolatile) {
10013 // volatile restrict version
10014 ParamTypes[0] =
10017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10018 /*IsAssignmentOperator=*/isEqualOp);
10019 }
10020 }
10021 }
10022
10023 if (isEqualOp) {
10024 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10025 // Make sure we don't add the same candidate twice.
10026 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10027 continue;
10028
10029 QualType ParamTypes[2] = {
10031 PtrTy,
10032 };
10033
10034 // non-volatile version
10035 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10036 /*IsAssignmentOperator=*/true);
10037
10038 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10039 VisibleTypeConversionsQuals.hasVolatile();
10040 if (NeedVolatile) {
10041 // volatile version
10042 ParamTypes[0] = S.Context.getLValueReferenceType(
10043 S.Context.getVolatileType(PtrTy));
10044 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10045 /*IsAssignmentOperator=*/true);
10046 }
10047
10048 if (!PtrTy.isRestrictQualified() &&
10049 VisibleTypeConversionsQuals.hasRestrict()) {
10050 // restrict version
10051 ParamTypes[0] = S.Context.getLValueReferenceType(
10052 S.Context.getRestrictType(PtrTy));
10053 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10054 /*IsAssignmentOperator=*/true);
10055
10056 if (NeedVolatile) {
10057 // volatile restrict version
10058 ParamTypes[0] =
10061 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10062 /*IsAssignmentOperator=*/true);
10063 }
10064 }
10065 }
10066 }
10067 }
10068
10069 // C++ [over.built]p18:
10070 //
10071 // For every triple (L, VQ, R), where L is an arithmetic type,
10072 // VQ is either volatile or empty, and R is a promoted
10073 // arithmetic type, there exist candidate operator functions of
10074 // the form
10075 //
10076 // VQ L& operator=(VQ L&, R);
10077 // VQ L& operator*=(VQ L&, R);
10078 // VQ L& operator/=(VQ L&, R);
10079 // VQ L& operator+=(VQ L&, R);
10080 // VQ L& operator-=(VQ L&, R);
10081 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10082 if (!HasArithmeticOrEnumeralCandidateType)
10083 return;
10084
10085 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10086 for (unsigned Right = FirstPromotedArithmeticType;
10087 Right < LastPromotedArithmeticType; ++Right) {
10088 QualType ParamTypes[2];
10089 ParamTypes[1] = ArithmeticTypes[Right];
10091 S, ArithmeticTypes[Left], Args[0]);
10092
10094 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10095 ParamTypes[0] =
10096 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10097 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10098 /*IsAssignmentOperator=*/isEqualOp);
10099 });
10100 }
10101 }
10102
10103 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10104 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10105 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10106 QualType ParamTypes[2];
10107 ParamTypes[1] = Vec2Ty;
10108 // Add this built-in operator as a candidate (VQ is empty).
10109 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10110 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10111 /*IsAssignmentOperator=*/isEqualOp);
10112
10113 // Add this built-in operator as a candidate (VQ is 'volatile').
10114 if (VisibleTypeConversionsQuals.hasVolatile()) {
10115 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10116 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10117 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10118 /*IsAssignmentOperator=*/isEqualOp);
10119 }
10120 }
10121 }
10122
10123 // C++ [over.built]p22:
10124 //
10125 // For every triple (L, VQ, R), where L is an integral type, VQ
10126 // is either volatile or empty, and R is a promoted integral
10127 // type, there exist candidate operator functions of the form
10128 //
10129 // VQ L& operator%=(VQ L&, R);
10130 // VQ L& operator<<=(VQ L&, R);
10131 // VQ L& operator>>=(VQ L&, R);
10132 // VQ L& operator&=(VQ L&, R);
10133 // VQ L& operator^=(VQ L&, R);
10134 // VQ L& operator|=(VQ L&, R);
10135 void addAssignmentIntegralOverloads() {
10136 if (!HasArithmeticOrEnumeralCandidateType)
10137 return;
10138
10139 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10140 for (unsigned Right = FirstPromotedIntegralType;
10141 Right < LastPromotedIntegralType; ++Right) {
10142 QualType ParamTypes[2];
10143 ParamTypes[1] = ArithmeticTypes[Right];
10145 S, ArithmeticTypes[Left], Args[0]);
10146
10148 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10149 ParamTypes[0] =
10150 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10151 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10152 });
10153 }
10154 }
10155 }
10156
10157 // C++ [over.operator]p23:
10158 //
10159 // There also exist candidate operator functions of the form
10160 //
10161 // bool operator!(bool);
10162 // bool operator&&(bool, bool);
10163 // bool operator||(bool, bool);
10164 void addExclaimOverload() {
10165 QualType ParamTy = S.Context.BoolTy;
10166 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10167 /*IsAssignmentOperator=*/false,
10168 /*NumContextualBoolArguments=*/1);
10169 }
10170 void addAmpAmpOrPipePipeOverload() {
10171 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10172 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10173 /*IsAssignmentOperator=*/false,
10174 /*NumContextualBoolArguments=*/2);
10175 }
10176
10177 // C++ [over.built]p13:
10178 //
10179 // For every cv-qualified or cv-unqualified object type T there
10180 // exist candidate operator functions of the form
10181 //
10182 // T* operator+(T*, ptrdiff_t); [ABOVE]
10183 // T& operator[](T*, ptrdiff_t);
10184 // T* operator-(T*, ptrdiff_t); [ABOVE]
10185 // T* operator+(ptrdiff_t, T*); [ABOVE]
10186 // T& operator[](ptrdiff_t, T*);
10187 void addSubscriptOverloads() {
10188 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10189 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10190 QualType PointeeType = PtrTy->getPointeeType();
10191 if (!PointeeType->isObjectType())
10192 continue;
10193
10194 // T& operator[](T*, ptrdiff_t)
10195 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10196 }
10197
10198 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10199 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10200 QualType PointeeType = PtrTy->getPointeeType();
10201 if (!PointeeType->isObjectType())
10202 continue;
10203
10204 // T& operator[](ptrdiff_t, T*)
10205 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10206 }
10207 }
10208
10209 // C++ [over.built]p11:
10210 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10211 // C1 is the same type as C2 or is a derived class of C2, T is an object
10212 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10213 // there exist candidate operator functions of the form
10214 //
10215 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10216 //
10217 // where CV12 is the union of CV1 and CV2.
10218 void addArrowStarOverloads() {
10219 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10220 QualType C1Ty = PtrTy;
10221 QualType C1;
10222 QualifierCollector Q1;
10223 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10224 if (!isa<RecordType>(C1))
10225 continue;
10226 // heuristic to reduce number of builtin candidates in the set.
10227 // Add volatile/restrict version only if there are conversions to a
10228 // volatile/restrict type.
10229 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10230 continue;
10231 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10232 continue;
10233 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10234 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10235 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10236 *D2 = mptr->getMostRecentCXXRecordDecl();
10237 if (!declaresSameEntity(D1, D2) &&
10238 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10239 break;
10240 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10241 // build CV12 T&
10242 QualType T = mptr->getPointeeType();
10243 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10244 T.isVolatileQualified())
10245 continue;
10246 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10247 T.isRestrictQualified())
10248 continue;
10249 T = Q1.apply(S.Context, T);
10250 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10251 }
10252 }
10253 }
10254
10255 // Note that we don't consider the first argument, since it has been
10256 // contextually converted to bool long ago. The candidates below are
10257 // therefore added as binary.
10258 //
10259 // C++ [over.built]p25:
10260 // For every type T, where T is a pointer, pointer-to-member, or scoped
10261 // enumeration type, there exist candidate operator functions of the form
10262 //
10263 // T operator?(bool, T, T);
10264 //
10265 void addConditionalOperatorOverloads() {
10266 /// Set of (canonical) types that we've already handled.
10267 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10268
10269 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10270 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10271 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10272 continue;
10273
10274 QualType ParamTypes[2] = {PtrTy, PtrTy};
10275 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10276 }
10277
10278 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10279 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10280 continue;
10281
10282 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10283 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10284 }
10285
10286 if (S.getLangOpts().CPlusPlus11) {
10287 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10288 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10289 continue;
10290
10291 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10292 continue;
10293
10294 QualType ParamTypes[2] = {EnumTy, EnumTy};
10295 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10296 }
10297 }
10298 }
10299 }
10300};
10301
10302} // end anonymous namespace
10303
10305 SourceLocation OpLoc,
10306 ArrayRef<Expr *> Args,
10307 OverloadCandidateSet &CandidateSet) {
10308 // Find all of the types that the arguments can convert to, but only
10309 // if the operator we're looking at has built-in operator candidates
10310 // that make use of these types. Also record whether we encounter non-record
10311 // candidate types or either arithmetic or enumeral candidate types.
10312 QualifiersAndAtomic VisibleTypeConversionsQuals;
10313 VisibleTypeConversionsQuals.addConst();
10314 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10315 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10316 if (Args[ArgIdx]->getType()->isAtomicType())
10317 VisibleTypeConversionsQuals.addAtomic();
10318 }
10319
10320 bool HasNonRecordCandidateType = false;
10321 bool HasArithmeticOrEnumeralCandidateType = false;
10323 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10324 CandidateTypes.emplace_back(*this);
10325 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10326 OpLoc,
10327 true,
10328 (Op == OO_Exclaim ||
10329 Op == OO_AmpAmp ||
10330 Op == OO_PipePipe),
10331 VisibleTypeConversionsQuals);
10332 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10333 CandidateTypes[ArgIdx].hasNonRecordTypes();
10334 HasArithmeticOrEnumeralCandidateType =
10335 HasArithmeticOrEnumeralCandidateType ||
10336 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10337 }
10338
10339 // Exit early when no non-record types have been added to the candidate set
10340 // for any of the arguments to the operator.
10341 //
10342 // We can't exit early for !, ||, or &&, since there we have always have
10343 // 'bool' overloads.
10344 if (!HasNonRecordCandidateType &&
10345 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10346 return;
10347
10348 // Setup an object to manage the common state for building overloads.
10349 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10350 VisibleTypeConversionsQuals,
10351 HasArithmeticOrEnumeralCandidateType,
10352 CandidateTypes, CandidateSet);
10353
10354 // Dispatch over the operation to add in only those overloads which apply.
10355 switch (Op) {
10356 case OO_None:
10358 llvm_unreachable("Expected an overloaded operator");
10359
10360 case OO_New:
10361 case OO_Delete:
10362 case OO_Array_New:
10363 case OO_Array_Delete:
10364 case OO_Call:
10365 llvm_unreachable(
10366 "Special operators don't use AddBuiltinOperatorCandidates");
10367
10368 case OO_Comma:
10369 case OO_Arrow:
10370 case OO_Coawait:
10371 // C++ [over.match.oper]p3:
10372 // -- For the operator ',', the unary operator '&', the
10373 // operator '->', or the operator 'co_await', the
10374 // built-in candidates set is empty.
10375 break;
10376
10377 case OO_Plus: // '+' is either unary or binary
10378 if (Args.size() == 1)
10379 OpBuilder.addUnaryPlusPointerOverloads();
10380 [[fallthrough]];
10381
10382 case OO_Minus: // '-' is either unary or binary
10383 if (Args.size() == 1) {
10384 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10385 } else {
10386 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10387 OpBuilder.addGenericBinaryArithmeticOverloads();
10388 OpBuilder.addMatrixBinaryArithmeticOverloads();
10389 }
10390 break;
10391
10392 case OO_Star: // '*' is either unary or binary
10393 if (Args.size() == 1)
10394 OpBuilder.addUnaryStarPointerOverloads();
10395 else {
10396 OpBuilder.addGenericBinaryArithmeticOverloads();
10397 OpBuilder.addMatrixBinaryArithmeticOverloads();
10398 }
10399 break;
10400
10401 case OO_Slash:
10402 OpBuilder.addGenericBinaryArithmeticOverloads();
10403 break;
10404
10405 case OO_PlusPlus:
10406 case OO_MinusMinus:
10407 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10408 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10409 break;
10410
10411 case OO_EqualEqual:
10412 case OO_ExclaimEqual:
10413 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10414 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10415 OpBuilder.addGenericBinaryArithmeticOverloads();
10416 break;
10417
10418 case OO_Less:
10419 case OO_Greater:
10420 case OO_LessEqual:
10421 case OO_GreaterEqual:
10422 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10423 OpBuilder.addGenericBinaryArithmeticOverloads();
10424 break;
10425
10426 case OO_Spaceship:
10427 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10428 OpBuilder.addThreeWayArithmeticOverloads();
10429 break;
10430
10431 case OO_Percent:
10432 case OO_Caret:
10433 case OO_Pipe:
10434 case OO_LessLess:
10435 case OO_GreaterGreater:
10436 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10437 break;
10438
10439 case OO_Amp: // '&' is either unary or binary
10440 if (Args.size() == 1)
10441 // C++ [over.match.oper]p3:
10442 // -- For the operator ',', the unary operator '&', or the
10443 // operator '->', the built-in candidates set is empty.
10444 break;
10445
10446 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10447 break;
10448
10449 case OO_Tilde:
10450 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10451 break;
10452
10453 case OO_Equal:
10454 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10455 [[fallthrough]];
10456
10457 case OO_PlusEqual:
10458 case OO_MinusEqual:
10459 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10460 [[fallthrough]];
10461
10462 case OO_StarEqual:
10463 case OO_SlashEqual:
10464 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10465 break;
10466
10467 case OO_PercentEqual:
10468 case OO_LessLessEqual:
10469 case OO_GreaterGreaterEqual:
10470 case OO_AmpEqual:
10471 case OO_CaretEqual:
10472 case OO_PipeEqual:
10473 OpBuilder.addAssignmentIntegralOverloads();
10474 break;
10475
10476 case OO_Exclaim:
10477 OpBuilder.addExclaimOverload();
10478 break;
10479
10480 case OO_AmpAmp:
10481 case OO_PipePipe:
10482 OpBuilder.addAmpAmpOrPipePipeOverload();
10483 break;
10484
10485 case OO_Subscript:
10486 if (Args.size() == 2)
10487 OpBuilder.addSubscriptOverloads();
10488 break;
10489
10490 case OO_ArrowStar:
10491 OpBuilder.addArrowStarOverloads();
10492 break;
10493
10494 case OO_Conditional:
10495 OpBuilder.addConditionalOperatorOverloads();
10496 OpBuilder.addGenericBinaryArithmeticOverloads();
10497 break;
10498 }
10499}
10500
10501void
10503 SourceLocation Loc,
10504 ArrayRef<Expr *> Args,
10505 TemplateArgumentListInfo *ExplicitTemplateArgs,
10506 OverloadCandidateSet& CandidateSet,
10507 bool PartialOverloading) {
10508 ADLResult Fns;
10509
10510 // FIXME: This approach for uniquing ADL results (and removing
10511 // redundant candidates from the set) relies on pointer-equality,
10512 // which means we need to key off the canonical decl. However,
10513 // always going back to the canonical decl might not get us the
10514 // right set of default arguments. What default arguments are
10515 // we supposed to consider on ADL candidates, anyway?
10516
10517 // FIXME: Pass in the explicit template arguments?
10518 ArgumentDependentLookup(Name, Loc, Args, Fns);
10519
10520 ArrayRef<Expr *> ReversedArgs;
10521
10522 // Erase all of the candidates we already knew about.
10523 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10524 CandEnd = CandidateSet.end();
10525 Cand != CandEnd; ++Cand)
10526 if (Cand->Function) {
10527 FunctionDecl *Fn = Cand->Function;
10528 Fns.erase(Fn);
10529 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10530 Fns.erase(FunTmpl);
10531 }
10532
10533 // For each of the ADL candidates we found, add it to the overload
10534 // set.
10535 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10537
10538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10539 if (ExplicitTemplateArgs)
10540 continue;
10541
10543 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10544 PartialOverloading, /*AllowExplicit=*/true,
10545 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10546 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10548 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10549 /*SuppressUserConversions=*/false, PartialOverloading,
10550 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10551 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10552 }
10553 } else {
10554 auto *FTD = cast<FunctionTemplateDecl>(*I);
10556 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10557 /*SuppressUserConversions=*/false, PartialOverloading,
10558 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10559 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10560 *this, Args, FTD->getTemplatedDecl())) {
10561
10562 // As template candidates are not deduced immediately,
10563 // persist the array in the overload set.
10564 if (ReversedArgs.empty())
10565 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10566
10568 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10569 /*SuppressUserConversions=*/false, PartialOverloading,
10570 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10572 }
10573 }
10574 }
10575}
10576
10577namespace {
10578enum class Comparison { Equal, Better, Worse };
10579}
10580
10581/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10582/// overload resolution.
10583///
10584/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10585/// Cand1's first N enable_if attributes have precisely the same conditions as
10586/// Cand2's first N enable_if attributes (where N = the number of enable_if
10587/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10588///
10589/// Note that you can have a pair of candidates such that Cand1's enable_if
10590/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10591/// worse than Cand1's.
10592static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10593 const FunctionDecl *Cand2) {
10594 // Common case: One (or both) decls don't have enable_if attrs.
10595 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10596 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10597 if (!Cand1Attr || !Cand2Attr) {
10598 if (Cand1Attr == Cand2Attr)
10599 return Comparison::Equal;
10600 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10601 }
10602
10603 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10604 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10605
10606 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10607 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10608 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10609 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10610
10611 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10612 // has fewer enable_if attributes than Cand2, and vice versa.
10613 if (!Cand1A)
10614 return Comparison::Worse;
10615 if (!Cand2A)
10616 return Comparison::Better;
10617
10618 Cand1ID.clear();
10619 Cand2ID.clear();
10620
10621 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10622 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10623 if (Cand1ID != Cand2ID)
10624 return Comparison::Worse;
10625 }
10626
10627 return Comparison::Equal;
10628}
10629
10630static Comparison
10632 const OverloadCandidate &Cand2) {
10633 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10634 !Cand2.Function->isMultiVersion())
10635 return Comparison::Equal;
10636
10637 // If both are invalid, they are equal. If one of them is invalid, the other
10638 // is better.
10639 if (Cand1.Function->isInvalidDecl()) {
10640 if (Cand2.Function->isInvalidDecl())
10641 return Comparison::Equal;
10642 return Comparison::Worse;
10643 }
10644 if (Cand2.Function->isInvalidDecl())
10645 return Comparison::Better;
10646
10647 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10648 // cpu_dispatch, else arbitrarily based on the identifiers.
10649 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10650 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10651 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10652 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10653
10654 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10655 return Comparison::Equal;
10656
10657 if (Cand1CPUDisp && !Cand2CPUDisp)
10658 return Comparison::Better;
10659 if (Cand2CPUDisp && !Cand1CPUDisp)
10660 return Comparison::Worse;
10661
10662 if (Cand1CPUSpec && Cand2CPUSpec) {
10663 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10664 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10665 ? Comparison::Better
10666 : Comparison::Worse;
10667
10668 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10669 FirstDiff = std::mismatch(
10670 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10671 Cand2CPUSpec->cpus_begin(),
10672 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10673 return LHS->getName() == RHS->getName();
10674 });
10675
10676 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10677 "Two different cpu-specific versions should not have the same "
10678 "identifier list, otherwise they'd be the same decl!");
10679 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10680 ? Comparison::Better
10681 : Comparison::Worse;
10682 }
10683 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10684}
10685
10686/// Compute the type of the implicit object parameter for the given function,
10687/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10688/// null QualType if there is a 'matches anything' implicit object parameter.
10689static std::optional<QualType>
10692 return std::nullopt;
10693
10694 auto *M = cast<CXXMethodDecl>(F);
10695 // Static member functions' object parameters match all types.
10696 if (M->isStatic())
10697 return QualType();
10698 return M->getFunctionObjectParameterReferenceType();
10699}
10700
10701// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10702// represent the same entity.
10703static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10704 const FunctionDecl *F2) {
10705 if (declaresSameEntity(F1, F2))
10706 return true;
10707 auto PT1 = F1->getPrimaryTemplate();
10708 auto PT2 = F2->getPrimaryTemplate();
10709 if (PT1 && PT2) {
10710 if (declaresSameEntity(PT1, PT2) ||
10711 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10712 PT2->getInstantiatedFromMemberTemplate()))
10713 return true;
10714 }
10715 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10716 // different functions with same params). Consider removing this (as no test
10717 // fail w/o it).
10718 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10719 if (First) {
10720 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10721 return *T;
10722 }
10723 assert(I < F->getNumParams());
10724 return F->getParamDecl(I++)->getType();
10725 };
10726
10727 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10728 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10729
10730 if (F1NumParams != F2NumParams)
10731 return false;
10732
10733 unsigned I1 = 0, I2 = 0;
10734 for (unsigned I = 0; I != F1NumParams; ++I) {
10735 QualType T1 = NextParam(F1, I1, I == 0);
10736 QualType T2 = NextParam(F2, I2, I == 0);
10737 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10738 if (!Context.hasSameUnqualifiedType(T1, T2))
10739 return false;
10740 }
10741 return true;
10742}
10743
10744/// We're allowed to use constraints partial ordering only if the candidates
10745/// have the same parameter types:
10746/// [over.match.best.general]p2.6
10747/// F1 and F2 are non-template functions with the same
10748/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10750 FunctionDecl *Fn2,
10751 bool IsFn1Reversed,
10752 bool IsFn2Reversed) {
10753 assert(Fn1 && Fn2);
10754 if (Fn1->isVariadic() != Fn2->isVariadic())
10755 return false;
10756
10757 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10758 IsFn1Reversed ^ IsFn2Reversed))
10759 return false;
10760
10761 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10762 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10763 if (Mem1 && Mem2) {
10764 // if they are member functions, both are direct members of the same class,
10765 // and
10766 if (Mem1->getParent() != Mem2->getParent())
10767 return false;
10768 // if both are non-static member functions, they have the same types for
10769 // their object parameters
10770 if (Mem1->isInstance() && Mem2->isInstance() &&
10772 Mem1->getFunctionObjectParameterReferenceType(),
10773 Mem1->getFunctionObjectParameterReferenceType()))
10774 return false;
10775 }
10776 return true;
10777}
10778
10779static FunctionDecl *
10781 bool IsFn1Reversed, bool IsFn2Reversed) {
10782 if (!Fn1 || !Fn2)
10783 return nullptr;
10784
10785 // C++ [temp.constr.order]:
10786 // A non-template function F1 is more partial-ordering-constrained than a
10787 // non-template function F2 if:
10788 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10789 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10790
10791 if (Cand1IsSpecialization || Cand2IsSpecialization)
10792 return nullptr;
10793
10794 // - they have the same non-object-parameter-type-lists, and [...]
10795 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10796 IsFn2Reversed))
10797 return nullptr;
10798
10799 // - the declaration of F1 is more constrained than the declaration of F2.
10800 return S.getMoreConstrainedFunction(Fn1, Fn2);
10801}
10802
10803/// isBetterOverloadCandidate - Determines whether the first overload
10804/// candidate is a better candidate than the second (C++ 13.3.3p1).
10806 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10808 bool PartialOverloading) {
10809 // Define viable functions to be better candidates than non-viable
10810 // functions.
10811 if (!Cand2.Viable)
10812 return Cand1.Viable;
10813 else if (!Cand1.Viable)
10814 return false;
10815
10816 // [CUDA] A function with 'never' preference is marked not viable, therefore
10817 // is never shown up here. The worst preference shown up here is 'wrong side',
10818 // e.g. an H function called by a HD function in device compilation. This is
10819 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10820 // function which is called only by an H function. A deferred diagnostic will
10821 // be triggered if it is emitted. However a wrong-sided function is still
10822 // a viable candidate here.
10823 //
10824 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10825 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10826 // can be emitted, Cand1 is not better than Cand2. This rule should have
10827 // precedence over other rules.
10828 //
10829 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10830 // other rules should be used to determine which is better. This is because
10831 // host/device based overloading resolution is mostly for determining
10832 // viability of a function. If two functions are both viable, other factors
10833 // should take precedence in preference, e.g. the standard-defined preferences
10834 // like argument conversion ranks or enable_if partial-ordering. The
10835 // preference for pass-object-size parameters is probably most similar to a
10836 // type-based-overloading decision and so should take priority.
10837 //
10838 // If other rules cannot determine which is better, CUDA preference will be
10839 // used again to determine which is better.
10840 //
10841 // TODO: Currently IdentifyPreference does not return correct values
10842 // for functions called in global variable initializers due to missing
10843 // correct context about device/host. Therefore we can only enforce this
10844 // rule when there is a caller. We should enforce this rule for functions
10845 // in global variable initializers once proper context is added.
10846 //
10847 // TODO: We can only enable the hostness based overloading resolution when
10848 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10849 // overloading resolution diagnostics.
10850 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10851 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10852 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10853 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10854 bool IsCand1ImplicitHD =
10856 bool IsCand2ImplicitHD =
10858 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10859 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10860 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10861 // The implicit HD function may be a function in a system header which
10862 // is forced by pragma. In device compilation, if we prefer HD candidates
10863 // over wrong-sided candidates, overloading resolution may change, which
10864 // may result in non-deferrable diagnostics. As a workaround, we let
10865 // implicit HD candidates take equal preference as wrong-sided candidates.
10866 // This will preserve the overloading resolution.
10867 // TODO: We still need special handling of implicit HD functions since
10868 // they may incur other diagnostics to be deferred. We should make all
10869 // host/device related diagnostics deferrable and remove special handling
10870 // of implicit HD functions.
10871 auto EmitThreshold =
10872 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10873 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10876 auto Cand1Emittable = P1 > EmitThreshold;
10877 auto Cand2Emittable = P2 > EmitThreshold;
10878 if (Cand1Emittable && !Cand2Emittable)
10879 return true;
10880 if (!Cand1Emittable && Cand2Emittable)
10881 return false;
10882 }
10883 }
10884
10885 // C++ [over.match.best]p1: (Changed in C++23)
10886 //
10887 // -- if F is a static member function, ICS1(F) is defined such
10888 // that ICS1(F) is neither better nor worse than ICS1(G) for
10889 // any function G, and, symmetrically, ICS1(G) is neither
10890 // better nor worse than ICS1(F).
10891 unsigned StartArg = 0;
10892 if (!Cand1.TookAddressOfOverload &&
10894 StartArg = 1;
10895
10896 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10897 // We don't allow incompatible pointer conversions in C++.
10898 if (!S.getLangOpts().CPlusPlus)
10899 return ICS.isStandard() &&
10900 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10901
10902 // The only ill-formed conversion we allow in C++ is the string literal to
10903 // char* conversion, which is only considered ill-formed after C++11.
10904 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10906 };
10907
10908 // Define functions that don't require ill-formed conversions for a given
10909 // argument to be better candidates than functions that do.
10910 unsigned NumArgs = Cand1.Conversions.size();
10911 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10912 bool HasBetterConversion = false;
10913 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10914 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10915 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10916 if (Cand1Bad != Cand2Bad) {
10917 if (Cand1Bad)
10918 return false;
10919 HasBetterConversion = true;
10920 }
10921 }
10922
10923 if (HasBetterConversion)
10924 return true;
10925
10926 // C++ [over.match.best]p1:
10927 // A viable function F1 is defined to be a better function than another
10928 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10929 // conversion sequence than ICSi(F2), and then...
10930 bool HasWorseConversion = false;
10931 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10933 Cand1.Conversions[ArgIdx],
10934 Cand2.Conversions[ArgIdx])) {
10936 // Cand1 has a better conversion sequence.
10937 HasBetterConversion = true;
10938 break;
10939
10941 if (Cand1.Function && Cand2.Function &&
10942 Cand1.isReversed() != Cand2.isReversed() &&
10943 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10944 // Work around large-scale breakage caused by considering reversed
10945 // forms of operator== in C++20:
10946 //
10947 // When comparing a function against a reversed function, if we have a
10948 // better conversion for one argument and a worse conversion for the
10949 // other, the implicit conversion sequences are treated as being equally
10950 // good.
10951 //
10952 // This prevents a comparison function from being considered ambiguous
10953 // with a reversed form that is written in the same way.
10954 //
10955 // We diagnose this as an extension from CreateOverloadedBinOp.
10956 HasWorseConversion = true;
10957 break;
10958 }
10959
10960 // Cand1 can't be better than Cand2.
10961 return false;
10962
10964 // Do nothing.
10965 break;
10966 }
10967 }
10968
10969 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10970 // ICSj(F2), or, if not that,
10971 if (HasBetterConversion && !HasWorseConversion)
10972 return true;
10973
10974 // -- the context is an initialization by user-defined conversion
10975 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10976 // from the return type of F1 to the destination type (i.e.,
10977 // the type of the entity being initialized) is a better
10978 // conversion sequence than the standard conversion sequence
10979 // from the return type of F2 to the destination type.
10981 Cand1.Function && Cand2.Function &&
10984
10985 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10986 // First check whether we prefer one of the conversion functions over the
10987 // other. This only distinguishes the results in non-standard, extension
10988 // cases such as the conversion from a lambda closure type to a function
10989 // pointer or block.
10994 Cand1.FinalConversion,
10995 Cand2.FinalConversion);
10996
10999
11000 // FIXME: Compare kind of reference binding if conversion functions
11001 // convert to a reference type used in direct reference binding, per
11002 // C++14 [over.match.best]p1 section 2 bullet 3.
11003 }
11004
11005 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11006 // as combined with the resolution to CWG issue 243.
11007 //
11008 // When the context is initialization by constructor ([over.match.ctor] or
11009 // either phase of [over.match.list]), a constructor is preferred over
11010 // a conversion function.
11011 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11012 Cand1.Function && Cand2.Function &&
11015 return isa<CXXConstructorDecl>(Cand1.Function);
11016
11017 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11018 return Cand2.StrictPackMatch;
11019
11020 // -- F1 is a non-template function and F2 is a function template
11021 // specialization, or, if not that,
11022 bool Cand1IsSpecialization = Cand1.Function &&
11024 bool Cand2IsSpecialization = Cand2.Function &&
11026 if (Cand1IsSpecialization != Cand2IsSpecialization)
11027 return Cand2IsSpecialization;
11028
11029 // -- F1 and F2 are function template specializations, and the function
11030 // template for F1 is more specialized than the template for F2
11031 // according to the partial ordering rules described in 14.5.5.2, or,
11032 // if not that,
11033 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11034 const auto *Obj1Context =
11035 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11036 const auto *Obj2Context =
11037 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11038 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11040 Cand2.Function->getPrimaryTemplate(), Loc,
11042 : TPOC_Call,
11044 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11045 : QualType{},
11046 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11047 : QualType{},
11048 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11049 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11050 }
11051 }
11052
11053 // -— F1 and F2 are non-template functions and F1 is more
11054 // partial-ordering-constrained than F2 [...],
11056 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11057 Cand2.isReversed());
11058 F && F == Cand1.Function)
11059 return true;
11060
11061 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11062 // class B of D, and for all arguments the corresponding parameters of
11063 // F1 and F2 have the same type.
11064 // FIXME: Implement the "all parameters have the same type" check.
11065 bool Cand1IsInherited =
11066 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11067 bool Cand2IsInherited =
11068 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11069 if (Cand1IsInherited != Cand2IsInherited)
11070 return Cand2IsInherited;
11071 else if (Cand1IsInherited) {
11072 assert(Cand2IsInherited);
11073 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11074 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11075 if (Cand1Class->isDerivedFrom(Cand2Class))
11076 return true;
11077 if (Cand2Class->isDerivedFrom(Cand1Class))
11078 return false;
11079 // Inherited from sibling base classes: still ambiguous.
11080 }
11081
11082 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11083 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11084 // with reversed order of parameters and F1 is not
11085 //
11086 // We rank reversed + different operator as worse than just reversed, but
11087 // that comparison can never happen, because we only consider reversing for
11088 // the maximally-rewritten operator (== or <=>).
11089 if (Cand1.RewriteKind != Cand2.RewriteKind)
11090 return Cand1.RewriteKind < Cand2.RewriteKind;
11091
11092 // Check C++17 tie-breakers for deduction guides.
11093 {
11094 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11095 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11096 if (Guide1 && Guide2) {
11097 // -- F1 is generated from a deduction-guide and F2 is not
11098 if (Guide1->isImplicit() != Guide2->isImplicit())
11099 return Guide2->isImplicit();
11100
11101 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11102 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11103 return true;
11104 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11105 return false;
11106
11107 // --F1 is generated from a non-template constructor and F2 is generated
11108 // from a constructor template
11109 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11110 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11111 if (Constructor1 && Constructor2) {
11112 bool isC1Templated = Constructor1->getTemplatedKind() !=
11114 bool isC2Templated = Constructor2->getTemplatedKind() !=
11116 if (isC1Templated != isC2Templated)
11117 return isC2Templated;
11118 }
11119 }
11120 }
11121
11122 // Check for enable_if value-based overload resolution.
11123 if (Cand1.Function && Cand2.Function) {
11124 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11125 if (Cmp != Comparison::Equal)
11126 return Cmp == Comparison::Better;
11127 }
11128
11129 bool HasPS1 = Cand1.Function != nullptr &&
11131 bool HasPS2 = Cand2.Function != nullptr &&
11133 if (HasPS1 != HasPS2 && HasPS1)
11134 return true;
11135
11136 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11137 if (MV == Comparison::Better)
11138 return true;
11139 if (MV == Comparison::Worse)
11140 return false;
11141
11142 // If other rules cannot determine which is better, CUDA preference is used
11143 // to determine which is better.
11144 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11145 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11146 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11147 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11148 }
11149
11150 // General member function overloading is handled above, so this only handles
11151 // constructors with address spaces.
11152 // This only handles address spaces since C++ has no other
11153 // qualifier that can be used with constructors.
11154 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11155 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11156 if (CD1 && CD2) {
11157 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11158 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11159 if (AS1 != AS2) {
11161 return true;
11163 return false;
11164 }
11165 }
11166
11167 return false;
11168}
11169
11170/// Determine whether two declarations are "equivalent" for the purposes of
11171/// name lookup and overload resolution. This applies when the same internal/no
11172/// linkage entity is defined by two modules (probably by textually including
11173/// the same header). In such a case, we don't consider the declarations to
11174/// declare the same entity, but we also don't want lookups with both
11175/// declarations visible to be ambiguous in some cases (this happens when using
11176/// a modularized libstdc++).
11178 const NamedDecl *B) {
11179 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11180 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11181 if (!VA || !VB)
11182 return false;
11183
11184 // The declarations must be declaring the same name as an internal linkage
11185 // entity in different modules.
11186 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11187 VB->getDeclContext()->getRedeclContext()) ||
11188 getOwningModule(VA) == getOwningModule(VB) ||
11189 VA->isExternallyVisible() || VB->isExternallyVisible())
11190 return false;
11191
11192 // Check that the declarations appear to be equivalent.
11193 //
11194 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11195 // For constants and functions, we should check the initializer or body is
11196 // the same. For non-constant variables, we shouldn't allow it at all.
11197 if (Context.hasSameType(VA->getType(), VB->getType()))
11198 return true;
11199
11200 // Enum constants within unnamed enumerations will have different types, but
11201 // may still be similar enough to be interchangeable for our purposes.
11202 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11203 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11204 // Only handle anonymous enums. If the enumerations were named and
11205 // equivalent, they would have been merged to the same type.
11206 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11207 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11208 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11209 !Context.hasSameType(EnumA->getIntegerType(),
11210 EnumB->getIntegerType()))
11211 return false;
11212 // Allow this only if the value is the same for both enumerators.
11213 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11214 }
11215 }
11216
11217 // Nothing else is sufficiently similar.
11218 return false;
11219}
11220
11223 assert(D && "Unknown declaration");
11224 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11225
11226 Module *M = getOwningModule(D);
11227 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11228 << !M << (M ? M->getFullModuleName() : "");
11229
11230 for (auto *E : Equiv) {
11231 Module *M = getOwningModule(E);
11232 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11233 << !M << (M ? M->getFullModuleName() : "");
11234 }
11235}
11236
11239 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11241 static_cast<CNSInfo *>(DeductionFailure.Data)
11242 ->Satisfaction.ContainsErrors;
11243}
11244
11247 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11248 bool PartialOverloading, bool AllowExplicit,
11250 bool AggregateCandidateDeduction) {
11251
11252 auto *C =
11253 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11254
11257 /*AllowObjCConversionOnExplicit=*/false,
11258 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11259 PartialOverloading, AggregateCandidateDeduction},
11261 FoundDecl,
11262 Args,
11263 IsADLCandidate,
11264 PO};
11265
11266 HasDeferredTemplateConstructors |=
11267 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11268}
11269
11271 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11272 CXXRecordDecl *ActingContext, QualType ObjectType,
11273 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11274 bool SuppressUserConversions, bool PartialOverloading,
11276
11277 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11278
11279 auto *C =
11280 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11281
11284 /*AllowObjCConversionOnExplicit=*/false,
11285 /*AllowResultConversion=*/false,
11286 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11287 /*AggregateCandidateDeduction=*/false},
11288 MethodTmpl,
11289 FoundDecl,
11290 Args,
11291 ActingContext,
11292 ObjectClassification,
11293 ObjectType,
11294 PO};
11295}
11296
11299 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11300 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11301 bool AllowResultConversion) {
11302
11303 auto *C =
11304 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11305
11308 AllowObjCConversionOnExplicit, AllowResultConversion,
11309 /*AllowExplicit=*/false,
11310 /*SuppressUserConversions=*/false,
11311 /*PartialOverloading*/ false,
11312 /*AggregateCandidateDeduction=*/false},
11314 FoundDecl,
11315 ActingContext,
11316 From,
11317 ToType};
11318}
11319
11320static void
11323
11325 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11326 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11327 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11328}
11329
11330static void
11334 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11335 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11336 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11337 C.AggregateCandidateDeduction);
11338}
11339
11340static void
11344 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11345 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11346 C.AllowResultConversion);
11347}
11348
11350 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11351 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11352 while (Cand) {
11353 switch (Cand->Kind) {
11356 S, *this,
11357 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11358 break;
11361 S, *this,
11362 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11363 break;
11366 S, *this,
11367 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11368 break;
11369 }
11370 Cand = Cand->Next;
11371 }
11372 FirstDeferredCandidate = nullptr;
11373 DeferredCandidatesCount = 0;
11374}
11375
11377OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11378 Best->Best = true;
11379 if (Best->Function && Best->Function->isDeleted())
11380 return OR_Deleted;
11381 return OR_Success;
11382}
11383
11384void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11386 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11387 // are accepted by both clang and NVCC. However, during a particular
11388 // compilation mode only one call variant is viable. We need to
11389 // exclude non-viable overload candidates from consideration based
11390 // only on their host/device attributes. Specifically, if one
11391 // candidate call is WrongSide and the other is SameSide, we ignore
11392 // the WrongSide candidate.
11393 // We only need to remove wrong-sided candidates here if
11394 // -fgpu-exclude-wrong-side-overloads is off. When
11395 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11396 // uniformly in isBetterOverloadCandidate.
11397 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11398 return;
11399 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11400
11401 bool ContainsSameSideCandidate =
11402 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11403 // Check viable function only.
11404 return Cand->Viable && Cand->Function &&
11405 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11407 });
11408
11409 if (!ContainsSameSideCandidate)
11410 return;
11411
11412 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11413 // Check viable function only to avoid unnecessary data copying/moving.
11414 return Cand->Viable && Cand->Function &&
11415 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11417 };
11418 llvm::erase_if(Candidates, IsWrongSideCandidate);
11419}
11420
11421/// Computes the best viable function (C++ 13.3.3)
11422/// within an overload candidate set.
11423///
11424/// \param Loc The location of the function name (or operator symbol) for
11425/// which overload resolution occurs.
11426///
11427/// \param Best If overload resolution was successful or found a deleted
11428/// function, \p Best points to the candidate function found.
11429///
11430/// \returns The result of overload resolution.
11432 SourceLocation Loc,
11433 iterator &Best) {
11434
11436 DeferredCandidatesCount == 0) &&
11437 "Unexpected deferred template candidates");
11438
11439 bool TwoPhaseResolution =
11440 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11441
11442 if (TwoPhaseResolution) {
11443 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11444 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11445 if (!(HasDeferredTemplateConstructors &&
11446 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11447 return Res;
11448 }
11449 }
11450
11452 return BestViableFunctionImpl(S, Loc, Best);
11453}
11454
11455OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11457
11459 Candidates.reserve(this->Candidates.size());
11460 std::transform(this->Candidates.begin(), this->Candidates.end(),
11461 std::back_inserter(Candidates),
11462 [](OverloadCandidate &Cand) { return &Cand; });
11463
11464 if (S.getLangOpts().CUDA)
11465 CudaExcludeWrongSideCandidates(S, Candidates);
11466
11467 Best = end();
11468 for (auto *Cand : Candidates) {
11469 Cand->Best = false;
11470 if (Cand->Viable) {
11471 if (Best == end() ||
11472 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11473 Best = Cand;
11474 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11475 // This candidate has constraint that we were unable to evaluate because
11476 // it referenced an expression that contained an error. Rather than fall
11477 // back onto a potentially unintended candidate (made worse by
11478 // subsuming constraints), treat this as 'no viable candidate'.
11479 Best = end();
11480 return OR_No_Viable_Function;
11481 }
11482 }
11483
11484 // If we didn't find any viable functions, abort.
11485 if (Best == end())
11486 return OR_No_Viable_Function;
11487
11488 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11489 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11490 PendingBest.push_back(&*Best);
11491 Best->Best = true;
11492
11493 // Make sure that this function is better than every other viable
11494 // function. If not, we have an ambiguity.
11495 while (!PendingBest.empty()) {
11496 auto *Curr = PendingBest.pop_back_val();
11497 for (auto *Cand : Candidates) {
11498 if (Cand->Viable && !Cand->Best &&
11499 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11500 PendingBest.push_back(Cand);
11501 Cand->Best = true;
11502
11504 Curr->Function))
11505 EquivalentCands.push_back(Cand->Function);
11506 else
11507 Best = end();
11508 }
11509 }
11510 }
11511
11512 if (Best == end())
11513 return OR_Ambiguous;
11514
11515 OverloadingResult R = ResultForBestCandidate(Best);
11516
11517 if (!EquivalentCands.empty())
11519 EquivalentCands);
11520 return R;
11521}
11522
11523namespace {
11524
11525enum OverloadCandidateKind {
11526 oc_function,
11527 oc_method,
11528 oc_reversed_binary_operator,
11529 oc_constructor,
11530 oc_implicit_default_constructor,
11531 oc_implicit_copy_constructor,
11532 oc_implicit_move_constructor,
11533 oc_implicit_copy_assignment,
11534 oc_implicit_move_assignment,
11535 oc_implicit_equality_comparison,
11536 oc_inherited_constructor
11537};
11538
11539enum OverloadCandidateSelect {
11540 ocs_non_template,
11541 ocs_template,
11542 ocs_described_template,
11543};
11544
11545static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11546ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11547 const FunctionDecl *Fn,
11549 std::string &Description) {
11550
11551 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11552 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11553 isTemplate = true;
11554 Description = S.getTemplateArgumentBindingsText(
11555 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11556 }
11557
11558 OverloadCandidateSelect Select = [&]() {
11559 if (!Description.empty())
11560 return ocs_described_template;
11561 return isTemplate ? ocs_template : ocs_non_template;
11562 }();
11563
11564 OverloadCandidateKind Kind = [&]() {
11565 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11566 return oc_implicit_equality_comparison;
11567
11568 if (CRK & CRK_Reversed)
11569 return oc_reversed_binary_operator;
11570
11571 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11572 if (!Ctor->isImplicit()) {
11574 return oc_inherited_constructor;
11575 else
11576 return oc_constructor;
11577 }
11578
11579 if (Ctor->isDefaultConstructor())
11580 return oc_implicit_default_constructor;
11581
11582 if (Ctor->isMoveConstructor())
11583 return oc_implicit_move_constructor;
11584
11585 assert(Ctor->isCopyConstructor() &&
11586 "unexpected sort of implicit constructor");
11587 return oc_implicit_copy_constructor;
11588 }
11589
11590 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11591 // This actually gets spelled 'candidate function' for now, but
11592 // it doesn't hurt to split it out.
11593 if (!Meth->isImplicit())
11594 return oc_method;
11595
11596 if (Meth->isMoveAssignmentOperator())
11597 return oc_implicit_move_assignment;
11598
11599 if (Meth->isCopyAssignmentOperator())
11600 return oc_implicit_copy_assignment;
11601
11602 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11603 return oc_method;
11604 }
11605
11606 return oc_function;
11607 }();
11608
11609 return std::make_pair(Kind, Select);
11610}
11611
11612void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11613 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11614 // set.
11615 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11616 S.Diag(FoundDecl->getLocation(),
11617 diag::note_ovl_candidate_inherited_constructor)
11618 << Shadow->getNominatedBaseClass();
11619}
11620
11621} // end anonymous namespace
11622
11624 const FunctionDecl *FD) {
11625 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11626 bool AlwaysTrue;
11627 if (EnableIf->getCond()->isValueDependent() ||
11628 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11629 return false;
11630 if (!AlwaysTrue)
11631 return false;
11632 }
11633 return true;
11634}
11635
11636/// Returns true if we can take the address of the function.
11637///
11638/// \param Complain - If true, we'll emit a diagnostic
11639/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11640/// we in overload resolution?
11641/// \param Loc - The location of the statement we're complaining about. Ignored
11642/// if we're not complaining, or if we're in overload resolution.
11644 bool Complain,
11645 bool InOverloadResolution,
11646 SourceLocation Loc) {
11647 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11648 if (Complain) {
11649 if (InOverloadResolution)
11650 S.Diag(FD->getBeginLoc(),
11651 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11652 else
11653 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11654 }
11655 return false;
11656 }
11657
11658 if (FD->getTrailingRequiresClause()) {
11659 ConstraintSatisfaction Satisfaction;
11660 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11661 return false;
11662 if (!Satisfaction.IsSatisfied) {
11663 if (Complain) {
11664 if (InOverloadResolution) {
11665 SmallString<128> TemplateArgString;
11666 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11667 TemplateArgString += " ";
11668 TemplateArgString += S.getTemplateArgumentBindingsText(
11669 FunTmpl->getTemplateParameters(),
11671 }
11672
11673 S.Diag(FD->getBeginLoc(),
11674 diag::note_ovl_candidate_unsatisfied_constraints)
11675 << TemplateArgString;
11676 } else
11677 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11678 << FD;
11679 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11680 }
11681 return false;
11682 }
11683 }
11684
11685 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11686 return P->hasAttr<PassObjectSizeAttr>();
11687 });
11688 if (I == FD->param_end())
11689 return true;
11690
11691 if (Complain) {
11692 // Add one to ParamNo because it's user-facing
11693 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11694 if (InOverloadResolution)
11695 S.Diag(FD->getLocation(),
11696 diag::note_ovl_candidate_has_pass_object_size_params)
11697 << ParamNo;
11698 else
11699 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11700 << FD << ParamNo;
11701 }
11702 return false;
11703}
11704
11706 const FunctionDecl *FD) {
11707 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11708 /*InOverloadResolution=*/true,
11709 /*Loc=*/SourceLocation());
11710}
11711
11713 bool Complain,
11714 SourceLocation Loc) {
11715 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11716 /*InOverloadResolution=*/false,
11717 Loc);
11718}
11719
11720// Don't print candidates other than the one that matches the calling
11721// convention of the call operator, since that is guaranteed to exist.
11723 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11724
11725 if (!ConvD)
11726 return false;
11727 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11728 if (!RD->isLambda())
11729 return false;
11730
11731 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11732 CallingConv CallOpCC =
11733 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11734 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11735 CallingConv ConvToCC =
11736 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11737
11738 return ConvToCC != CallOpCC;
11739}
11740
11741// Notes the location of an overload candidate.
11743 OverloadCandidateRewriteKind RewriteKind,
11744 QualType DestType, bool TakingAddress) {
11745 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11746 return;
11747 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11748 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11749 return;
11750 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11751 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11752 return;
11754 return;
11755
11756 std::string FnDesc;
11757 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11758 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11759 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11760 << (unsigned)KSPair.first << (unsigned)KSPair.second
11761 << Fn << FnDesc;
11762
11763 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11764 Diag(Fn->getLocation(), PD);
11765 MaybeEmitInheritedConstructorNote(*this, Found);
11766}
11767
11768static void
11770 // Perhaps the ambiguity was caused by two atomic constraints that are
11771 // 'identical' but not equivalent:
11772 //
11773 // void foo() requires (sizeof(T) > 4) { } // #1
11774 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11775 //
11776 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11777 // #2 to subsume #1, but these constraint are not considered equivalent
11778 // according to the subsumption rules because they are not the same
11779 // source-level construct. This behavior is quite confusing and we should try
11780 // to help the user figure out what happened.
11781
11782 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11783 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11784 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11785 if (!I->Function)
11786 continue;
11788 if (auto *Template = I->Function->getPrimaryTemplate())
11789 Template->getAssociatedConstraints(AC);
11790 else
11791 I->Function->getAssociatedConstraints(AC);
11792 if (AC.empty())
11793 continue;
11794 if (FirstCand == nullptr) {
11795 FirstCand = I->Function;
11796 FirstAC = AC;
11797 } else if (SecondCand == nullptr) {
11798 SecondCand = I->Function;
11799 SecondAC = AC;
11800 } else {
11801 // We have more than one pair of constrained functions - this check is
11802 // expensive and we'd rather not try to diagnose it.
11803 return;
11804 }
11805 }
11806 if (!SecondCand)
11807 return;
11808 // The diagnostic can only happen if there are associated constraints on
11809 // both sides (there needs to be some identical atomic constraint).
11810 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11811 SecondCand, SecondAC))
11812 // Just show the user one diagnostic, they'll probably figure it out
11813 // from here.
11814 return;
11815}
11816
11817// Notes the location of all overload candidates designated through
11818// OverloadedExpr
11819void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11820 bool TakingAddress) {
11821 assert(OverloadedExpr->getType() == Context.OverloadTy);
11822
11823 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11824 OverloadExpr *OvlExpr = Ovl.Expression;
11825
11826 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11827 IEnd = OvlExpr->decls_end();
11828 I != IEnd; ++I) {
11829 if (FunctionTemplateDecl *FunTmpl =
11830 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11831 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11832 TakingAddress);
11833 } else if (FunctionDecl *Fun
11834 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11835 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11836 }
11837 }
11838}
11839
11840/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11841/// "lead" diagnostic; it will be given two arguments, the source and
11842/// target types of the conversion.
11844 Sema &S,
11845 SourceLocation CaretLoc,
11846 const PartialDiagnostic &PDiag) const {
11847 S.Diag(CaretLoc, PDiag)
11848 << Ambiguous.getFromType() << Ambiguous.getToType();
11849 unsigned CandsShown = 0;
11851 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11852 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11853 break;
11854 ++CandsShown;
11855 S.NoteOverloadCandidate(I->first, I->second);
11856 }
11857 S.Diags.overloadCandidatesShown(CandsShown);
11858 if (I != E)
11859 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11860}
11861
11863 unsigned I, bool TakingCandidateAddress) {
11864 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11865 assert(Conv.isBad());
11866 assert(Cand->Function && "for now, candidate must be a function");
11867 FunctionDecl *Fn = Cand->Function;
11868
11869 // There's a conversion slot for the object argument if this is a
11870 // non-constructor method. Note that 'I' corresponds the
11871 // conversion-slot index.
11872 bool isObjectArgument = false;
11873 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11875 if (I == 0)
11876 isObjectArgument = true;
11877 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11878 I--;
11879 }
11880
11881 std::string FnDesc;
11882 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11883 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11884 FnDesc);
11885
11886 Expr *FromExpr = Conv.Bad.FromExpr;
11887 QualType FromTy = Conv.Bad.getFromType();
11888 QualType ToTy = Conv.Bad.getToType();
11889 SourceRange ToParamRange;
11890
11891 // FIXME: In presence of parameter packs we can't determine parameter range
11892 // reliably, as we don't have access to instantiation.
11893 bool HasParamPack =
11894 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11895 return Parm->isParameterPack();
11896 });
11897 if (!isObjectArgument && !HasParamPack)
11898 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11899
11900 if (FromTy == S.Context.OverloadTy) {
11901 assert(FromExpr && "overload set argument came from implicit argument?");
11902 Expr *E = FromExpr->IgnoreParens();
11903 if (isa<UnaryOperator>(E))
11904 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11905 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11906
11907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11908 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11909 << ToParamRange << ToTy << Name << I + 1;
11910 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11911 return;
11912 }
11913
11914 // Do some hand-waving analysis to see if the non-viability is due
11915 // to a qualifier mismatch.
11916 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11917 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11918 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11919 CToTy = RT->getPointeeType();
11920 else {
11921 // TODO: detect and diagnose the full richness of const mismatches.
11922 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11923 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11924 CFromTy = FromPT->getPointeeType();
11925 CToTy = ToPT->getPointeeType();
11926 }
11927 }
11928
11929 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11930 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11931 Qualifiers FromQs = CFromTy.getQualifiers();
11932 Qualifiers ToQs = CToTy.getQualifiers();
11933
11934 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11935 if (isObjectArgument)
11936 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11937 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11938 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11939 else
11940 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11941 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11942 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11943 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11944 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11945 return;
11946 }
11947
11948 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11949 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11950 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11951 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11952 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11953 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11954 return;
11955 }
11956
11957 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11958 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11959 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11960 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11961 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11962 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11963 return;
11964 }
11965
11966 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11967 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11968 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11969 << FromTy << !!FromQs.getPointerAuth()
11970 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11971 << ToQs.getPointerAuth().getAsString() << I + 1
11972 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11973 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11974 return;
11975 }
11976
11977 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11978 assert(CVR && "expected qualifiers mismatch");
11979
11980 if (isObjectArgument) {
11981 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11982 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11983 << FromTy << (CVR - 1);
11984 } else {
11985 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11986 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11987 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11988 }
11989 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11990 return;
11991 }
11992
11995 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11996 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11997 << (unsigned)isObjectArgument << I + 1
11999 << ToParamRange;
12000 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12001 return;
12002 }
12003
12004 // Special diagnostic for failure to convert an initializer list, since
12005 // telling the user that it has type void is not useful.
12006 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12008 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12009 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12012 ? 2
12013 : 0);
12014 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12015 return;
12016 }
12017
12018 // Diagnose references or pointers to incomplete types differently,
12019 // since it's far from impossible that the incompleteness triggered
12020 // the failure.
12021 QualType TempFromTy = FromTy.getNonReferenceType();
12022 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12023 TempFromTy = PTy->getPointeeType();
12024 if (TempFromTy->isIncompleteType()) {
12025 // Emit the generic diagnostic and, optionally, add the hints to it.
12026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12027 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12028 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12029 << (unsigned)(Cand->Fix.Kind);
12030
12031 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12032 return;
12033 }
12034
12035 // Diagnose base -> derived pointer conversions.
12036 unsigned BaseToDerivedConversion = 0;
12037 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12038 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12039 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12040 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12041 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12042 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12043 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12044 FromPtrTy->getPointeeType()))
12045 BaseToDerivedConversion = 1;
12046 }
12047 } else if (const ObjCObjectPointerType *FromPtrTy
12048 = FromTy->getAs<ObjCObjectPointerType>()) {
12049 if (const ObjCObjectPointerType *ToPtrTy
12050 = ToTy->getAs<ObjCObjectPointerType>())
12051 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12052 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12053 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12054 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12055 FromIface->isSuperClassOf(ToIface))
12056 BaseToDerivedConversion = 2;
12057 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12058 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12059 S.getASTContext()) &&
12060 !FromTy->isIncompleteType() &&
12061 !ToRefTy->getPointeeType()->isIncompleteType() &&
12062 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12063 BaseToDerivedConversion = 3;
12064 }
12065 }
12066
12067 if (BaseToDerivedConversion) {
12068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12069 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12070 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12071 << I + 1;
12072 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12073 return;
12074 }
12075
12076 if (isa<ObjCObjectPointerType>(CFromTy) &&
12077 isa<PointerType>(CToTy)) {
12078 Qualifiers FromQs = CFromTy.getQualifiers();
12079 Qualifiers ToQs = CToTy.getQualifiers();
12080 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12082 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12083 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12084 << I + 1;
12085 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12086 return;
12087 }
12088 }
12089
12090 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12091 return;
12092
12093 // Emit the generic diagnostic and, optionally, add the hints to it.
12094 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12095 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12096 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12097 << (unsigned)(Cand->Fix.Kind);
12098
12099 // Check that location of Fn is not in system header.
12100 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12101 // If we can fix the conversion, suggest the FixIts.
12102 for (const FixItHint &HI : Cand->Fix.Hints)
12103 FDiag << HI;
12104 }
12105
12106 S.Diag(Fn->getLocation(), FDiag);
12107
12108 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12109}
12110
12111/// Additional arity mismatch diagnosis specific to a function overload
12112/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12113/// over a candidate in any candidate set.
12115 unsigned NumArgs, bool IsAddressOf = false) {
12116 assert(Cand->Function && "Candidate is required to be a function.");
12117 FunctionDecl *Fn = Cand->Function;
12118 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12119 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12120
12121 // With invalid overloaded operators, it's possible that we think we
12122 // have an arity mismatch when in fact it looks like we have the
12123 // right number of arguments, because only overloaded operators have
12124 // the weird behavior of overloading member and non-member functions.
12125 // Just don't report anything.
12126 if (Fn->isInvalidDecl() &&
12127 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12128 return true;
12129
12130 if (NumArgs < MinParams) {
12131 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12133 Cand->DeductionFailure.getResult() ==
12135 } else {
12136 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12138 Cand->DeductionFailure.getResult() ==
12140 }
12141
12142 return false;
12143}
12144
12145/// General arity mismatch diagnosis over a candidate in a candidate set.
12147 unsigned NumFormalArgs,
12148 bool IsAddressOf = false) {
12149 assert(isa<FunctionDecl>(D) &&
12150 "The templated declaration should at least be a function"
12151 " when diagnosing bad template argument deduction due to too many"
12152 " or too few arguments");
12153
12155
12156 // TODO: treat calls to a missing default constructor as a special case
12157 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12158 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12159 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12160
12161 // at least / at most / exactly
12162 bool HasExplicitObjectParam =
12163 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12164
12165 unsigned ParamCount =
12166 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12167 unsigned mode, modeCount;
12168
12169 if (NumFormalArgs < MinParams) {
12170 if (MinParams != ParamCount || FnTy->isVariadic() ||
12171 FnTy->isTemplateVariadic())
12172 mode = 0; // "at least"
12173 else
12174 mode = 2; // "exactly"
12175 modeCount = MinParams;
12176 } else {
12177 if (MinParams != ParamCount)
12178 mode = 1; // "at most"
12179 else
12180 mode = 2; // "exactly"
12181 modeCount = ParamCount;
12182 }
12183
12184 std::string Description;
12185 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12186 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12187
12188 if (modeCount == 1 && !IsAddressOf &&
12189 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12191 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12192 << Description << mode
12193 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12194 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12195 else
12196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12197 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12198 << Description << mode << modeCount << NumFormalArgs
12199 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12200
12201 MaybeEmitInheritedConstructorNote(S, Found);
12202}
12203
12204/// Arity mismatch diagnosis specific to a function overload candidate.
12206 unsigned NumFormalArgs) {
12207 assert(Cand->Function && "Candidate must be a function");
12208 FunctionDecl *Fn = Cand->Function;
12209 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12210 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12211 Cand->TookAddressOfOverload);
12212}
12213
12215 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12216 return TD;
12217 llvm_unreachable("Unsupported: Getting the described template declaration"
12218 " for bad deduction diagnosis");
12219}
12220
12221/// Diagnose a failed template-argument deduction.
12222static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12223 DeductionFailureInfo &DeductionFailure,
12224 unsigned NumArgs,
12225 bool TakingCandidateAddress) {
12226 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12227 NamedDecl *ParamD;
12228 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12229 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12230 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12231 switch (DeductionFailure.getResult()) {
12233 llvm_unreachable(
12234 "TemplateDeductionResult::Success while diagnosing bad deduction");
12236 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12237 "while diagnosing bad deduction");
12240 return;
12241
12243 assert(ParamD && "no parameter found for incomplete deduction result");
12244 S.Diag(Templated->getLocation(),
12245 diag::note_ovl_candidate_incomplete_deduction)
12246 << ParamD->getDeclName();
12247 MaybeEmitInheritedConstructorNote(S, Found);
12248 return;
12249 }
12250
12252 assert(ParamD && "no parameter found for incomplete deduction result");
12253 S.Diag(Templated->getLocation(),
12254 diag::note_ovl_candidate_incomplete_deduction_pack)
12255 << ParamD->getDeclName()
12256 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12257 << *DeductionFailure.getFirstArg();
12258 MaybeEmitInheritedConstructorNote(S, Found);
12259 return;
12260 }
12261
12263 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12265
12266 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12267
12268 // Param will have been canonicalized, but it should just be a
12269 // qualified version of ParamD, so move the qualifiers to that.
12271 Qs.strip(Param);
12272 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12273 assert(S.Context.hasSameType(Param, NonCanonParam));
12274
12275 // Arg has also been canonicalized, but there's nothing we can do
12276 // about that. It also doesn't matter as much, because it won't
12277 // have any template parameters in it (because deduction isn't
12278 // done on dependent types).
12279 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12280
12281 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12282 << ParamD->getDeclName() << Arg << NonCanonParam;
12283 MaybeEmitInheritedConstructorNote(S, Found);
12284 return;
12285 }
12286
12288 assert(ParamD && "no parameter found for inconsistent deduction result");
12289 int which = 0;
12290 if (isa<TemplateTypeParmDecl>(ParamD))
12291 which = 0;
12292 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12293 // Deduction might have failed because we deduced arguments of two
12294 // different types for a non-type template parameter.
12295 // FIXME: Use a different TDK value for this.
12296 QualType T1 =
12297 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12298 QualType T2 =
12299 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12300 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12301 S.Diag(Templated->getLocation(),
12302 diag::note_ovl_candidate_inconsistent_deduction_types)
12303 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12304 << *DeductionFailure.getSecondArg() << T2;
12305 MaybeEmitInheritedConstructorNote(S, Found);
12306 return;
12307 }
12308
12309 which = 1;
12310 } else {
12311 which = 2;
12312 }
12313
12314 // Tweak the diagnostic if the problem is that we deduced packs of
12315 // different arities. We'll print the actual packs anyway in case that
12316 // includes additional useful information.
12317 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12318 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12319 DeductionFailure.getFirstArg()->pack_size() !=
12320 DeductionFailure.getSecondArg()->pack_size()) {
12321 which = 3;
12322 }
12323
12324 S.Diag(Templated->getLocation(),
12325 diag::note_ovl_candidate_inconsistent_deduction)
12326 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12327 << *DeductionFailure.getSecondArg();
12328 MaybeEmitInheritedConstructorNote(S, Found);
12329 return;
12330 }
12331
12333 assert(ParamD && "no parameter found for invalid explicit arguments");
12334 if (ParamD->getDeclName())
12335 S.Diag(Templated->getLocation(),
12336 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12337 << ParamD->getDeclName();
12338 else {
12339 int index = 0;
12340 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12341 index = TTP->getIndex();
12342 else if (NonTypeTemplateParmDecl *NTTP
12343 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12344 index = NTTP->getIndex();
12345 else
12346 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12347 S.Diag(Templated->getLocation(),
12348 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12349 << (index + 1);
12350 }
12351 MaybeEmitInheritedConstructorNote(S, Found);
12352 return;
12353
12355 // Format the template argument list into the argument string.
12356 SmallString<128> TemplateArgString;
12357 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12358 TemplateArgString = " ";
12359 TemplateArgString += S.getTemplateArgumentBindingsText(
12360 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12361 if (TemplateArgString.size() == 1)
12362 TemplateArgString.clear();
12363 S.Diag(Templated->getLocation(),
12364 diag::note_ovl_candidate_unsatisfied_constraints)
12365 << TemplateArgString;
12366
12368 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12369 return;
12370 }
12373 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12374 return;
12375
12377 S.Diag(Templated->getLocation(),
12378 diag::note_ovl_candidate_instantiation_depth);
12379 MaybeEmitInheritedConstructorNote(S, Found);
12380 return;
12381
12383 // Format the template argument list into the argument string.
12384 SmallString<128> TemplateArgString;
12385 if (TemplateArgumentList *Args =
12386 DeductionFailure.getTemplateArgumentList()) {
12387 TemplateArgString = " ";
12388 TemplateArgString += S.getTemplateArgumentBindingsText(
12389 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12390 if (TemplateArgString.size() == 1)
12391 TemplateArgString.clear();
12392 }
12393
12394 // If this candidate was disabled by enable_if, say so.
12395 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12396 if (PDiag && PDiag->second.getDiagID() ==
12397 diag::err_typename_nested_not_found_enable_if) {
12398 // FIXME: Use the source range of the condition, and the fully-qualified
12399 // name of the enable_if template. These are both present in PDiag.
12400 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12401 << "'enable_if'" << TemplateArgString;
12402 return;
12403 }
12404
12405 // We found a specific requirement that disabled the enable_if.
12406 if (PDiag && PDiag->second.getDiagID() ==
12407 diag::err_typename_nested_not_found_requirement) {
12408 S.Diag(Templated->getLocation(),
12409 diag::note_ovl_candidate_disabled_by_requirement)
12410 << PDiag->second.getStringArg(0) << TemplateArgString;
12411 return;
12412 }
12413
12414 // Format the SFINAE diagnostic into the argument string.
12415 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12416 // formatted message in another diagnostic.
12417 SmallString<128> SFINAEArgString;
12418 SourceRange R;
12419 if (PDiag) {
12420 SFINAEArgString = ": ";
12421 R = SourceRange(PDiag->first, PDiag->first);
12422 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12423 }
12424
12425 S.Diag(Templated->getLocation(),
12426 diag::note_ovl_candidate_substitution_failure)
12427 << TemplateArgString << SFINAEArgString << R;
12428 MaybeEmitInheritedConstructorNote(S, Found);
12429 return;
12430 }
12431
12434 // Format the template argument list into the argument string.
12435 SmallString<128> TemplateArgString;
12436 if (TemplateArgumentList *Args =
12437 DeductionFailure.getTemplateArgumentList()) {
12438 TemplateArgString = " ";
12439 TemplateArgString += S.getTemplateArgumentBindingsText(
12440 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12441 if (TemplateArgString.size() == 1)
12442 TemplateArgString.clear();
12443 }
12444
12445 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12446 << (*DeductionFailure.getCallArgIndex() + 1)
12447 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12448 << TemplateArgString
12449 << (DeductionFailure.getResult() ==
12451 break;
12452 }
12453
12455 // FIXME: Provide a source location to indicate what we couldn't match.
12456 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12457 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12458 if (FirstTA.getKind() == TemplateArgument::Template &&
12459 SecondTA.getKind() == TemplateArgument::Template) {
12460 TemplateName FirstTN = FirstTA.getAsTemplate();
12461 TemplateName SecondTN = SecondTA.getAsTemplate();
12462 if (FirstTN.getKind() == TemplateName::Template &&
12463 SecondTN.getKind() == TemplateName::Template) {
12464 if (FirstTN.getAsTemplateDecl()->getName() ==
12465 SecondTN.getAsTemplateDecl()->getName()) {
12466 // FIXME: This fixes a bad diagnostic where both templates are named
12467 // the same. This particular case is a bit difficult since:
12468 // 1) It is passed as a string to the diagnostic printer.
12469 // 2) The diagnostic printer only attempts to find a better
12470 // name for types, not decls.
12471 // Ideally, this should folded into the diagnostic printer.
12472 S.Diag(Templated->getLocation(),
12473 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12474 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12475 return;
12476 }
12477 }
12478 }
12479
12480 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12482 return;
12483
12484 // FIXME: For generic lambda parameters, check if the function is a lambda
12485 // call operator, and if so, emit a prettier and more informative
12486 // diagnostic that mentions 'auto' and lambda in addition to
12487 // (or instead of?) the canonical template type parameters.
12488 S.Diag(Templated->getLocation(),
12489 diag::note_ovl_candidate_non_deduced_mismatch)
12490 << FirstTA << SecondTA;
12491 return;
12492 }
12493 // TODO: diagnose these individually, then kill off
12494 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12496 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12497 MaybeEmitInheritedConstructorNote(S, Found);
12498 return;
12500 S.Diag(Templated->getLocation(),
12501 diag::note_cuda_ovl_candidate_target_mismatch);
12502 return;
12503 }
12504}
12505
12506/// Diagnose a failed template-argument deduction, for function calls.
12508 unsigned NumArgs,
12509 bool TakingCandidateAddress) {
12510 assert(Cand->Function && "Candidate must be a function");
12511 FunctionDecl *Fn = Cand->Function;
12515 if (CheckArityMismatch(S, Cand, NumArgs))
12516 return;
12517 }
12518 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12519 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12520}
12521
12522/// CUDA: diagnose an invalid call across targets.
12524 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12525 assert(Cand->Function && "Candidate must be a Function.");
12526 FunctionDecl *Callee = Cand->Function;
12527
12528 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12529 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12530
12531 std::string FnDesc;
12532 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12533 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12534 Cand->getRewriteKind(), FnDesc);
12535
12536 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12537 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12538 << FnDesc /* Ignored */
12539 << CalleeTarget << CallerTarget;
12540
12541 // This could be an implicit constructor for which we could not infer the
12542 // target due to a collsion. Diagnose that case.
12543 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12544 if (Meth != nullptr && Meth->isImplicit()) {
12545 CXXRecordDecl *ParentClass = Meth->getParent();
12547
12548 switch (FnKindPair.first) {
12549 default:
12550 return;
12551 case oc_implicit_default_constructor:
12553 break;
12554 case oc_implicit_copy_constructor:
12556 break;
12557 case oc_implicit_move_constructor:
12559 break;
12560 case oc_implicit_copy_assignment:
12562 break;
12563 case oc_implicit_move_assignment:
12565 break;
12566 };
12567
12568 bool ConstRHS = false;
12569 if (Meth->getNumParams()) {
12570 if (const ReferenceType *RT =
12571 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12572 ConstRHS = RT->getPointeeType().isConstQualified();
12573 }
12574 }
12575
12576 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12577 /* ConstRHS */ ConstRHS,
12578 /* Diagnose */ true);
12579 }
12580}
12581
12583 assert(Cand->Function && "Candidate must be a function");
12584 FunctionDecl *Callee = Cand->Function;
12585 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12586
12587 S.Diag(Callee->getLocation(),
12588 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12589 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12590}
12591
12593 assert(Cand->Function && "Candidate must be a function");
12594 FunctionDecl *Fn = Cand->Function;
12596 assert(ES.isExplicit() && "not an explicit candidate");
12597
12598 unsigned Kind;
12599 switch (Fn->getDeclKind()) {
12600 case Decl::Kind::CXXConstructor:
12601 Kind = 0;
12602 break;
12603 case Decl::Kind::CXXConversion:
12604 Kind = 1;
12605 break;
12606 case Decl::Kind::CXXDeductionGuide:
12607 Kind = Fn->isImplicit() ? 0 : 2;
12608 break;
12609 default:
12610 llvm_unreachable("invalid Decl");
12611 }
12612
12613 // Note the location of the first (in-class) declaration; a redeclaration
12614 // (particularly an out-of-class definition) will typically lack the
12615 // 'explicit' specifier.
12616 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12617 FunctionDecl *First = Fn->getFirstDecl();
12618 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12619 First = Pattern->getFirstDecl();
12620
12621 S.Diag(First->getLocation(),
12622 diag::note_ovl_candidate_explicit)
12623 << Kind << (ES.getExpr() ? 1 : 0)
12624 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12625}
12626
12628 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12629 if (!DG)
12630 return;
12631 TemplateDecl *OriginTemplate =
12633 // We want to always print synthesized deduction guides for type aliases.
12634 // They would retain the explicit bit of the corresponding constructor.
12635 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12636 return;
12637 std::string FunctionProto;
12638 llvm::raw_string_ostream OS(FunctionProto);
12639 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12640 if (!Template) {
12641 // This also could be an instantiation. Find out the primary template.
12642 FunctionDecl *Pattern =
12643 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12644 if (!Pattern) {
12645 // The implicit deduction guide is built on an explicit non-template
12646 // deduction guide. Currently, this might be the case only for type
12647 // aliases.
12648 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12649 // gets merged.
12650 assert(OriginTemplate->isTypeAlias() &&
12651 "Non-template implicit deduction guides are only possible for "
12652 "type aliases");
12653 DG->print(OS);
12654 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12655 << FunctionProto;
12656 return;
12657 }
12659 assert(Template && "Cannot find the associated function template of "
12660 "CXXDeductionGuideDecl?");
12661 }
12662 Template->print(OS);
12663 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12664 << FunctionProto;
12665}
12666
12667/// Generates a 'note' diagnostic for an overload candidate. We've
12668/// already generated a primary error at the call site.
12669///
12670/// It really does need to be a single diagnostic with its caret
12671/// pointed at the candidate declaration. Yes, this creates some
12672/// major challenges of technical writing. Yes, this makes pointing
12673/// out problems with specific arguments quite awkward. It's still
12674/// better than generating twenty screens of text for every failed
12675/// overload.
12676///
12677/// It would be great to be able to express per-candidate problems
12678/// more richly for those diagnostic clients that cared, but we'd
12679/// still have to be just as careful with the default diagnostics.
12680/// \param CtorDestAS Addr space of object being constructed (for ctor
12681/// candidates only).
12683 unsigned NumArgs,
12684 bool TakingCandidateAddress,
12685 LangAS CtorDestAS = LangAS::Default) {
12686 assert(Cand->Function && "Candidate must be a function");
12687 FunctionDecl *Fn = Cand->Function;
12689 return;
12690
12691 // There is no physical candidate declaration to point to for OpenCL builtins.
12692 // Except for failed conversions, the notes are identical for each candidate,
12693 // so do not generate such notes.
12694 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12696 return;
12697
12698 // Skip implicit member functions when trying to resolve
12699 // the address of a an overload set for a function pointer.
12700 if (Cand->TookAddressOfOverload &&
12701 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12702 return;
12703
12704 // Note deleted candidates, but only if they're viable.
12705 if (Cand->Viable) {
12706 if (Fn->isDeleted()) {
12707 std::string FnDesc;
12708 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12709 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12710 Cand->getRewriteKind(), FnDesc);
12711
12712 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12713 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12714 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12716 return;
12717 }
12718
12719 // We don't really have anything else to say about viable candidates.
12720 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12721 return;
12722 }
12723
12724 // If this is a synthesized deduction guide we're deducing against, add a note
12725 // for it. These deduction guides are not explicitly spelled in the source
12726 // code, so simply printing a deduction failure note mentioning synthesized
12727 // template parameters or pointing to the header of the surrounding RecordDecl
12728 // would be confusing.
12729 //
12730 // We prefer adding such notes at the end of the deduction failure because
12731 // duplicate code snippets appearing in the diagnostic would likely become
12732 // noisy.
12733 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12734
12735 switch (Cand->FailureKind) {
12738 return DiagnoseArityMismatch(S, Cand, NumArgs);
12739
12741 return DiagnoseBadDeduction(S, Cand, NumArgs,
12742 TakingCandidateAddress);
12743
12745 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12746 << (Fn->getPrimaryTemplate() ? 1 : 0);
12747 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12748 return;
12749 }
12750
12752 Qualifiers QualsForPrinting;
12753 QualsForPrinting.setAddressSpace(CtorDestAS);
12754 S.Diag(Fn->getLocation(),
12755 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12756 << QualsForPrinting;
12757 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12758 return;
12759 }
12760
12764 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12765
12767 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12768 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12769 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12770 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12771
12772 // FIXME: this currently happens when we're called from SemaInit
12773 // when user-conversion overload fails. Figure out how to handle
12774 // those conditions and diagnose them well.
12775 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12776 }
12777
12779 return DiagnoseBadTarget(S, Cand);
12780
12781 case ovl_fail_enable_if:
12782 return DiagnoseFailedEnableIfAttr(S, Cand);
12783
12784 case ovl_fail_explicit:
12785 return DiagnoseFailedExplicitSpec(S, Cand);
12786
12788 // It's generally not interesting to note copy/move constructors here.
12789 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12790 return;
12791 S.Diag(Fn->getLocation(),
12792 diag::note_ovl_candidate_inherited_constructor_slice)
12793 << (Fn->getPrimaryTemplate() ? 1 : 0)
12794 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12795 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12796 return;
12797
12799 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12800 (void)Available;
12801 assert(!Available);
12802 break;
12803 }
12805 // Do nothing, these should simply be ignored.
12806 break;
12807
12809 std::string FnDesc;
12810 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12811 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12812 Cand->getRewriteKind(), FnDesc);
12813
12814 S.Diag(Fn->getLocation(),
12815 diag::note_ovl_candidate_constraints_not_satisfied)
12816 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12817 << FnDesc /* Ignored */;
12818 ConstraintSatisfaction Satisfaction;
12819 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12820 /*ForOverloadResolution=*/true))
12821 break;
12822 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12823 }
12824 }
12825}
12826
12829 return;
12830
12831 // Desugar the type of the surrogate down to a function type,
12832 // retaining as many typedefs as possible while still showing
12833 // the function type (and, therefore, its parameter types).
12834 QualType FnType = Cand->Surrogate->getConversionType();
12835 bool isLValueReference = false;
12836 bool isRValueReference = false;
12837 bool isPointer = false;
12838 if (const LValueReferenceType *FnTypeRef =
12839 FnType->getAs<LValueReferenceType>()) {
12840 FnType = FnTypeRef->getPointeeType();
12841 isLValueReference = true;
12842 } else if (const RValueReferenceType *FnTypeRef =
12843 FnType->getAs<RValueReferenceType>()) {
12844 FnType = FnTypeRef->getPointeeType();
12845 isRValueReference = true;
12846 }
12847 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12848 FnType = FnTypePtr->getPointeeType();
12849 isPointer = true;
12850 }
12851 // Desugar down to a function type.
12852 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12853 // Reconstruct the pointer/reference as appropriate.
12854 if (isPointer) FnType = S.Context.getPointerType(FnType);
12855 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12856 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12857
12858 if (!Cand->Viable &&
12860 S.Diag(Cand->Surrogate->getLocation(),
12861 diag::note_ovl_surrogate_constraints_not_satisfied)
12862 << Cand->Surrogate;
12863 ConstraintSatisfaction Satisfaction;
12864 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12865 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12866 } else {
12867 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12868 << FnType;
12869 }
12870}
12871
12872static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12873 SourceLocation OpLoc,
12874 OverloadCandidate *Cand) {
12875 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12876 std::string TypeStr("operator");
12877 TypeStr += Opc;
12878 TypeStr += "(";
12879 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12880 if (Cand->Conversions.size() == 1) {
12881 TypeStr += ")";
12882 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12883 } else {
12884 TypeStr += ", ";
12885 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12886 TypeStr += ")";
12887 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12888 }
12889}
12890
12892 OverloadCandidate *Cand) {
12893 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12894 if (ICS.isBad()) break; // all meaningless after first invalid
12895 if (!ICS.isAmbiguous()) continue;
12896
12898 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12899 }
12900}
12901
12903 if (Cand->Function)
12904 return Cand->Function->getLocation();
12905 if (Cand->IsSurrogate)
12906 return Cand->Surrogate->getLocation();
12907 return SourceLocation();
12908}
12909
12910static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12911 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12915 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12916
12920 return 1;
12921
12924 return 2;
12925
12933 return 3;
12934
12936 return 4;
12937
12939 return 5;
12940
12943 return 6;
12944 }
12945 llvm_unreachable("Unhandled deduction result");
12946}
12947
12948namespace {
12949
12950struct CompareOverloadCandidatesForDisplay {
12951 Sema &S;
12952 SourceLocation Loc;
12953 size_t NumArgs;
12955
12956 CompareOverloadCandidatesForDisplay(
12957 Sema &S, SourceLocation Loc, size_t NArgs,
12959 : S(S), NumArgs(NArgs), CSK(CSK) {}
12960
12961 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12962 // If there are too many or too few arguments, that's the high-order bit we
12963 // want to sort by, even if the immediate failure kind was something else.
12964 if (C->FailureKind == ovl_fail_too_many_arguments ||
12965 C->FailureKind == ovl_fail_too_few_arguments)
12966 return static_cast<OverloadFailureKind>(C->FailureKind);
12967
12968 if (C->Function) {
12969 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12971 if (NumArgs < C->Function->getMinRequiredArguments())
12973 }
12974
12975 return static_cast<OverloadFailureKind>(C->FailureKind);
12976 }
12977
12978 bool operator()(const OverloadCandidate *L,
12979 const OverloadCandidate *R) {
12980 // Fast-path this check.
12981 if (L == R) return false;
12982
12983 // Order first by viability.
12984 if (L->Viable) {
12985 if (!R->Viable) return true;
12986
12987 if (int Ord = CompareConversions(*L, *R))
12988 return Ord < 0;
12989 // Use other tie breakers.
12990 } else if (R->Viable)
12991 return false;
12992
12993 assert(L->Viable == R->Viable);
12994
12995 // Criteria by which we can sort non-viable candidates:
12996 if (!L->Viable) {
12997 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12998 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12999
13000 // 1. Arity mismatches come after other candidates.
13001 if (LFailureKind == ovl_fail_too_many_arguments ||
13002 LFailureKind == ovl_fail_too_few_arguments) {
13003 if (RFailureKind == ovl_fail_too_many_arguments ||
13004 RFailureKind == ovl_fail_too_few_arguments) {
13005 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13006 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13007 if (LDist == RDist) {
13008 if (LFailureKind == RFailureKind)
13009 // Sort non-surrogates before surrogates.
13010 return !L->IsSurrogate && R->IsSurrogate;
13011 // Sort candidates requiring fewer parameters than there were
13012 // arguments given after candidates requiring more parameters
13013 // than there were arguments given.
13014 return LFailureKind == ovl_fail_too_many_arguments;
13015 }
13016 return LDist < RDist;
13017 }
13018 return false;
13019 }
13020 if (RFailureKind == ovl_fail_too_many_arguments ||
13021 RFailureKind == ovl_fail_too_few_arguments)
13022 return true;
13023
13024 // 2. Bad conversions come first and are ordered by the number
13025 // of bad conversions and quality of good conversions.
13026 if (LFailureKind == ovl_fail_bad_conversion) {
13027 if (RFailureKind != ovl_fail_bad_conversion)
13028 return true;
13029
13030 // The conversion that can be fixed with a smaller number of changes,
13031 // comes first.
13032 unsigned numLFixes = L->Fix.NumConversionsFixed;
13033 unsigned numRFixes = R->Fix.NumConversionsFixed;
13034 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13035 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13036 if (numLFixes != numRFixes) {
13037 return numLFixes < numRFixes;
13038 }
13039
13040 // If there's any ordering between the defined conversions...
13041 if (int Ord = CompareConversions(*L, *R))
13042 return Ord < 0;
13043 } else if (RFailureKind == ovl_fail_bad_conversion)
13044 return false;
13045
13046 if (LFailureKind == ovl_fail_bad_deduction) {
13047 if (RFailureKind != ovl_fail_bad_deduction)
13048 return true;
13049
13051 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13052 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13053 if (LRank != RRank)
13054 return LRank < RRank;
13055 }
13056 } else if (RFailureKind == ovl_fail_bad_deduction)
13057 return false;
13058
13059 // TODO: others?
13060 }
13061
13062 // Sort everything else by location.
13063 SourceLocation LLoc = GetLocationForCandidate(L);
13064 SourceLocation RLoc = GetLocationForCandidate(R);
13065
13066 // Put candidates without locations (e.g. builtins) at the end.
13067 if (LLoc.isValid() && RLoc.isValid())
13068 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13069 if (LLoc.isValid() && !RLoc.isValid())
13070 return true;
13071 if (RLoc.isValid() && !LLoc.isValid())
13072 return false;
13073 assert(!LLoc.isValid() && !RLoc.isValid());
13074 // For builtins and other functions without locations, fallback to the order
13075 // in which they were added into the candidate set.
13076 return L < R;
13077 }
13078
13079private:
13080 struct ConversionSignals {
13081 unsigned KindRank = 0;
13083
13084 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13085 ConversionSignals Sig;
13086 Sig.KindRank = Seq.getKindRank();
13087 if (Seq.isStandard())
13088 Sig.Rank = Seq.Standard.getRank();
13089 else if (Seq.isUserDefined())
13090 Sig.Rank = Seq.UserDefined.After.getRank();
13091 // We intend StaticObjectArgumentConversion to compare the same as
13092 // StandardConversion with ICR_ExactMatch rank.
13093 return Sig;
13094 }
13095
13096 static ConversionSignals ForObjectArgument() {
13097 // We intend StaticObjectArgumentConversion to compare the same as
13098 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13099 return {};
13100 }
13101 };
13102
13103 // Returns -1 if conversions in L are considered better.
13104 // 0 if they are considered indistinguishable.
13105 // 1 if conversions in R are better.
13106 int CompareConversions(const OverloadCandidate &L,
13107 const OverloadCandidate &R) {
13108 // We cannot use `isBetterOverloadCandidate` because it is defined
13109 // according to the C++ standard and provides a partial order, but we need
13110 // a total order as this function is used in sort.
13111 assert(L.Conversions.size() == R.Conversions.size());
13112 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13113 auto LS = L.IgnoreObjectArgument && I == 0
13114 ? ConversionSignals::ForObjectArgument()
13115 : ConversionSignals::ForSequence(L.Conversions[I]);
13116 auto RS = R.IgnoreObjectArgument
13117 ? ConversionSignals::ForObjectArgument()
13118 : ConversionSignals::ForSequence(R.Conversions[I]);
13119 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13120 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13121 ? -1
13122 : 1;
13123 }
13124 // FIXME: find a way to compare templates for being more or less
13125 // specialized that provides a strict weak ordering.
13126 return 0;
13127 }
13128};
13129}
13130
13131/// CompleteNonViableCandidate - Normally, overload resolution only
13132/// computes up to the first bad conversion. Produces the FixIt set if
13133/// possible.
13134static void
13136 ArrayRef<Expr *> Args,
13138 assert(!Cand->Viable);
13139
13140 // Don't do anything on failures other than bad conversion.
13142 return;
13143
13144 // We only want the FixIts if all the arguments can be corrected.
13145 bool Unfixable = false;
13146 // Use a implicit copy initialization to check conversion fixes.
13148
13149 // Attempt to fix the bad conversion.
13150 unsigned ConvCount = Cand->Conversions.size();
13151 for (unsigned ConvIdx =
13152 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13153 : 0);
13154 /**/; ++ConvIdx) {
13155 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13156 if (Cand->Conversions[ConvIdx].isInitialized() &&
13157 Cand->Conversions[ConvIdx].isBad()) {
13158 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13159 break;
13160 }
13161 }
13162
13163 // FIXME: this should probably be preserved from the overload
13164 // operation somehow.
13165 bool SuppressUserConversions = false;
13166
13167 unsigned ConvIdx = 0;
13168 unsigned ArgIdx = 0;
13169 ArrayRef<QualType> ParamTypes;
13170 bool Reversed = Cand->isReversed();
13171
13172 if (Cand->IsSurrogate) {
13173 QualType ConvType
13175 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13176 ConvType = ConvPtrType->getPointeeType();
13177 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13178 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13179 ConvIdx = 1;
13180 } else if (Cand->Function) {
13181 ParamTypes =
13182 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13183 if (isa<CXXMethodDecl>(Cand->Function) &&
13186 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13187 ConvIdx = 1;
13189 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13191 OO_Subscript)
13192 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13193 ArgIdx = 1;
13194 }
13195 } else {
13196 // Builtin operator.
13197 assert(ConvCount <= 3);
13198 ParamTypes = Cand->BuiltinParamTypes;
13199 }
13200
13201 // Fill in the rest of the conversions.
13202 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13203 ConvIdx != ConvCount && ArgIdx < Args.size();
13204 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13205 if (Cand->Conversions[ConvIdx].isInitialized()) {
13206 // We've already checked this conversion.
13207 } else if (ParamIdx < ParamTypes.size()) {
13208 if (ParamTypes[ParamIdx]->isDependentType())
13209 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13210 Args[ArgIdx]->getType());
13211 else {
13212 Cand->Conversions[ConvIdx] =
13213 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13214 SuppressUserConversions,
13215 /*InOverloadResolution=*/true,
13216 /*AllowObjCWritebackConversion=*/
13217 S.getLangOpts().ObjCAutoRefCount);
13218 // Store the FixIt in the candidate if it exists.
13219 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13220 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13221 }
13222 } else
13223 Cand->Conversions[ConvIdx].setEllipsis();
13224 }
13225}
13226
13229 SourceLocation OpLoc,
13230 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13231
13233
13234 // Sort the candidates by viability and position. Sorting directly would
13235 // be prohibitive, so we make a set of pointers and sort those.
13237 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13238 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13239 Cand != LastCand; ++Cand) {
13240 if (!Filter(*Cand))
13241 continue;
13242 switch (OCD) {
13243 case OCD_AllCandidates:
13244 if (!Cand->Viable) {
13245 if (!Cand->Function && !Cand->IsSurrogate) {
13246 // This a non-viable builtin candidate. We do not, in general,
13247 // want to list every possible builtin candidate.
13248 continue;
13249 }
13250 CompleteNonViableCandidate(S, Cand, Args, Kind);
13251 }
13252 break;
13253
13255 if (!Cand->Viable)
13256 continue;
13257 break;
13258
13260 if (!Cand->Best)
13261 continue;
13262 break;
13263 }
13264
13265 Cands.push_back(Cand);
13266 }
13267
13268 llvm::stable_sort(
13269 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13270
13271 return Cands;
13272}
13273
13275 SourceLocation OpLoc) {
13276 bool DeferHint = false;
13277 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13278 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13279 // host device candidates.
13280 auto WrongSidedCands =
13281 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13282 return (Cand.Viable == false &&
13284 (Cand.Function &&
13285 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13286 Cand.Function->template hasAttr<CUDADeviceAttr>());
13287 });
13288 DeferHint = !WrongSidedCands.empty();
13289 }
13290 return DeferHint;
13291}
13292
13293/// When overload resolution fails, prints diagnostic messages containing the
13294/// candidates in the candidate set.
13297 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13298 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13299
13300 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13301
13302 {
13303 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13304 S.Diag(PD.first, PD.second);
13305 }
13306
13307 // In WebAssembly we don't want to emit further diagnostics if a table is
13308 // passed as an argument to a function.
13309 bool NoteCands = true;
13310 for (const Expr *Arg : Args) {
13311 if (Arg->getType()->isWebAssemblyTableType())
13312 NoteCands = false;
13313 }
13314
13315 if (NoteCands)
13316 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13317
13318 if (OCD == OCD_AmbiguousCandidates)
13320 {Candidates.begin(), Candidates.end()});
13321}
13322
13325 StringRef Opc, SourceLocation OpLoc) {
13326 bool ReportedAmbiguousConversions = false;
13327
13328 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13329 unsigned CandsShown = 0;
13330 auto I = Cands.begin(), E = Cands.end();
13331 for (; I != E; ++I) {
13332 OverloadCandidate *Cand = *I;
13333
13334 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13335 ShowOverloads == Ovl_Best) {
13336 break;
13337 }
13338 ++CandsShown;
13339
13340 if (Cand->Function)
13341 NoteFunctionCandidate(S, Cand, Args.size(),
13342 Kind == CSK_AddressOfOverloadSet, DestAS);
13343 else if (Cand->IsSurrogate)
13344 NoteSurrogateCandidate(S, Cand);
13345 else {
13346 assert(Cand->Viable &&
13347 "Non-viable built-in candidates are not added to Cands.");
13348 // Generally we only see ambiguities including viable builtin
13349 // operators if overload resolution got screwed up by an
13350 // ambiguous user-defined conversion.
13351 //
13352 // FIXME: It's quite possible for different conversions to see
13353 // different ambiguities, though.
13354 if (!ReportedAmbiguousConversions) {
13355 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13356 ReportedAmbiguousConversions = true;
13357 }
13358
13359 // If this is a viable builtin, print it.
13360 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13361 }
13362 }
13363
13364 // Inform S.Diags that we've shown an overload set with N elements. This may
13365 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13366 S.Diags.overloadCandidatesShown(CandsShown);
13367
13368 if (I != E) {
13369 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13370 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13371 }
13372}
13373
13374static SourceLocation
13376 return Cand->Specialization ? Cand->Specialization->getLocation()
13377 : SourceLocation();
13378}
13379
13380namespace {
13381struct CompareTemplateSpecCandidatesForDisplay {
13382 Sema &S;
13383 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13384
13385 bool operator()(const TemplateSpecCandidate *L,
13386 const TemplateSpecCandidate *R) {
13387 // Fast-path this check.
13388 if (L == R)
13389 return false;
13390
13391 // Assuming that both candidates are not matches...
13392
13393 // Sort by the ranking of deduction failures.
13397
13398 // Sort everything else by location.
13399 SourceLocation LLoc = GetLocationForCandidate(L);
13400 SourceLocation RLoc = GetLocationForCandidate(R);
13401
13402 // Put candidates without locations (e.g. builtins) at the end.
13403 if (LLoc.isInvalid())
13404 return false;
13405 if (RLoc.isInvalid())
13406 return true;
13407
13408 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13409 }
13410};
13411}
13412
13413/// Diagnose a template argument deduction failure.
13414/// We are treating these failures as overload failures due to bad
13415/// deductions.
13417 bool ForTakingAddress) {
13419 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13420}
13421
13422void TemplateSpecCandidateSet::destroyCandidates() {
13423 for (iterator i = begin(), e = end(); i != e; ++i) {
13424 i->DeductionFailure.Destroy();
13425 }
13426}
13427
13429 destroyCandidates();
13430 Candidates.clear();
13431}
13432
13433/// NoteCandidates - When no template specialization match is found, prints
13434/// diagnostic messages containing the non-matching specializations that form
13435/// the candidate set.
13436/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13437/// OCD == OCD_AllCandidates and Cand->Viable == false.
13439 // Sort the candidates by position (assuming no candidate is a match).
13440 // Sorting directly would be prohibitive, so we make a set of pointers
13441 // and sort those.
13443 Cands.reserve(size());
13444 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13445 if (Cand->Specialization)
13446 Cands.push_back(Cand);
13447 // Otherwise, this is a non-matching builtin candidate. We do not,
13448 // in general, want to list every possible builtin candidate.
13449 }
13450
13451 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13452
13453 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13454 // for generalization purposes (?).
13455 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13456
13458 unsigned CandsShown = 0;
13459 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13460 TemplateSpecCandidate *Cand = *I;
13461
13462 // Set an arbitrary limit on the number of candidates we'll spam
13463 // the user with. FIXME: This limit should depend on details of the
13464 // candidate list.
13465 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13466 break;
13467 ++CandsShown;
13468
13469 assert(Cand->Specialization &&
13470 "Non-matching built-in candidates are not added to Cands.");
13471 Cand->NoteDeductionFailure(S, ForTakingAddress);
13472 }
13473
13474 if (I != E)
13475 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13476}
13477
13478// [PossiblyAFunctionType] --> [Return]
13479// NonFunctionType --> NonFunctionType
13480// R (A) --> R(A)
13481// R (*)(A) --> R (A)
13482// R (&)(A) --> R (A)
13483// R (S::*)(A) --> R (A)
13485 QualType Ret = PossiblyAFunctionType;
13486 if (const PointerType *ToTypePtr =
13487 PossiblyAFunctionType->getAs<PointerType>())
13488 Ret = ToTypePtr->getPointeeType();
13489 else if (const ReferenceType *ToTypeRef =
13490 PossiblyAFunctionType->getAs<ReferenceType>())
13491 Ret = ToTypeRef->getPointeeType();
13492 else if (const MemberPointerType *MemTypePtr =
13493 PossiblyAFunctionType->getAs<MemberPointerType>())
13494 Ret = MemTypePtr->getPointeeType();
13495 Ret =
13496 Context.getCanonicalType(Ret).getUnqualifiedType();
13497 return Ret;
13498}
13499
13501 bool Complain = true) {
13502 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13503 S.DeduceReturnType(FD, Loc, Complain))
13504 return true;
13505
13506 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13507 if (S.getLangOpts().CPlusPlus17 &&
13508 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13509 !S.ResolveExceptionSpec(Loc, FPT))
13510 return true;
13511
13512 return false;
13513}
13514
13515namespace {
13516// A helper class to help with address of function resolution
13517// - allows us to avoid passing around all those ugly parameters
13518class AddressOfFunctionResolver {
13519 Sema& S;
13520 Expr* SourceExpr;
13521 const QualType& TargetType;
13522 QualType TargetFunctionType; // Extracted function type from target type
13523
13524 bool Complain;
13525 //DeclAccessPair& ResultFunctionAccessPair;
13526 ASTContext& Context;
13527
13528 bool TargetTypeIsNonStaticMemberFunction;
13529 bool FoundNonTemplateFunction;
13530 bool StaticMemberFunctionFromBoundPointer;
13531 bool HasComplained;
13532
13533 OverloadExpr::FindResult OvlExprInfo;
13534 OverloadExpr *OvlExpr;
13535 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13536 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13537 TemplateSpecCandidateSet FailedCandidates;
13538
13539public:
13540 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13541 const QualType &TargetType, bool Complain)
13542 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13543 Complain(Complain), Context(S.getASTContext()),
13544 TargetTypeIsNonStaticMemberFunction(
13545 !!TargetType->getAs<MemberPointerType>()),
13546 FoundNonTemplateFunction(false),
13547 StaticMemberFunctionFromBoundPointer(false),
13548 HasComplained(false),
13549 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13550 OvlExpr(OvlExprInfo.Expression),
13551 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13552 ExtractUnqualifiedFunctionTypeFromTargetType();
13553
13554 if (TargetFunctionType->isFunctionType()) {
13555 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13556 if (!UME->isImplicitAccess() &&
13558 StaticMemberFunctionFromBoundPointer = true;
13559 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13560 DeclAccessPair dap;
13561 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13562 OvlExpr, false, &dap)) {
13563 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13564 if (!Method->isStatic()) {
13565 // If the target type is a non-function type and the function found
13566 // is a non-static member function, pretend as if that was the
13567 // target, it's the only possible type to end up with.
13568 TargetTypeIsNonStaticMemberFunction = true;
13569
13570 // And skip adding the function if its not in the proper form.
13571 // We'll diagnose this due to an empty set of functions.
13572 if (!OvlExprInfo.HasFormOfMemberPointer)
13573 return;
13574 }
13575
13576 Matches.push_back(std::make_pair(dap, Fn));
13577 }
13578 return;
13579 }
13580
13581 if (OvlExpr->hasExplicitTemplateArgs())
13582 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13583
13584 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13585 // C++ [over.over]p4:
13586 // If more than one function is selected, [...]
13587 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13588 if (FoundNonTemplateFunction) {
13589 EliminateAllTemplateMatches();
13590 EliminateLessPartialOrderingConstrainedMatches();
13591 } else
13592 EliminateAllExceptMostSpecializedTemplate();
13593 }
13594 }
13595
13596 if (S.getLangOpts().CUDA && Matches.size() > 1)
13597 EliminateSuboptimalCudaMatches();
13598 }
13599
13600 bool hasComplained() const { return HasComplained; }
13601
13602private:
13603 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13604 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13605 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13606 }
13607
13608 /// \return true if A is considered a better overload candidate for the
13609 /// desired type than B.
13610 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13611 // If A doesn't have exactly the correct type, we don't want to classify it
13612 // as "better" than anything else. This way, the user is required to
13613 // disambiguate for us if there are multiple candidates and no exact match.
13614 return candidateHasExactlyCorrectType(A) &&
13615 (!candidateHasExactlyCorrectType(B) ||
13616 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13617 }
13618
13619 /// \return true if we were able to eliminate all but one overload candidate,
13620 /// false otherwise.
13621 bool eliminiateSuboptimalOverloadCandidates() {
13622 // Same algorithm as overload resolution -- one pass to pick the "best",
13623 // another pass to be sure that nothing is better than the best.
13624 auto Best = Matches.begin();
13625 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13626 if (isBetterCandidate(I->second, Best->second))
13627 Best = I;
13628
13629 const FunctionDecl *BestFn = Best->second;
13630 auto IsBestOrInferiorToBest = [this, BestFn](
13631 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13632 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13633 };
13634
13635 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13636 // option, so we can potentially give the user a better error
13637 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13638 return false;
13639 Matches[0] = *Best;
13640 Matches.resize(1);
13641 return true;
13642 }
13643
13644 bool isTargetTypeAFunction() const {
13645 return TargetFunctionType->isFunctionType();
13646 }
13647
13648 // [ToType] [Return]
13649
13650 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13651 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13652 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13653 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13654 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13655 }
13656
13657 // return true if any matching specializations were found
13658 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13659 const DeclAccessPair& CurAccessFunPair) {
13660 if (CXXMethodDecl *Method
13661 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13662 // Skip non-static function templates when converting to pointer, and
13663 // static when converting to member pointer.
13664 bool CanConvertToFunctionPointer =
13665 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13666 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13667 return false;
13668 }
13669 else if (TargetTypeIsNonStaticMemberFunction)
13670 return false;
13671
13672 // C++ [over.over]p2:
13673 // If the name is a function template, template argument deduction is
13674 // done (14.8.2.2), and if the argument deduction succeeds, the
13675 // resulting template argument list is used to generate a single
13676 // function template specialization, which is added to the set of
13677 // overloaded functions considered.
13678 FunctionDecl *Specialization = nullptr;
13679 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13681 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13682 Specialization, Info, /*IsAddressOfFunction*/ true);
13683 Result != TemplateDeductionResult::Success) {
13684 // Make a note of the failed deduction for diagnostics.
13685 FailedCandidates.addCandidate()
13686 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13687 MakeDeductionFailureInfo(Context, Result, Info));
13688 return false;
13689 }
13690
13691 // Template argument deduction ensures that we have an exact match or
13692 // compatible pointer-to-function arguments that would be adjusted by ICS.
13693 // This function template specicalization works.
13695 Context.getCanonicalType(Specialization->getType()),
13696 Context.getCanonicalType(TargetFunctionType)));
13697
13699 return false;
13700
13701 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13702 return true;
13703 }
13704
13705 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13706 const DeclAccessPair& CurAccessFunPair) {
13707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13708 // Skip non-static functions when converting to pointer, and static
13709 // when converting to member pointer.
13710 bool CanConvertToFunctionPointer =
13711 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13712 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13713 return false;
13714 }
13715 else if (TargetTypeIsNonStaticMemberFunction)
13716 return false;
13717
13718 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13719 if (S.getLangOpts().CUDA) {
13720 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13721 if (!(Caller && Caller->isImplicit()) &&
13722 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13723 return false;
13724 }
13725 if (FunDecl->isMultiVersion()) {
13726 const auto *TA = FunDecl->getAttr<TargetAttr>();
13727 if (TA && !TA->isDefaultVersion())
13728 return false;
13729 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13730 if (TVA && !TVA->isDefaultVersion())
13731 return false;
13732 }
13733
13734 // If any candidate has a placeholder return type, trigger its deduction
13735 // now.
13736 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13737 Complain)) {
13738 HasComplained |= Complain;
13739 return false;
13740 }
13741
13742 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13743 return false;
13744
13745 // If we're in C, we need to support types that aren't exactly identical.
13746 if (!S.getLangOpts().CPlusPlus ||
13747 candidateHasExactlyCorrectType(FunDecl)) {
13748 Matches.push_back(std::make_pair(
13749 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13750 FoundNonTemplateFunction = true;
13751 return true;
13752 }
13753 }
13754
13755 return false;
13756 }
13757
13758 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13759 bool Ret = false;
13760
13761 // If the overload expression doesn't have the form of a pointer to
13762 // member, don't try to convert it to a pointer-to-member type.
13763 if (IsInvalidFormOfPointerToMemberFunction())
13764 return false;
13765
13766 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13767 E = OvlExpr->decls_end();
13768 I != E; ++I) {
13769 // Look through any using declarations to find the underlying function.
13770 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13771
13772 // C++ [over.over]p3:
13773 // Non-member functions and static member functions match
13774 // targets of type "pointer-to-function" or "reference-to-function."
13775 // Nonstatic member functions match targets of
13776 // type "pointer-to-member-function."
13777 // Note that according to DR 247, the containing class does not matter.
13778 if (FunctionTemplateDecl *FunctionTemplate
13779 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13780 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13781 Ret = true;
13782 }
13783 // If we have explicit template arguments supplied, skip non-templates.
13784 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13785 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13786 Ret = true;
13787 }
13788 assert(Ret || Matches.empty());
13789 return Ret;
13790 }
13791
13792 void EliminateAllExceptMostSpecializedTemplate() {
13793 // [...] and any given function template specialization F1 is
13794 // eliminated if the set contains a second function template
13795 // specialization whose function template is more specialized
13796 // than the function template of F1 according to the partial
13797 // ordering rules of 14.5.5.2.
13798
13799 // The algorithm specified above is quadratic. We instead use a
13800 // two-pass algorithm (similar to the one used to identify the
13801 // best viable function in an overload set) that identifies the
13802 // best function template (if it exists).
13803
13804 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13805 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13806 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13807
13808 // TODO: It looks like FailedCandidates does not serve much purpose
13809 // here, since the no_viable diagnostic has index 0.
13810 UnresolvedSetIterator Result = S.getMostSpecialized(
13811 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13812 SourceExpr->getBeginLoc(), S.PDiag(),
13813 S.PDiag(diag::err_addr_ovl_ambiguous)
13814 << Matches[0].second->getDeclName(),
13815 S.PDiag(diag::note_ovl_candidate)
13816 << (unsigned)oc_function << (unsigned)ocs_described_template,
13817 Complain, TargetFunctionType);
13818
13819 if (Result != MatchesCopy.end()) {
13820 // Make it the first and only element
13821 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13822 Matches[0].second = cast<FunctionDecl>(*Result);
13823 Matches.resize(1);
13824 } else
13825 HasComplained |= Complain;
13826 }
13827
13828 void EliminateAllTemplateMatches() {
13829 // [...] any function template specializations in the set are
13830 // eliminated if the set also contains a non-template function, [...]
13831 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13832 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13833 ++I;
13834 else {
13835 Matches[I] = Matches[--N];
13836 Matches.resize(N);
13837 }
13838 }
13839 }
13840
13841 void EliminateLessPartialOrderingConstrainedMatches() {
13842 // C++ [over.over]p5:
13843 // [...] Any given non-template function F0 is eliminated if the set
13844 // contains a second non-template function that is more
13845 // partial-ordering-constrained than F0. [...]
13846 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13847 "Call EliminateAllTemplateMatches() first");
13848 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13849 Results.push_back(Matches[0]);
13850 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13851 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13852 FunctionDecl *F = getMorePartialOrderingConstrained(
13853 S, Matches[I].second, Results[0].second,
13854 /*IsFn1Reversed=*/false,
13855 /*IsFn2Reversed=*/false);
13856 if (!F) {
13857 Results.push_back(Matches[I]);
13858 continue;
13859 }
13860 if (F == Matches[I].second) {
13861 Results.clear();
13862 Results.push_back(Matches[I]);
13863 }
13864 }
13865 std::swap(Matches, Results);
13866 }
13867
13868 void EliminateSuboptimalCudaMatches() {
13869 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13870 Matches);
13871 }
13872
13873public:
13874 void ComplainNoMatchesFound() const {
13875 assert(Matches.empty());
13876 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13877 << OvlExpr->getName() << TargetFunctionType
13878 << OvlExpr->getSourceRange();
13879 if (FailedCandidates.empty())
13880 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13881 /*TakingAddress=*/true);
13882 else {
13883 // We have some deduction failure messages. Use them to diagnose
13884 // the function templates, and diagnose the non-template candidates
13885 // normally.
13886 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13887 IEnd = OvlExpr->decls_end();
13888 I != IEnd; ++I)
13889 if (FunctionDecl *Fun =
13890 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13892 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13893 /*TakingAddress=*/true);
13894 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13895 }
13896 }
13897
13898 bool IsInvalidFormOfPointerToMemberFunction() const {
13899 return TargetTypeIsNonStaticMemberFunction &&
13900 !OvlExprInfo.HasFormOfMemberPointer;
13901 }
13902
13903 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13904 // TODO: Should we condition this on whether any functions might
13905 // have matched, or is it more appropriate to do that in callers?
13906 // TODO: a fixit wouldn't hurt.
13907 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13908 << TargetType << OvlExpr->getSourceRange();
13909 }
13910
13911 bool IsStaticMemberFunctionFromBoundPointer() const {
13912 return StaticMemberFunctionFromBoundPointer;
13913 }
13914
13915 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13916 S.Diag(OvlExpr->getBeginLoc(),
13917 diag::err_invalid_form_pointer_member_function)
13918 << OvlExpr->getSourceRange();
13919 }
13920
13921 void ComplainOfInvalidConversion() const {
13922 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13923 << OvlExpr->getName() << TargetType;
13924 }
13925
13926 void ComplainMultipleMatchesFound() const {
13927 assert(Matches.size() > 1);
13928 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13929 << OvlExpr->getName() << OvlExpr->getSourceRange();
13930 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13931 /*TakingAddress=*/true);
13932 }
13933
13934 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13935
13936 int getNumMatches() const { return Matches.size(); }
13937
13938 FunctionDecl* getMatchingFunctionDecl() const {
13939 if (Matches.size() != 1) return nullptr;
13940 return Matches[0].second;
13941 }
13942
13943 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13944 if (Matches.size() != 1) return nullptr;
13945 return &Matches[0].first;
13946 }
13947};
13948}
13949
13950FunctionDecl *
13952 QualType TargetType,
13953 bool Complain,
13954 DeclAccessPair &FoundResult,
13955 bool *pHadMultipleCandidates) {
13956 assert(AddressOfExpr->getType() == Context.OverloadTy);
13957
13958 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13959 Complain);
13960 int NumMatches = Resolver.getNumMatches();
13961 FunctionDecl *Fn = nullptr;
13962 bool ShouldComplain = Complain && !Resolver.hasComplained();
13963 if (NumMatches == 0 && ShouldComplain) {
13964 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13965 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13966 else
13967 Resolver.ComplainNoMatchesFound();
13968 }
13969 else if (NumMatches > 1 && ShouldComplain)
13970 Resolver.ComplainMultipleMatchesFound();
13971 else if (NumMatches == 1) {
13972 Fn = Resolver.getMatchingFunctionDecl();
13973 assert(Fn);
13974 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13975 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13976 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13977 if (Complain) {
13978 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13979 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13980 else
13981 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13982 }
13983 }
13984
13985 if (pHadMultipleCandidates)
13986 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13987 return Fn;
13988}
13989
13993 OverloadExpr *Ovl = R.Expression;
13994 bool IsResultAmbiguous = false;
13995 FunctionDecl *Result = nullptr;
13996 DeclAccessPair DAP;
13997 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13998
13999 // Return positive for better, negative for worse, 0 for equal preference.
14000 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14001 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14002 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14003 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14004 };
14005
14006 // Don't use the AddressOfResolver because we're specifically looking for
14007 // cases where we have one overload candidate that lacks
14008 // enable_if/pass_object_size/...
14009 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14010 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14011 if (!FD)
14012 return nullptr;
14013
14015 continue;
14016
14017 // If we found a better result, update Result.
14018 auto FoundBetter = [&]() {
14019 IsResultAmbiguous = false;
14020 DAP = I.getPair();
14021 Result = FD;
14022 };
14023
14024 // We have more than one result - see if it is more
14025 // partial-ordering-constrained than the previous one.
14026 if (Result) {
14027 // Check CUDA preference first. If the candidates have differennt CUDA
14028 // preference, choose the one with higher CUDA preference. Otherwise,
14029 // choose the one with more constraints.
14030 if (getLangOpts().CUDA) {
14031 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14032 // FD has different preference than Result.
14033 if (PreferenceByCUDA != 0) {
14034 // FD is more preferable than Result.
14035 if (PreferenceByCUDA > 0)
14036 FoundBetter();
14037 continue;
14038 }
14039 }
14040 // FD has the same CUDA preference than Result. Continue to check
14041 // constraints.
14042
14043 // C++ [over.over]p5:
14044 // [...] Any given non-template function F0 is eliminated if the set
14045 // contains a second non-template function that is more
14046 // partial-ordering-constrained than F0 [...]
14047 FunctionDecl *MoreConstrained =
14049 /*IsFn1Reversed=*/false,
14050 /*IsFn2Reversed=*/false);
14051 if (MoreConstrained != FD) {
14052 if (!MoreConstrained) {
14053 IsResultAmbiguous = true;
14054 AmbiguousDecls.push_back(FD);
14055 }
14056 continue;
14057 }
14058 // FD is more constrained - replace Result with it.
14059 }
14060 FoundBetter();
14061 }
14062
14063 if (IsResultAmbiguous)
14064 return nullptr;
14065
14066 if (Result) {
14067 // We skipped over some ambiguous declarations which might be ambiguous with
14068 // the selected result.
14069 for (FunctionDecl *Skipped : AmbiguousDecls) {
14070 // If skipped candidate has different CUDA preference than the result,
14071 // there is no ambiguity. Otherwise check whether they have different
14072 // constraints.
14073 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14074 continue;
14075 if (!getMoreConstrainedFunction(Skipped, Result))
14076 return nullptr;
14077 }
14078 Pair = DAP;
14079 }
14080 return Result;
14081}
14082
14084 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14085 Expr *E = SrcExpr.get();
14086 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14087
14088 DeclAccessPair DAP;
14090 if (!Found || Found->isCPUDispatchMultiVersion() ||
14091 Found->isCPUSpecificMultiVersion())
14092 return false;
14093
14094 // Emitting multiple diagnostics for a function that is both inaccessible and
14095 // unavailable is consistent with our behavior elsewhere. So, always check
14096 // for both.
14100 if (Res.isInvalid())
14101 return false;
14102 Expr *Fixed = Res.get();
14103 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14104 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14105 else
14106 SrcExpr = Fixed;
14107 return true;
14108}
14109
14111 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14112 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14113 // C++ [over.over]p1:
14114 // [...] [Note: any redundant set of parentheses surrounding the
14115 // overloaded function name is ignored (5.1). ]
14116 // C++ [over.over]p1:
14117 // [...] The overloaded function name can be preceded by the &
14118 // operator.
14119
14120 // If we didn't actually find any template-ids, we're done.
14121 if (!ovl->hasExplicitTemplateArgs())
14122 return nullptr;
14123
14124 TemplateArgumentListInfo ExplicitTemplateArgs;
14125 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14126
14127 // Look through all of the overloaded functions, searching for one
14128 // whose type matches exactly.
14129 FunctionDecl *Matched = nullptr;
14130 for (UnresolvedSetIterator I = ovl->decls_begin(),
14131 E = ovl->decls_end(); I != E; ++I) {
14132 // C++0x [temp.arg.explicit]p3:
14133 // [...] In contexts where deduction is done and fails, or in contexts
14134 // where deduction is not done, if a template argument list is
14135 // specified and it, along with any default template arguments,
14136 // identifies a single function template specialization, then the
14137 // template-id is an lvalue for the function template specialization.
14139 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14140 if (!FunctionTemplate)
14141 continue;
14142
14143 // C++ [over.over]p2:
14144 // If the name is a function template, template argument deduction is
14145 // done (14.8.2.2), and if the argument deduction succeeds, the
14146 // resulting template argument list is used to generate a single
14147 // function template specialization, which is added to the set of
14148 // overloaded functions considered.
14149 FunctionDecl *Specialization = nullptr;
14150 TemplateDeductionInfo Info(ovl->getNameLoc());
14152 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14153 /*IsAddressOfFunction*/ true);
14155 // Make a note of the failed deduction for diagnostics.
14156 if (FailedTSC)
14157 FailedTSC->addCandidate().set(
14158 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14160 continue;
14161 }
14162
14163 assert(Specialization && "no specialization and no error?");
14164
14165 // C++ [temp.deduct.call]p6:
14166 // [...] If all successful deductions yield the same deduced A, that
14167 // deduced A is the result of deduction; otherwise, the parameter is
14168 // treated as a non-deduced context.
14169 if (Matched) {
14170 if (ForTypeDeduction &&
14172 Specialization->getType()))
14173 continue;
14174 // Multiple matches; we can't resolve to a single declaration.
14175 if (Complain) {
14176 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14177 << ovl->getName();
14179 }
14180 return nullptr;
14181 }
14182
14183 Matched = Specialization;
14184 if (FoundResult) *FoundResult = I.getPair();
14185 }
14186
14187 if (Matched &&
14188 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14189 return nullptr;
14190
14191 return Matched;
14192}
14193
14195 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14196 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14197 unsigned DiagIDForComplaining) {
14198 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14199
14201
14202 DeclAccessPair found;
14203 ExprResult SingleFunctionExpression;
14205 ovl.Expression, /*complain*/ false, &found)) {
14206 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14207 SrcExpr = ExprError();
14208 return true;
14209 }
14210
14211 // It is only correct to resolve to an instance method if we're
14212 // resolving a form that's permitted to be a pointer to member.
14213 // Otherwise we'll end up making a bound member expression, which
14214 // is illegal in all the contexts we resolve like this.
14215 if (!ovl.HasFormOfMemberPointer &&
14216 isa<CXXMethodDecl>(fn) &&
14217 cast<CXXMethodDecl>(fn)->isInstance()) {
14218 if (!complain) return false;
14219
14220 Diag(ovl.Expression->getExprLoc(),
14221 diag::err_bound_member_function)
14222 << 0 << ovl.Expression->getSourceRange();
14223
14224 // TODO: I believe we only end up here if there's a mix of
14225 // static and non-static candidates (otherwise the expression
14226 // would have 'bound member' type, not 'overload' type).
14227 // Ideally we would note which candidate was chosen and why
14228 // the static candidates were rejected.
14229 SrcExpr = ExprError();
14230 return true;
14231 }
14232
14233 // Fix the expression to refer to 'fn'.
14234 SingleFunctionExpression =
14235 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14236
14237 // If desired, do function-to-pointer decay.
14238 if (doFunctionPointerConversion) {
14239 SingleFunctionExpression =
14240 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14241 if (SingleFunctionExpression.isInvalid()) {
14242 SrcExpr = ExprError();
14243 return true;
14244 }
14245 }
14246 }
14247
14248 if (!SingleFunctionExpression.isUsable()) {
14249 if (complain) {
14250 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14251 << ovl.Expression->getName()
14252 << DestTypeForComplaining
14253 << OpRangeForComplaining
14255 NoteAllOverloadCandidates(SrcExpr.get());
14256
14257 SrcExpr = ExprError();
14258 return true;
14259 }
14260
14261 return false;
14262 }
14263
14264 SrcExpr = SingleFunctionExpression;
14265 return true;
14266}
14267
14268/// Add a single candidate to the overload set.
14270 DeclAccessPair FoundDecl,
14271 TemplateArgumentListInfo *ExplicitTemplateArgs,
14272 ArrayRef<Expr *> Args,
14273 OverloadCandidateSet &CandidateSet,
14274 bool PartialOverloading,
14275 bool KnownValid) {
14276 NamedDecl *Callee = FoundDecl.getDecl();
14277 if (isa<UsingShadowDecl>(Callee))
14278 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14279
14280 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14281 if (ExplicitTemplateArgs) {
14282 assert(!KnownValid && "Explicit template arguments?");
14283 return;
14284 }
14285 // Prevent ill-formed function decls to be added as overload candidates.
14286 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14287 return;
14288
14289 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14290 /*SuppressUserConversions=*/false,
14291 PartialOverloading);
14292 return;
14293 }
14294
14295 if (FunctionTemplateDecl *FuncTemplate
14296 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14297 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14298 ExplicitTemplateArgs, Args, CandidateSet,
14299 /*SuppressUserConversions=*/false,
14300 PartialOverloading);
14301 return;
14302 }
14303
14304 assert(!KnownValid && "unhandled case in overloaded call candidate");
14305}
14306
14308 ArrayRef<Expr *> Args,
14309 OverloadCandidateSet &CandidateSet,
14310 bool PartialOverloading) {
14311
14312#ifndef NDEBUG
14313 // Verify that ArgumentDependentLookup is consistent with the rules
14314 // in C++0x [basic.lookup.argdep]p3:
14315 //
14316 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14317 // and let Y be the lookup set produced by argument dependent
14318 // lookup (defined as follows). If X contains
14319 //
14320 // -- a declaration of a class member, or
14321 //
14322 // -- a block-scope function declaration that is not a
14323 // using-declaration, or
14324 //
14325 // -- a declaration that is neither a function or a function
14326 // template
14327 //
14328 // then Y is empty.
14329
14330 if (ULE->requiresADL()) {
14332 E = ULE->decls_end(); I != E; ++I) {
14333 assert(!(*I)->getDeclContext()->isRecord());
14334 assert(isa<UsingShadowDecl>(*I) ||
14335 !(*I)->getDeclContext()->isFunctionOrMethod());
14336 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14337 }
14338 }
14339#endif
14340
14341 // It would be nice to avoid this copy.
14342 TemplateArgumentListInfo TABuffer;
14343 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14344 if (ULE->hasExplicitTemplateArgs()) {
14345 ULE->copyTemplateArgumentsInto(TABuffer);
14346 ExplicitTemplateArgs = &TABuffer;
14347 }
14348
14350 E = ULE->decls_end(); I != E; ++I)
14351 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14352 CandidateSet, PartialOverloading,
14353 /*KnownValid*/ true);
14354
14355 if (ULE->requiresADL())
14357 Args, ExplicitTemplateArgs,
14358 CandidateSet, PartialOverloading);
14359}
14360
14362 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14363 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14364 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14365 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14366 CandidateSet, false, /*KnownValid*/ false);
14367}
14368
14369/// Determine whether a declaration with the specified name could be moved into
14370/// a different namespace.
14372 switch (Name.getCXXOverloadedOperator()) {
14373 case OO_New: case OO_Array_New:
14374 case OO_Delete: case OO_Array_Delete:
14375 return false;
14376
14377 default:
14378 return true;
14379 }
14380}
14381
14382/// Attempt to recover from an ill-formed use of a non-dependent name in a
14383/// template, where the non-dependent name was declared after the template
14384/// was defined. This is common in code written for a compilers which do not
14385/// correctly implement two-stage name lookup.
14386///
14387/// Returns true if a viable candidate was found and a diagnostic was issued.
14389 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14391 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14392 CXXRecordDecl **FoundInClass = nullptr) {
14393 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14394 return false;
14395
14396 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14397 if (DC->isTransparentContext())
14398 continue;
14399
14400 SemaRef.LookupQualifiedName(R, DC);
14401
14402 if (!R.empty()) {
14404
14405 OverloadCandidateSet Candidates(FnLoc, CSK);
14406 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14407 Candidates);
14408
14411 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14412
14413 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14414 // We either found non-function declarations or a best viable function
14415 // at class scope. A class-scope lookup result disables ADL. Don't
14416 // look past this, but let the caller know that we found something that
14417 // either is, or might be, usable in this class.
14418 if (FoundInClass) {
14419 *FoundInClass = RD;
14420 if (OR == OR_Success) {
14421 R.clear();
14422 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14423 R.resolveKind();
14424 }
14425 }
14426 return false;
14427 }
14428
14429 if (OR != OR_Success) {
14430 // There wasn't a unique best function or function template.
14431 return false;
14432 }
14433
14434 // Find the namespaces where ADL would have looked, and suggest
14435 // declaring the function there instead.
14436 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14437 Sema::AssociatedClassSet AssociatedClasses;
14438 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14439 AssociatedNamespaces,
14440 AssociatedClasses);
14441 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14443 DeclContext *Std = SemaRef.getStdNamespace();
14444 for (Sema::AssociatedNamespaceSet::iterator
14445 it = AssociatedNamespaces.begin(),
14446 end = AssociatedNamespaces.end(); it != end; ++it) {
14447 // Never suggest declaring a function within namespace 'std'.
14448 if (Std && Std->Encloses(*it))
14449 continue;
14450
14451 // Never suggest declaring a function within a namespace with a
14452 // reserved name, like __gnu_cxx.
14453 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14454 if (NS &&
14455 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14456 continue;
14457
14458 SuggestedNamespaces.insert(*it);
14459 }
14460 }
14461
14462 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14463 << R.getLookupName();
14464 if (SuggestedNamespaces.empty()) {
14465 SemaRef.Diag(Best->Function->getLocation(),
14466 diag::note_not_found_by_two_phase_lookup)
14467 << R.getLookupName() << 0;
14468 } else if (SuggestedNamespaces.size() == 1) {
14469 SemaRef.Diag(Best->Function->getLocation(),
14470 diag::note_not_found_by_two_phase_lookup)
14471 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14472 } else {
14473 // FIXME: It would be useful to list the associated namespaces here,
14474 // but the diagnostics infrastructure doesn't provide a way to produce
14475 // a localized representation of a list of items.
14476 SemaRef.Diag(Best->Function->getLocation(),
14477 diag::note_not_found_by_two_phase_lookup)
14478 << R.getLookupName() << 2;
14479 }
14480
14481 // Try to recover by calling this function.
14482 return true;
14483 }
14484
14485 R.clear();
14486 }
14487
14488 return false;
14489}
14490
14491/// Attempt to recover from ill-formed use of a non-dependent operator in a
14492/// template, where the non-dependent operator was declared after the template
14493/// was defined.
14494///
14495/// Returns true if a viable candidate was found and a diagnostic was issued.
14496static bool
14498 SourceLocation OpLoc,
14499 ArrayRef<Expr *> Args) {
14500 DeclarationName OpName =
14502 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14503 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14505 /*ExplicitTemplateArgs=*/nullptr, Args);
14506}
14507
14508namespace {
14509class BuildRecoveryCallExprRAII {
14510 Sema &SemaRef;
14511 Sema::SatisfactionStackResetRAII SatStack;
14512
14513public:
14514 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14515 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14516 SemaRef.IsBuildingRecoveryCallExpr = true;
14517 }
14518
14519 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14520};
14521}
14522
14523/// Attempts to recover from a call where no functions were found.
14524///
14525/// This function will do one of three things:
14526/// * Diagnose, recover, and return a recovery expression.
14527/// * Diagnose, fail to recover, and return ExprError().
14528/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14529/// expected to diagnose as appropriate.
14530static ExprResult
14533 SourceLocation LParenLoc,
14535 SourceLocation RParenLoc,
14536 bool EmptyLookup, bool AllowTypoCorrection) {
14537 // Do not try to recover if it is already building a recovery call.
14538 // This stops infinite loops for template instantiations like
14539 //
14540 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14541 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14542 if (SemaRef.IsBuildingRecoveryCallExpr)
14543 return ExprResult();
14544 BuildRecoveryCallExprRAII RCE(SemaRef);
14545
14546 CXXScopeSpec SS;
14547 SS.Adopt(ULE->getQualifierLoc());
14548 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14549
14550 TemplateArgumentListInfo TABuffer;
14551 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14552 if (ULE->hasExplicitTemplateArgs()) {
14553 ULE->copyTemplateArgumentsInto(TABuffer);
14554 ExplicitTemplateArgs = &TABuffer;
14555 }
14556
14557 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14559 CXXRecordDecl *FoundInClass = nullptr;
14560 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14562 ExplicitTemplateArgs, Args, &FoundInClass)) {
14563 // OK, diagnosed a two-phase lookup issue.
14564 } else if (EmptyLookup) {
14565 // Try to recover from an empty lookup with typo correction.
14566 R.clear();
14567 NoTypoCorrectionCCC NoTypoValidator{};
14568 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14569 ExplicitTemplateArgs != nullptr,
14570 dyn_cast<MemberExpr>(Fn));
14571 CorrectionCandidateCallback &Validator =
14572 AllowTypoCorrection
14573 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14574 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14575 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14576 Args))
14577 return ExprError();
14578 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14579 // We found a usable declaration of the name in a dependent base of some
14580 // enclosing class.
14581 // FIXME: We should also explain why the candidates found by name lookup
14582 // were not viable.
14583 if (SemaRef.DiagnoseDependentMemberLookup(R))
14584 return ExprError();
14585 } else {
14586 // We had viable candidates and couldn't recover; let the caller diagnose
14587 // this.
14588 return ExprResult();
14589 }
14590
14591 // If we get here, we should have issued a diagnostic and formed a recovery
14592 // lookup result.
14593 assert(!R.empty() && "lookup results empty despite recovery");
14594
14595 // If recovery created an ambiguity, just bail out.
14596 if (R.isAmbiguous()) {
14598 return ExprError();
14599 }
14600
14601 // Build an implicit member call if appropriate. Just drop the
14602 // casts and such from the call, we don't really care.
14603 ExprResult NewFn = ExprError();
14604 if ((*R.begin())->isCXXClassMember())
14605 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14606 ExplicitTemplateArgs, S);
14607 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14608 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14609 ExplicitTemplateArgs);
14610 else
14611 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14612
14613 if (NewFn.isInvalid())
14614 return ExprError();
14615
14616 // This shouldn't cause an infinite loop because we're giving it
14617 // an expression with viable lookup results, which should never
14618 // end up here.
14619 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14620 MultiExprArg(Args.data(), Args.size()),
14621 RParenLoc);
14622}
14623
14626 MultiExprArg Args,
14627 SourceLocation RParenLoc,
14628 OverloadCandidateSet *CandidateSet,
14629 ExprResult *Result) {
14630#ifndef NDEBUG
14631 if (ULE->requiresADL()) {
14632 // To do ADL, we must have found an unqualified name.
14633 assert(!ULE->getQualifier() && "qualified name with ADL");
14634
14635 // We don't perform ADL for implicit declarations of builtins.
14636 // Verify that this was correctly set up.
14637 FunctionDecl *F;
14638 if (ULE->decls_begin() != ULE->decls_end() &&
14639 ULE->decls_begin() + 1 == ULE->decls_end() &&
14640 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14641 F->getBuiltinID() && F->isImplicit())
14642 llvm_unreachable("performing ADL for builtin");
14643
14644 // We don't perform ADL in C.
14645 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14646 }
14647#endif
14648
14649 UnbridgedCastsSet UnbridgedCasts;
14650 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14651 *Result = ExprError();
14652 return true;
14653 }
14654
14655 // Add the functions denoted by the callee to the set of candidate
14656 // functions, including those from argument-dependent lookup.
14657 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14658
14659 if (getLangOpts().MSVCCompat &&
14660 CurContext->isDependentContext() && !isSFINAEContext() &&
14662
14664 if (CandidateSet->empty() ||
14665 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14667 // In Microsoft mode, if we are inside a template class member function
14668 // then create a type dependent CallExpr. The goal is to postpone name
14669 // lookup to instantiation time to be able to search into type dependent
14670 // base classes.
14671 CallExpr *CE =
14672 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14673 RParenLoc, CurFPFeatureOverrides());
14675 *Result = CE;
14676 return true;
14677 }
14678 }
14679
14680 if (CandidateSet->empty())
14681 return false;
14682
14683 UnbridgedCasts.restore();
14684 return false;
14685}
14686
14687// Guess at what the return type for an unresolvable overload should be.
14690 std::optional<QualType> Result;
14691 // Adjust Type after seeing a candidate.
14692 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14693 if (!Candidate.Function)
14694 return;
14695 if (Candidate.Function->isInvalidDecl())
14696 return;
14697 QualType T = Candidate.Function->getReturnType();
14698 if (T.isNull())
14699 return;
14700 if (!Result)
14701 Result = T;
14702 else if (Result != T)
14703 Result = QualType();
14704 };
14705
14706 // Look for an unambiguous type from a progressively larger subset.
14707 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14708 //
14709 // First, consider only the best candidate.
14710 if (Best && *Best != CS.end())
14711 ConsiderCandidate(**Best);
14712 // Next, consider only viable candidates.
14713 if (!Result)
14714 for (const auto &C : CS)
14715 if (C.Viable)
14716 ConsiderCandidate(C);
14717 // Finally, consider all candidates.
14718 if (!Result)
14719 for (const auto &C : CS)
14720 ConsiderCandidate(C);
14721
14722 if (!Result)
14723 return QualType();
14724 auto Value = *Result;
14725 if (Value.isNull() || Value->isUndeducedType())
14726 return QualType();
14727 return Value;
14728}
14729
14730/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14731/// the completed call expression. If overload resolution fails, emits
14732/// diagnostics and returns ExprError()
14735 SourceLocation LParenLoc,
14736 MultiExprArg Args,
14737 SourceLocation RParenLoc,
14738 Expr *ExecConfig,
14739 OverloadCandidateSet *CandidateSet,
14741 OverloadingResult OverloadResult,
14742 bool AllowTypoCorrection) {
14743 switch (OverloadResult) {
14744 case OR_Success: {
14745 FunctionDecl *FDecl = (*Best)->Function;
14746 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14747 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14748 return ExprError();
14749 ExprResult Res =
14750 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14751 if (Res.isInvalid())
14752 return ExprError();
14753 return SemaRef.BuildResolvedCallExpr(
14754 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14755 /*IsExecConfig=*/false,
14756 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14757 }
14758
14759 case OR_No_Viable_Function: {
14760 if (*Best != CandidateSet->end() &&
14761 CandidateSet->getKind() ==
14763 if (CXXMethodDecl *M =
14764 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14766 CandidateSet->NoteCandidates(
14768 Fn->getBeginLoc(),
14769 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14770 SemaRef, OCD_AmbiguousCandidates, Args);
14771 return ExprError();
14772 }
14773 }
14774
14775 // Try to recover by looking for viable functions which the user might
14776 // have meant to call.
14777 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14778 Args, RParenLoc,
14779 CandidateSet->empty(),
14780 AllowTypoCorrection);
14781 if (Recovery.isInvalid() || Recovery.isUsable())
14782 return Recovery;
14783
14784 // If the user passes in a function that we can't take the address of, we
14785 // generally end up emitting really bad error messages. Here, we attempt to
14786 // emit better ones.
14787 for (const Expr *Arg : Args) {
14788 if (!Arg->getType()->isFunctionType())
14789 continue;
14790 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14791 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14792 if (FD &&
14793 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14794 Arg->getExprLoc()))
14795 return ExprError();
14796 }
14797 }
14798
14799 CandidateSet->NoteCandidates(
14801 Fn->getBeginLoc(),
14802 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14803 << ULE->getName() << Fn->getSourceRange()),
14804 SemaRef, OCD_AllCandidates, Args);
14805 break;
14806 }
14807
14808 case OR_Ambiguous:
14809 CandidateSet->NoteCandidates(
14810 PartialDiagnosticAt(Fn->getBeginLoc(),
14811 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14812 << ULE->getName() << Fn->getSourceRange()),
14813 SemaRef, OCD_AmbiguousCandidates, Args);
14814 break;
14815
14816 case OR_Deleted: {
14817 FunctionDecl *FDecl = (*Best)->Function;
14818 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14819 Fn->getSourceRange(), ULE->getName(),
14820 *CandidateSet, FDecl, Args);
14821
14822 // We emitted an error for the unavailable/deleted function call but keep
14823 // the call in the AST.
14824 ExprResult Res =
14825 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14826 if (Res.isInvalid())
14827 return ExprError();
14828 return SemaRef.BuildResolvedCallExpr(
14829 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14830 /*IsExecConfig=*/false,
14831 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14832 }
14833 }
14834
14835 // Overload resolution failed, try to recover.
14836 SmallVector<Expr *, 8> SubExprs = {Fn};
14837 SubExprs.append(Args.begin(), Args.end());
14838 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14839 chooseRecoveryType(*CandidateSet, Best));
14840}
14841
14844 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14845 if (I->Viable &&
14846 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14847 I->Viable = false;
14848 I->FailureKind = ovl_fail_addr_not_available;
14849 }
14850 }
14851}
14852
14855 SourceLocation LParenLoc,
14856 MultiExprArg Args,
14857 SourceLocation RParenLoc,
14858 Expr *ExecConfig,
14859 bool AllowTypoCorrection,
14860 bool CalleesAddressIsTaken) {
14861
14865
14866 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14867 ExprResult result;
14868
14869 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14870 &result))
14871 return result;
14872
14873 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14874 // functions that aren't addressible are considered unviable.
14875 if (CalleesAddressIsTaken)
14876 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14877
14879 OverloadingResult OverloadResult =
14880 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14881
14882 // [C++23][over.call.func]
14883 // if overload resolution selects a non-static member function,
14884 // the call is ill-formed;
14886 Best != CandidateSet.end()) {
14887 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14888 M && M->isImplicitObjectMemberFunction()) {
14889 OverloadResult = OR_No_Viable_Function;
14890 }
14891 }
14892
14893 // Model the case with a call to a templated function whose definition
14894 // encloses the call and whose return type contains a placeholder type as if
14895 // the UnresolvedLookupExpr was type-dependent.
14896 if (OverloadResult == OR_Success) {
14897 const FunctionDecl *FDecl = Best->Function;
14898 if (LangOpts.CUDA)
14899 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14900 if (FDecl && FDecl->isTemplateInstantiation() &&
14901 FDecl->getReturnType()->isUndeducedType()) {
14902
14903 // Creating dependent CallExpr is not okay if the enclosing context itself
14904 // is not dependent. This situation notably arises if a non-dependent
14905 // member function calls the later-defined overloaded static function.
14906 //
14907 // For example, in
14908 // class A {
14909 // void c() { callee(1); }
14910 // static auto callee(auto x) { }
14911 // };
14912 //
14913 // Here callee(1) is unresolved at the call site, but is not inside a
14914 // dependent context. There will be no further attempt to resolve this
14915 // call if it is made dependent.
14916
14917 if (const auto *TP =
14918 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14919 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14920 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14921 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14922 }
14923 }
14924 }
14925
14926 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14927 ExecConfig, &CandidateSet, &Best,
14928 OverloadResult, AllowTypoCorrection);
14929}
14930
14934 const UnresolvedSetImpl &Fns,
14935 bool PerformADL) {
14937 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14938 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14939}
14940
14943 bool HadMultipleCandidates) {
14944 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14945 // the FoundDecl as it impedes TransformMemberExpr.
14946 // We go a bit further here: if there's no difference in UnderlyingDecl,
14947 // then using FoundDecl vs Method shouldn't make a difference either.
14948 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14949 FoundDecl = Method;
14950 // Convert the expression to match the conversion function's implicit object
14951 // parameter.
14952 ExprResult Exp;
14953 if (Method->isExplicitObjectMemberFunction())
14955 else
14957 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14958 if (Exp.isInvalid())
14959 return true;
14960
14961 if (Method->getParent()->isLambda() &&
14962 Method->getConversionType()->isBlockPointerType()) {
14963 // This is a lambda conversion to block pointer; check if the argument
14964 // was a LambdaExpr.
14965 Expr *SubE = E;
14966 auto *CE = dyn_cast<CastExpr>(SubE);
14967 if (CE && CE->getCastKind() == CK_NoOp)
14968 SubE = CE->getSubExpr();
14969 SubE = SubE->IgnoreParens();
14970 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14971 SubE = BE->getSubExpr();
14972 if (isa<LambdaExpr>(SubE)) {
14973 // For the conversion to block pointer on a lambda expression, we
14974 // construct a special BlockLiteral instead; this doesn't really make
14975 // a difference in ARC, but outside of ARC the resulting block literal
14976 // follows the normal lifetime rules for block literals instead of being
14977 // autoreleased.
14981 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14983
14984 // FIXME: This note should be produced by a CodeSynthesisContext.
14985 if (BlockExp.isInvalid())
14986 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14987 return BlockExp;
14988 }
14989 }
14990 CallExpr *CE;
14991 QualType ResultType = Method->getReturnType();
14993 ResultType = ResultType.getNonLValueExprType(Context);
14994 if (Method->isExplicitObjectMemberFunction()) {
14995 ExprResult FnExpr =
14996 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14997 HadMultipleCandidates, E->getBeginLoc());
14998 if (FnExpr.isInvalid())
14999 return ExprError();
15000 Expr *ObjectParam = Exp.get();
15001 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15002 ResultType, VK, Exp.get()->getEndLoc(),
15004 CE->setUsesMemberSyntax(true);
15005 } else {
15006 MemberExpr *ME =
15007 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15009 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15010 HadMultipleCandidates, DeclarationNameInfo(),
15011 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15012
15013 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15014 Exp.get()->getEndLoc(),
15016 }
15017
15018 if (CheckFunctionCall(Method, CE,
15019 Method->getType()->castAs<FunctionProtoType>()))
15020 return ExprError();
15021
15023}
15024
15027 const UnresolvedSetImpl &Fns,
15028 Expr *Input, bool PerformADL) {
15030 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15031 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15032 // TODO: provide better source location info.
15033 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15034
15035 if (checkPlaceholderForOverload(*this, Input))
15036 return ExprError();
15037
15038 Expr *Args[2] = { Input, nullptr };
15039 unsigned NumArgs = 1;
15040
15041 // For post-increment and post-decrement, add the implicit '0' as
15042 // the second argument, so that we know this is a post-increment or
15043 // post-decrement.
15044 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15045 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15046 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15047 SourceLocation());
15048 NumArgs = 2;
15049 }
15050
15051 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15052
15053 if (Input->isTypeDependent()) {
15055 // [C++26][expr.unary.op][expr.pre.incr]
15056 // The * operator yields an lvalue of type
15057 // The pre/post increment operators yied an lvalue.
15058 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15059 VK = VK_LValue;
15060
15061 if (Fns.empty())
15062 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15063 OK_Ordinary, OpLoc, false,
15065
15066 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15068 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15069 if (Fn.isInvalid())
15070 return ExprError();
15071 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15072 Context.DependentTy, VK_PRValue, OpLoc,
15074 }
15075
15076 // Build an empty overload set.
15078
15079 // Add the candidates from the given function set.
15080 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15081
15082 // Add operator candidates that are member functions.
15083 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15084
15085 // Add candidates from ADL.
15086 if (PerformADL) {
15087 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15088 /*ExplicitTemplateArgs*/nullptr,
15089 CandidateSet);
15090 }
15091
15092 // Add builtin operator candidates.
15093 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15094
15095 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15096
15097 // Perform overload resolution.
15099 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15100 case OR_Success: {
15101 // We found a built-in operator or an overloaded operator.
15102 FunctionDecl *FnDecl = Best->Function;
15103
15104 if (FnDecl) {
15105 Expr *Base = nullptr;
15106 // We matched an overloaded operator. Build a call to that
15107 // operator.
15108
15109 // Convert the arguments.
15110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15111 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15112
15113 ExprResult InputInit;
15114 if (Method->isExplicitObjectMemberFunction())
15115 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15116 else
15118 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15119 if (InputInit.isInvalid())
15120 return ExprError();
15121 Base = Input = InputInit.get();
15122 } else {
15123 // Convert the arguments.
15124 ExprResult InputInit
15126 Context,
15127 FnDecl->getParamDecl(0)),
15129 Input);
15130 if (InputInit.isInvalid())
15131 return ExprError();
15132 Input = InputInit.get();
15133 }
15134
15135 // Build the actual expression node.
15136 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15137 Base, HadMultipleCandidates,
15138 OpLoc);
15139 if (FnExpr.isInvalid())
15140 return ExprError();
15141
15142 // Determine the result type.
15143 QualType ResultTy = FnDecl->getReturnType();
15145 ResultTy = ResultTy.getNonLValueExprType(Context);
15146
15147 Args[0] = Input;
15149 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15151 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15152
15153 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15154 return ExprError();
15155
15156 if (CheckFunctionCall(FnDecl, TheCall,
15157 FnDecl->getType()->castAs<FunctionProtoType>()))
15158 return ExprError();
15159 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15160 } else {
15161 // We matched a built-in operator. Convert the arguments, then
15162 // break out so that we will build the appropriate built-in
15163 // operator node.
15165 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15168 if (InputRes.isInvalid())
15169 return ExprError();
15170 Input = InputRes.get();
15171 break;
15172 }
15173 }
15174
15176 // This is an erroneous use of an operator which can be overloaded by
15177 // a non-member function. Check for non-member operators which were
15178 // defined too late to be candidates.
15179 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15180 // FIXME: Recover by calling the found function.
15181 return ExprError();
15182
15183 // No viable function; fall through to handling this as a
15184 // built-in operator, which will produce an error message for us.
15185 break;
15186
15187 case OR_Ambiguous:
15188 CandidateSet.NoteCandidates(
15189 PartialDiagnosticAt(OpLoc,
15190 PDiag(diag::err_ovl_ambiguous_oper_unary)
15192 << Input->getType() << Input->getSourceRange()),
15193 *this, OCD_AmbiguousCandidates, ArgsArray,
15194 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15195 return ExprError();
15196
15197 case OR_Deleted: {
15198 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15199 // object whose method was called. Later in NoteCandidates size of ArgsArray
15200 // is passed further and it eventually ends up compared to number of
15201 // function candidate parameters which never includes the object parameter,
15202 // so slice ArgsArray to make sure apples are compared to apples.
15203 StringLiteral *Msg = Best->Function->getDeletedMessage();
15204 CandidateSet.NoteCandidates(
15205 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15207 << (Msg != nullptr)
15208 << (Msg ? Msg->getString() : StringRef())
15209 << Input->getSourceRange()),
15210 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15211 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15212 return ExprError();
15213 }
15214 }
15215
15216 // Either we found no viable overloaded operator or we matched a
15217 // built-in operator. In either case, fall through to trying to
15218 // build a built-in operation.
15219 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15220}
15221
15224 const UnresolvedSetImpl &Fns,
15225 ArrayRef<Expr *> Args, bool PerformADL) {
15226 SourceLocation OpLoc = CandidateSet.getLocation();
15227
15228 OverloadedOperatorKind ExtraOp =
15231 : OO_None;
15232
15233 // Add the candidates from the given function set. This also adds the
15234 // rewritten candidates using these functions if necessary.
15235 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15236
15237 // As template candidates are not deduced immediately,
15238 // persist the array in the overload set.
15239 ArrayRef<Expr *> ReversedArgs;
15240 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15241 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15242 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15243
15244 // Add operator candidates that are member functions.
15245 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15246 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15247 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15249
15250 // In C++20, also add any rewritten member candidates.
15251 if (ExtraOp) {
15252 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15253 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15254 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15256 }
15257
15258 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15259 // performed for an assignment operator (nor for operator[] nor operator->,
15260 // which don't get here).
15261 if (Op != OO_Equal && PerformADL) {
15262 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15263 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15264 /*ExplicitTemplateArgs*/ nullptr,
15265 CandidateSet);
15266 if (ExtraOp) {
15267 DeclarationName ExtraOpName =
15268 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15269 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15270 /*ExplicitTemplateArgs*/ nullptr,
15271 CandidateSet);
15272 }
15273 }
15274
15275 // Add builtin operator candidates.
15276 //
15277 // FIXME: We don't add any rewritten candidates here. This is strictly
15278 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15279 // resulting in our selecting a rewritten builtin candidate. For example:
15280 //
15281 // enum class E { e };
15282 // bool operator!=(E, E) requires false;
15283 // bool k = E::e != E::e;
15284 //
15285 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15286 // it seems unreasonable to consider rewritten builtin candidates. A core
15287 // issue has been filed proposing to removed this requirement.
15288 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15289}
15290
15293 const UnresolvedSetImpl &Fns, Expr *LHS,
15294 Expr *RHS, bool PerformADL,
15295 bool AllowRewrittenCandidates,
15296 FunctionDecl *DefaultedFn) {
15297 Expr *Args[2] = { LHS, RHS };
15298 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15299
15300 if (!getLangOpts().CPlusPlus20)
15301 AllowRewrittenCandidates = false;
15302
15304
15305 // If either side is type-dependent, create an appropriate dependent
15306 // expression.
15307 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15308 if (Fns.empty()) {
15309 // If there are no functions to store, just build a dependent
15310 // BinaryOperator or CompoundAssignment.
15313 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15314 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15315 Context.DependentTy);
15317 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15319 }
15320
15321 // FIXME: save results of ADL from here?
15322 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15323 // TODO: provide better source location info in DNLoc component.
15324 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15325 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15327 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15328 if (Fn.isInvalid())
15329 return ExprError();
15330 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15331 Context.DependentTy, VK_PRValue, OpLoc,
15333 }
15334
15335 // If this is the .* operator, which is not overloadable, just
15336 // create a built-in binary operator.
15337 if (Opc == BO_PtrMemD) {
15338 auto CheckPlaceholder = [&](Expr *&Arg) {
15340 if (Res.isUsable())
15341 Arg = Res.get();
15342 return !Res.isUsable();
15343 };
15344
15345 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15346 // expression that contains placeholders (in either the LHS or RHS).
15347 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15348 return ExprError();
15349 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15350 }
15351
15352 // Always do placeholder-like conversions on the RHS.
15353 if (checkPlaceholderForOverload(*this, Args[1]))
15354 return ExprError();
15355
15356 // Do placeholder-like conversion on the LHS; note that we should
15357 // not get here with a PseudoObject LHS.
15358 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15359 if (checkPlaceholderForOverload(*this, Args[0]))
15360 return ExprError();
15361
15362 // If this is the assignment operator, we only perform overload resolution
15363 // if the left-hand side is a class or enumeration type. This is actually
15364 // a hack. The standard requires that we do overload resolution between the
15365 // various built-in candidates, but as DR507 points out, this can lead to
15366 // problems. So we do it this way, which pretty much follows what GCC does.
15367 // Note that we go the traditional code path for compound assignment forms.
15368 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15369 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15370
15371 // Build the overload set.
15374 Op, OpLoc, AllowRewrittenCandidates));
15375 if (DefaultedFn)
15376 CandidateSet.exclude(DefaultedFn);
15377 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15378
15379 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15380
15381 // Perform overload resolution.
15383 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15384 case OR_Success: {
15385 // We found a built-in operator or an overloaded operator.
15386 FunctionDecl *FnDecl = Best->Function;
15387
15388 bool IsReversed = Best->isReversed();
15389 if (IsReversed)
15390 std::swap(Args[0], Args[1]);
15391
15392 if (FnDecl) {
15393
15394 if (FnDecl->isInvalidDecl())
15395 return ExprError();
15396
15397 Expr *Base = nullptr;
15398 // We matched an overloaded operator. Build a call to that
15399 // operator.
15400
15401 OverloadedOperatorKind ChosenOp =
15403
15404 // C++2a [over.match.oper]p9:
15405 // If a rewritten operator== candidate is selected by overload
15406 // resolution for an operator@, its return type shall be cv bool
15407 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15408 !FnDecl->getReturnType()->isBooleanType()) {
15409 bool IsExtension =
15411 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15412 : diag::err_ovl_rewrite_equalequal_not_bool)
15413 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15414 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15415 Diag(FnDecl->getLocation(), diag::note_declared_at);
15416 if (!IsExtension)
15417 return ExprError();
15418 }
15419
15420 if (AllowRewrittenCandidates && !IsReversed &&
15421 CandidateSet.getRewriteInfo().isReversible()) {
15422 // We could have reversed this operator, but didn't. Check if some
15423 // reversed form was a viable candidate, and if so, if it had a
15424 // better conversion for either parameter. If so, this call is
15425 // formally ambiguous, and allowing it is an extension.
15427 for (OverloadCandidate &Cand : CandidateSet) {
15428 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15429 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15430 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15432 *this, OpLoc, Cand.Conversions[ArgIdx],
15433 Best->Conversions[ArgIdx]) ==
15435 AmbiguousWith.push_back(Cand.Function);
15436 break;
15437 }
15438 }
15439 }
15440 }
15441
15442 if (!AmbiguousWith.empty()) {
15443 bool AmbiguousWithSelf =
15444 AmbiguousWith.size() == 1 &&
15445 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15446 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15448 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15449 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15450 if (AmbiguousWithSelf) {
15451 Diag(FnDecl->getLocation(),
15452 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15453 // Mark member== const or provide matching != to disallow reversed
15454 // args. Eg.
15455 // struct S { bool operator==(const S&); };
15456 // S()==S();
15457 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15458 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15459 !MD->isConst() &&
15460 !MD->hasCXXExplicitFunctionObjectParameter() &&
15461 Context.hasSameUnqualifiedType(
15462 MD->getFunctionObjectParameterType(),
15463 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15464 Context.hasSameUnqualifiedType(
15465 MD->getFunctionObjectParameterType(),
15466 Args[0]->getType()) &&
15467 Context.hasSameUnqualifiedType(
15468 MD->getFunctionObjectParameterType(),
15469 Args[1]->getType()))
15470 Diag(FnDecl->getLocation(),
15471 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15472 } else {
15473 Diag(FnDecl->getLocation(),
15474 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15475 for (auto *F : AmbiguousWith)
15476 Diag(F->getLocation(),
15477 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15478 }
15479 }
15480 }
15481
15482 // Check for nonnull = nullable.
15483 // This won't be caught in the arg's initialization: the parameter to
15484 // the assignment operator is not marked nonnull.
15485 if (Op == OO_Equal)
15487 Args[1]->getType(), OpLoc);
15488
15489 // Convert the arguments.
15490 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15491 // Best->Access is only meaningful for class members.
15492 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15493
15494 ExprResult Arg0, Arg1;
15495 unsigned ParamIdx = 0;
15496 if (Method->isExplicitObjectMemberFunction()) {
15497 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15498 ParamIdx = 1;
15499 } else {
15501 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15502 }
15505 Context, FnDecl->getParamDecl(ParamIdx)),
15506 SourceLocation(), Args[1]);
15507 if (Arg0.isInvalid() || Arg1.isInvalid())
15508 return ExprError();
15509
15510 Base = Args[0] = Arg0.getAs<Expr>();
15511 Args[1] = RHS = Arg1.getAs<Expr>();
15512 } else {
15513 // Convert the arguments.
15516 FnDecl->getParamDecl(0)),
15517 SourceLocation(), Args[0]);
15518 if (Arg0.isInvalid())
15519 return ExprError();
15520
15521 ExprResult Arg1 =
15524 FnDecl->getParamDecl(1)),
15525 SourceLocation(), Args[1]);
15526 if (Arg1.isInvalid())
15527 return ExprError();
15528 Args[0] = LHS = Arg0.getAs<Expr>();
15529 Args[1] = RHS = Arg1.getAs<Expr>();
15530 }
15531
15532 // Build the actual expression node.
15533 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15534 Best->FoundDecl, Base,
15535 HadMultipleCandidates, OpLoc);
15536 if (FnExpr.isInvalid())
15537 return ExprError();
15538
15539 // Determine the result type.
15540 QualType ResultTy = FnDecl->getReturnType();
15542 ResultTy = ResultTy.getNonLValueExprType(Context);
15543
15544 CallExpr *TheCall;
15545 ArrayRef<const Expr *> ArgsArray(Args, 2);
15546 const Expr *ImplicitThis = nullptr;
15547
15548 // We always create a CXXOperatorCallExpr, even for explicit object
15549 // members; CodeGen should take care not to emit the this pointer.
15551 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15553 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15554
15555 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15556 Method && Method->isImplicitObjectMemberFunction()) {
15557 // Cut off the implicit 'this'.
15558 ImplicitThis = ArgsArray[0];
15559 ArgsArray = ArgsArray.slice(1);
15560 }
15561
15562 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15563 FnDecl))
15564 return ExprError();
15565
15566 if (Op == OO_Equal) {
15567 // Check for a self move.
15568 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15569 // lifetime check.
15571 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15572 Args[1]);
15573 }
15574 if (ImplicitThis) {
15575 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15576 QualType ThisTypeFromDecl = Context.getPointerType(
15577 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15578
15579 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15580 ThisTypeFromDecl);
15581 }
15582
15583 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15584 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15586
15587 ExprResult R = MaybeBindToTemporary(TheCall);
15588 if (R.isInvalid())
15589 return ExprError();
15590
15591 R = CheckForImmediateInvocation(R, FnDecl);
15592 if (R.isInvalid())
15593 return ExprError();
15594
15595 // For a rewritten candidate, we've already reversed the arguments
15596 // if needed. Perform the rest of the rewrite now.
15597 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15598 (Op == OO_Spaceship && IsReversed)) {
15599 if (Op == OO_ExclaimEqual) {
15600 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15601 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15602 } else {
15603 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15604 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15605 Expr *ZeroLiteral =
15607
15610 Ctx.Entity = FnDecl;
15612
15614 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15615 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15616 /*AllowRewrittenCandidates=*/false);
15617
15619 }
15620 if (R.isInvalid())
15621 return ExprError();
15622 } else {
15623 assert(ChosenOp == Op && "unexpected operator name");
15624 }
15625
15626 // Make a note in the AST if we did any rewriting.
15627 if (Best->RewriteKind != CRK_None)
15628 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15629
15630 return R;
15631 } else {
15632 // We matched a built-in operator. Convert the arguments, then
15633 // break out so that we will build the appropriate built-in
15634 // operator node.
15636 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15639 if (ArgsRes0.isInvalid())
15640 return ExprError();
15641 Args[0] = ArgsRes0.get();
15642
15644 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15647 if (ArgsRes1.isInvalid())
15648 return ExprError();
15649 Args[1] = ArgsRes1.get();
15650 break;
15651 }
15652 }
15653
15654 case OR_No_Viable_Function: {
15655 // C++ [over.match.oper]p9:
15656 // If the operator is the operator , [...] and there are no
15657 // viable functions, then the operator is assumed to be the
15658 // built-in operator and interpreted according to clause 5.
15659 if (Opc == BO_Comma)
15660 break;
15661
15662 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15663 // compare result using '==' and '<'.
15664 if (DefaultedFn && Opc == BO_Cmp) {
15665 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15666 Args[1], DefaultedFn);
15667 if (E.isInvalid() || E.isUsable())
15668 return E;
15669 }
15670
15671 // For class as left operand for assignment or compound assignment
15672 // operator do not fall through to handling in built-in, but report that
15673 // no overloaded assignment operator found
15675 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15676 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15677 Args, OpLoc);
15678 DeferDiagsRAII DDR(*this,
15679 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15680 if (Args[0]->getType()->isRecordType() &&
15681 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15682 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15684 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15685 if (Args[0]->getType()->isIncompleteType()) {
15686 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15687 << Args[0]->getType()
15688 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15689 }
15690 } else {
15691 // This is an erroneous use of an operator which can be overloaded by
15692 // a non-member function. Check for non-member operators which were
15693 // defined too late to be candidates.
15694 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15695 // FIXME: Recover by calling the found function.
15696 return ExprError();
15697
15698 // No viable function; try to create a built-in operation, which will
15699 // produce an error. Then, show the non-viable candidates.
15700 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15701 }
15702 assert(Result.isInvalid() &&
15703 "C++ binary operator overloading is missing candidates!");
15704 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15705 return Result;
15706 }
15707
15708 case OR_Ambiguous:
15709 CandidateSet.NoteCandidates(
15710 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15712 << Args[0]->getType()
15713 << Args[1]->getType()
15714 << Args[0]->getSourceRange()
15715 << Args[1]->getSourceRange()),
15717 OpLoc);
15718 return ExprError();
15719
15720 case OR_Deleted: {
15721 if (isImplicitlyDeleted(Best->Function)) {
15722 FunctionDecl *DeletedFD = Best->Function;
15724 if (DFK.isSpecialMember()) {
15725 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15726 << Args[0]->getType() << DFK.asSpecialMember();
15727 } else {
15728 assert(DFK.isComparison());
15729 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15730 << Args[0]->getType() << DeletedFD;
15731 }
15732
15733 // The user probably meant to call this special member. Just
15734 // explain why it's deleted.
15735 NoteDeletedFunction(DeletedFD);
15736 return ExprError();
15737 }
15738
15739 StringLiteral *Msg = Best->Function->getDeletedMessage();
15740 CandidateSet.NoteCandidates(
15742 OpLoc,
15743 PDiag(diag::err_ovl_deleted_oper)
15744 << getOperatorSpelling(Best->Function->getDeclName()
15745 .getCXXOverloadedOperator())
15746 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15747 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15749 OpLoc);
15750 return ExprError();
15751 }
15752 }
15753
15754 // We matched a built-in operator; build it.
15755 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15756}
15757
15759 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15760 FunctionDecl *DefaultedFn) {
15761 const ComparisonCategoryInfo *Info =
15762 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15763 // If we're not producing a known comparison category type, we can't
15764 // synthesize a three-way comparison. Let the caller diagnose this.
15765 if (!Info)
15766 return ExprResult((Expr*)nullptr);
15767
15768 // If we ever want to perform this synthesis more generally, we will need to
15769 // apply the temporary materialization conversion to the operands.
15770 assert(LHS->isGLValue() && RHS->isGLValue() &&
15771 "cannot use prvalue expressions more than once");
15772 Expr *OrigLHS = LHS;
15773 Expr *OrigRHS = RHS;
15774
15775 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15776 // each of them multiple times below.
15777 LHS = new (Context)
15778 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15779 LHS->getObjectKind(), LHS);
15780 RHS = new (Context)
15781 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15782 RHS->getObjectKind(), RHS);
15783
15784 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15785 DefaultedFn);
15786 if (Eq.isInvalid())
15787 return ExprError();
15788
15789 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15790 true, DefaultedFn);
15791 if (Less.isInvalid())
15792 return ExprError();
15793
15795 if (Info->isPartial()) {
15796 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15797 DefaultedFn);
15798 if (Greater.isInvalid())
15799 return ExprError();
15800 }
15801
15802 // Form the list of comparisons we're going to perform.
15803 struct Comparison {
15804 ExprResult Cmp;
15806 } Comparisons[4] =
15812 };
15813
15814 int I = Info->isPartial() ? 3 : 2;
15815
15816 // Combine the comparisons with suitable conditional expressions.
15818 for (; I >= 0; --I) {
15819 // Build a reference to the comparison category constant.
15820 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15821 // FIXME: Missing a constant for a comparison category. Diagnose this?
15822 if (!VI)
15823 return ExprResult((Expr*)nullptr);
15824 ExprResult ThisResult =
15826 if (ThisResult.isInvalid())
15827 return ExprError();
15828
15829 // Build a conditional unless this is the final case.
15830 if (Result.get()) {
15831 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15832 ThisResult.get(), Result.get());
15833 if (Result.isInvalid())
15834 return ExprError();
15835 } else {
15836 Result = ThisResult;
15837 }
15838 }
15839
15840 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15841 // bind the OpaqueValueExprs before they're (repeatedly) used.
15842 Expr *SyntacticForm = BinaryOperator::Create(
15843 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15844 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15846 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15847 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15848}
15849
15851 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15852 MultiExprArg Args, SourceLocation LParenLoc) {
15853
15854 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15855 unsigned NumParams = Proto->getNumParams();
15856 unsigned NumArgsSlots =
15857 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15858 // Build the full argument list for the method call (the implicit object
15859 // parameter is placed at the beginning of the list).
15860 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15861 bool IsError = false;
15862 // Initialize the implicit object parameter.
15863 // Check the argument types.
15864 for (unsigned i = 0; i != NumParams; i++) {
15865 Expr *Arg;
15866 if (i < Args.size()) {
15867 Arg = Args[i];
15868 ExprResult InputInit =
15870 S.Context, Method->getParamDecl(i)),
15871 SourceLocation(), Arg);
15872 IsError |= InputInit.isInvalid();
15873 Arg = InputInit.getAs<Expr>();
15874 } else {
15875 ExprResult DefArg =
15876 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15877 if (DefArg.isInvalid()) {
15878 IsError = true;
15879 break;
15880 }
15881 Arg = DefArg.getAs<Expr>();
15882 }
15883
15884 MethodArgs.push_back(Arg);
15885 }
15886 return IsError;
15887}
15888
15890 SourceLocation RLoc,
15891 Expr *Base,
15892 MultiExprArg ArgExpr) {
15894 Args.push_back(Base);
15895 for (auto *e : ArgExpr) {
15896 Args.push_back(e);
15897 }
15898 DeclarationName OpName =
15899 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15900
15901 SourceRange Range = ArgExpr.empty()
15902 ? SourceRange{}
15903 : SourceRange(ArgExpr.front()->getBeginLoc(),
15904 ArgExpr.back()->getEndLoc());
15905
15906 // If either side is type-dependent, create an appropriate dependent
15907 // expression.
15909
15910 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15911 // CHECKME: no 'operator' keyword?
15912 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15913 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15915 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15916 if (Fn.isInvalid())
15917 return ExprError();
15918 // Can't add any actual overloads yet
15919
15920 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15921 Context.DependentTy, VK_PRValue, RLoc,
15923 }
15924
15925 // Handle placeholders
15926 UnbridgedCastsSet UnbridgedCasts;
15927 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15928 return ExprError();
15929 }
15930 // Build an empty overload set.
15932
15933 // Subscript can only be overloaded as a member function.
15934
15935 // Add operator candidates that are member functions.
15936 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15937
15938 // Add builtin operator candidates.
15939 if (Args.size() == 2)
15940 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15941
15942 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15943
15944 // Perform overload resolution.
15946 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15947 case OR_Success: {
15948 // We found a built-in operator or an overloaded operator.
15949 FunctionDecl *FnDecl = Best->Function;
15950
15951 if (FnDecl) {
15952 // We matched an overloaded operator. Build a call to that
15953 // operator.
15954
15955 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15956
15957 // Convert the arguments.
15959 SmallVector<Expr *, 2> MethodArgs;
15960
15961 // Initialize the object parameter.
15962 if (Method->isExplicitObjectMemberFunction()) {
15963 ExprResult Res =
15965 if (Res.isInvalid())
15966 return ExprError();
15967 Args[0] = Res.get();
15968 ArgExpr = Args;
15969 } else {
15971 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15972 if (Arg0.isInvalid())
15973 return ExprError();
15974
15975 MethodArgs.push_back(Arg0.get());
15976 }
15977
15979 *this, MethodArgs, Method, ArgExpr, LLoc);
15980 if (IsError)
15981 return ExprError();
15982
15983 // Build the actual expression node.
15984 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15985 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15987 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15988 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15989 if (FnExpr.isInvalid())
15990 return ExprError();
15991
15992 // Determine the result type
15993 QualType ResultTy = FnDecl->getReturnType();
15995 ResultTy = ResultTy.getNonLValueExprType(Context);
15996
15998 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16000
16001 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16002 return ExprError();
16003
16004 if (CheckFunctionCall(Method, TheCall,
16005 Method->getType()->castAs<FunctionProtoType>()))
16006 return ExprError();
16007
16009 FnDecl);
16010 } else {
16011 // We matched a built-in operator. Convert the arguments, then
16012 // break out so that we will build the appropriate built-in
16013 // operator node.
16015 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16018 if (ArgsRes0.isInvalid())
16019 return ExprError();
16020 Args[0] = ArgsRes0.get();
16021
16023 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16026 if (ArgsRes1.isInvalid())
16027 return ExprError();
16028 Args[1] = ArgsRes1.get();
16029
16030 break;
16031 }
16032 }
16033
16034 case OR_No_Viable_Function: {
16036 CandidateSet.empty()
16037 ? (PDiag(diag::err_ovl_no_oper)
16038 << Args[0]->getType() << /*subscript*/ 0
16039 << Args[0]->getSourceRange() << Range)
16040 : (PDiag(diag::err_ovl_no_viable_subscript)
16041 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16042 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16043 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16044 return ExprError();
16045 }
16046
16047 case OR_Ambiguous:
16048 if (Args.size() == 2) {
16049 CandidateSet.NoteCandidates(
16051 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16052 << "[]" << Args[0]->getType() << Args[1]->getType()
16053 << Args[0]->getSourceRange() << Range),
16054 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16055 } else {
16056 CandidateSet.NoteCandidates(
16058 PDiag(diag::err_ovl_ambiguous_subscript_call)
16059 << Args[0]->getType()
16060 << Args[0]->getSourceRange() << Range),
16061 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16062 }
16063 return ExprError();
16064
16065 case OR_Deleted: {
16066 StringLiteral *Msg = Best->Function->getDeletedMessage();
16067 CandidateSet.NoteCandidates(
16069 PDiag(diag::err_ovl_deleted_oper)
16070 << "[]" << (Msg != nullptr)
16071 << (Msg ? Msg->getString() : StringRef())
16072 << Args[0]->getSourceRange() << Range),
16073 *this, OCD_AllCandidates, Args, "[]", LLoc);
16074 return ExprError();
16075 }
16076 }
16077
16078 // We matched a built-in operator; build it.
16079 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16080}
16081
16083 SourceLocation LParenLoc,
16084 MultiExprArg Args,
16085 SourceLocation RParenLoc,
16086 Expr *ExecConfig, bool IsExecConfig,
16087 bool AllowRecovery) {
16088 assert(MemExprE->getType() == Context.BoundMemberTy ||
16089 MemExprE->getType() == Context.OverloadTy);
16090
16091 // Dig out the member expression. This holds both the object
16092 // argument and the member function we're referring to.
16093 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16094
16095 // Determine whether this is a call to a pointer-to-member function.
16096 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16097 assert(op->getType() == Context.BoundMemberTy);
16098 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16099
16100 QualType fnType =
16101 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16102
16103 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16104 QualType resultType = proto->getCallResultType(Context);
16106
16107 // Check that the object type isn't more qualified than the
16108 // member function we're calling.
16109 Qualifiers funcQuals = proto->getMethodQuals();
16110
16111 QualType objectType = op->getLHS()->getType();
16112 if (op->getOpcode() == BO_PtrMemI)
16113 objectType = objectType->castAs<PointerType>()->getPointeeType();
16114 Qualifiers objectQuals = objectType.getQualifiers();
16115
16116 Qualifiers difference = objectQuals - funcQuals;
16117 difference.removeObjCGCAttr();
16118 difference.removeAddressSpace();
16119 if (difference) {
16120 std::string qualsString = difference.getAsString();
16121 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16122 << fnType.getUnqualifiedType()
16123 << qualsString
16124 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16125 }
16126
16128 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16130
16131 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16132 call, nullptr))
16133 return ExprError();
16134
16135 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16136 return ExprError();
16137
16138 if (CheckOtherCall(call, proto))
16139 return ExprError();
16140
16141 return MaybeBindToTemporary(call);
16142 }
16143
16144 // We only try to build a recovery expr at this level if we can preserve
16145 // the return type, otherwise we return ExprError() and let the caller
16146 // recover.
16147 auto BuildRecoveryExpr = [&](QualType Type) {
16148 if (!AllowRecovery)
16149 return ExprError();
16150 std::vector<Expr *> SubExprs = {MemExprE};
16151 llvm::append_range(SubExprs, Args);
16152 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16153 Type);
16154 };
16155 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16156 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16157 RParenLoc, CurFPFeatureOverrides());
16158
16159 UnbridgedCastsSet UnbridgedCasts;
16160 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16161 return ExprError();
16162
16163 MemberExpr *MemExpr;
16164 CXXMethodDecl *Method = nullptr;
16165 bool HadMultipleCandidates = false;
16166 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16167 NestedNameSpecifier Qualifier = std::nullopt;
16168 if (isa<MemberExpr>(NakedMemExpr)) {
16169 MemExpr = cast<MemberExpr>(NakedMemExpr);
16171 FoundDecl = MemExpr->getFoundDecl();
16172 Qualifier = MemExpr->getQualifier();
16173 UnbridgedCasts.restore();
16174 } else {
16175 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16176 Qualifier = UnresExpr->getQualifier();
16177
16178 QualType ObjectType = UnresExpr->getBaseType();
16179 Expr::Classification ObjectClassification
16181 : UnresExpr->getBase()->Classify(Context);
16182
16183 // Add overload candidates
16184 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16186
16187 // FIXME: avoid copy.
16188 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16189 if (UnresExpr->hasExplicitTemplateArgs()) {
16190 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16191 TemplateArgs = &TemplateArgsBuffer;
16192 }
16193
16195 E = UnresExpr->decls_end(); I != E; ++I) {
16196
16197 QualType ExplicitObjectType = ObjectType;
16198
16199 NamedDecl *Func = *I;
16200 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16202 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16203
16204 bool HasExplicitParameter = false;
16205 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16206 M && M->hasCXXExplicitFunctionObjectParameter())
16207 HasExplicitParameter = true;
16208 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16209 M &&
16210 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16211 HasExplicitParameter = true;
16212
16213 if (HasExplicitParameter)
16214 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16215
16216 // Microsoft supports direct constructor calls.
16217 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16219 CandidateSet,
16220 /*SuppressUserConversions*/ false);
16221 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16222 // If explicit template arguments were provided, we can't call a
16223 // non-template member function.
16224 if (TemplateArgs)
16225 continue;
16226
16227 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16228 ObjectClassification, Args, CandidateSet,
16229 /*SuppressUserConversions=*/false);
16230 } else {
16232 I.getPair(), ActingDC, TemplateArgs,
16233 ExplicitObjectType, ObjectClassification,
16234 Args, CandidateSet,
16235 /*SuppressUserConversions=*/false);
16236 }
16237 }
16238
16239 HadMultipleCandidates = (CandidateSet.size() > 1);
16240
16241 DeclarationName DeclName = UnresExpr->getMemberName();
16242
16243 UnbridgedCasts.restore();
16244
16246 bool Succeeded = false;
16247 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16248 Best)) {
16249 case OR_Success:
16250 Method = cast<CXXMethodDecl>(Best->Function);
16251 FoundDecl = Best->FoundDecl;
16252 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16253 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16254 break;
16255 // If FoundDecl is different from Method (such as if one is a template
16256 // and the other a specialization), make sure DiagnoseUseOfDecl is
16257 // called on both.
16258 // FIXME: This would be more comprehensively addressed by modifying
16259 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16260 // being used.
16261 if (Method != FoundDecl.getDecl() &&
16263 break;
16264 Succeeded = true;
16265 break;
16266
16268 CandidateSet.NoteCandidates(
16270 UnresExpr->getMemberLoc(),
16271 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16272 << DeclName << MemExprE->getSourceRange()),
16273 *this, OCD_AllCandidates, Args);
16274 break;
16275 case OR_Ambiguous:
16276 CandidateSet.NoteCandidates(
16277 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16278 PDiag(diag::err_ovl_ambiguous_member_call)
16279 << DeclName << MemExprE->getSourceRange()),
16280 *this, OCD_AmbiguousCandidates, Args);
16281 break;
16282 case OR_Deleted:
16284 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16285 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16286 break;
16287 }
16288 // Overload resolution fails, try to recover.
16289 if (!Succeeded)
16290 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16291
16292 ExprResult Res =
16293 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16294 if (Res.isInvalid())
16295 return ExprError();
16296 MemExprE = Res.get();
16297
16298 // If overload resolution picked a static member
16299 // build a non-member call based on that function.
16300 if (Method->isStatic()) {
16301 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16302 ExecConfig, IsExecConfig);
16303 }
16304
16305 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16306 }
16307
16308 QualType ResultType = Method->getReturnType();
16310 ResultType = ResultType.getNonLValueExprType(Context);
16311
16312 assert(Method && "Member call to something that isn't a method?");
16313 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16314
16315 CallExpr *TheCall = nullptr;
16317 if (Method->isExplicitObjectMemberFunction()) {
16318 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16319 NewArgs))
16320 return ExprError();
16321
16322 // Build the actual expression node.
16323 ExprResult FnExpr =
16324 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16325 HadMultipleCandidates, MemExpr->getExprLoc());
16326 if (FnExpr.isInvalid())
16327 return ExprError();
16328
16329 TheCall =
16330 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16331 CurFPFeatureOverrides(), Proto->getNumParams());
16332 TheCall->setUsesMemberSyntax(true);
16333 } else {
16334 // Convert the object argument (for a non-static member function call).
16336 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16337 if (ObjectArg.isInvalid())
16338 return ExprError();
16339 MemExpr->setBase(ObjectArg.get());
16340 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16341 RParenLoc, CurFPFeatureOverrides(),
16342 Proto->getNumParams());
16343 }
16344
16345 // Check for a valid return type.
16346 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16347 TheCall, Method))
16348 return BuildRecoveryExpr(ResultType);
16349
16350 // Convert the rest of the arguments
16351 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16352 RParenLoc))
16353 return BuildRecoveryExpr(ResultType);
16354
16355 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16356
16357 if (CheckFunctionCall(Method, TheCall, Proto))
16358 return ExprError();
16359
16360 // In the case the method to call was not selected by the overloading
16361 // resolution process, we still need to handle the enable_if attribute. Do
16362 // that here, so it will not hide previous -- and more relevant -- errors.
16363 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16364 if (const EnableIfAttr *Attr =
16365 CheckEnableIf(Method, LParenLoc, Args, true)) {
16366 Diag(MemE->getMemberLoc(),
16367 diag::err_ovl_no_viable_member_function_in_call)
16368 << Method << Method->getSourceRange();
16369 Diag(Method->getLocation(),
16370 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16371 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16372 return ExprError();
16373 }
16374 }
16375
16377 TheCall->getDirectCallee()->isPureVirtual()) {
16378 const FunctionDecl *MD = TheCall->getDirectCallee();
16379
16380 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16382 Diag(MemExpr->getBeginLoc(),
16383 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16385 << MD->getParent();
16386
16387 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16388 if (getLangOpts().AppleKext)
16389 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16390 << MD->getParent() << MD->getDeclName();
16391 }
16392 }
16393
16394 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16395 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16396 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16397 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16398 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16399 MemExpr->getMemberLoc());
16400 }
16401
16403 TheCall->getDirectCallee());
16404}
16405
16408 SourceLocation LParenLoc,
16409 MultiExprArg Args,
16410 SourceLocation RParenLoc) {
16411 if (checkPlaceholderForOverload(*this, Obj))
16412 return ExprError();
16413 ExprResult Object = Obj;
16414
16415 UnbridgedCastsSet UnbridgedCasts;
16416 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16417 return ExprError();
16418
16419 assert(Object.get()->getType()->isRecordType() &&
16420 "Requires object type argument");
16421
16422 // C++ [over.call.object]p1:
16423 // If the primary-expression E in the function call syntax
16424 // evaluates to a class object of type "cv T", then the set of
16425 // candidate functions includes at least the function call
16426 // operators of T. The function call operators of T are obtained by
16427 // ordinary lookup of the name operator() in the context of
16428 // (E).operator().
16429 OverloadCandidateSet CandidateSet(LParenLoc,
16431 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16432
16433 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16434 diag::err_incomplete_object_call, Object.get()))
16435 return true;
16436
16437 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16438 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16441
16442 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16443 Oper != OperEnd; ++Oper) {
16444 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16445 Object.get()->Classify(Context), Args, CandidateSet,
16446 /*SuppressUserConversion=*/false);
16447 }
16448
16449 // When calling a lambda, both the call operator, and
16450 // the conversion operator to function pointer
16451 // are considered. But when constraint checking
16452 // on the call operator fails, it will also fail on the
16453 // conversion operator as the constraints are always the same.
16454 // As the user probably does not intend to perform a surrogate call,
16455 // we filter them out to produce better error diagnostics, ie to avoid
16456 // showing 2 failed overloads instead of one.
16457 bool IgnoreSurrogateFunctions = false;
16458 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16459 const OverloadCandidate &Candidate = *CandidateSet.begin();
16460 if (!Candidate.Viable &&
16462 IgnoreSurrogateFunctions = true;
16463 }
16464
16465 // C++ [over.call.object]p2:
16466 // In addition, for each (non-explicit in C++0x) conversion function
16467 // declared in T of the form
16468 //
16469 // operator conversion-type-id () cv-qualifier;
16470 //
16471 // where cv-qualifier is the same cv-qualification as, or a
16472 // greater cv-qualification than, cv, and where conversion-type-id
16473 // denotes the type "pointer to function of (P1,...,Pn) returning
16474 // R", or the type "reference to pointer to function of
16475 // (P1,...,Pn) returning R", or the type "reference to function
16476 // of (P1,...,Pn) returning R", a surrogate call function [...]
16477 // is also considered as a candidate function. Similarly,
16478 // surrogate call functions are added to the set of candidate
16479 // functions for each conversion function declared in an
16480 // accessible base class provided the function is not hidden
16481 // within T by another intervening declaration.
16482 const auto &Conversions = Record->getVisibleConversionFunctions();
16483 for (auto I = Conversions.begin(), E = Conversions.end();
16484 !IgnoreSurrogateFunctions && I != E; ++I) {
16485 NamedDecl *D = *I;
16486 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16487 if (isa<UsingShadowDecl>(D))
16488 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16489
16490 // Skip over templated conversion functions; they aren't
16491 // surrogates.
16493 continue;
16494
16496 if (!Conv->isExplicit()) {
16497 // Strip the reference type (if any) and then the pointer type (if
16498 // any) to get down to what might be a function type.
16499 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16500 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16501 ConvType = ConvPtrType->getPointeeType();
16502
16503 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16504 {
16505 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16506 Object.get(), Args, CandidateSet);
16507 }
16508 }
16509 }
16510
16511 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16512
16513 // Perform overload resolution.
16515 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16516 Best)) {
16517 case OR_Success:
16518 // Overload resolution succeeded; we'll build the appropriate call
16519 // below.
16520 break;
16521
16522 case OR_No_Viable_Function: {
16524 CandidateSet.empty()
16525 ? (PDiag(diag::err_ovl_no_oper)
16526 << Object.get()->getType() << /*call*/ 1
16527 << Object.get()->getSourceRange())
16528 : (PDiag(diag::err_ovl_no_viable_object_call)
16529 << Object.get()->getType() << Object.get()->getSourceRange());
16530 CandidateSet.NoteCandidates(
16531 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16532 OCD_AllCandidates, Args);
16533 break;
16534 }
16535 case OR_Ambiguous:
16536 if (!R.isAmbiguous())
16537 CandidateSet.NoteCandidates(
16538 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16539 PDiag(diag::err_ovl_ambiguous_object_call)
16540 << Object.get()->getType()
16541 << Object.get()->getSourceRange()),
16542 *this, OCD_AmbiguousCandidates, Args);
16543 break;
16544
16545 case OR_Deleted: {
16546 // FIXME: Is this diagnostic here really necessary? It seems that
16547 // 1. we don't have any tests for this diagnostic, and
16548 // 2. we already issue err_deleted_function_use for this later on anyway.
16549 StringLiteral *Msg = Best->Function->getDeletedMessage();
16550 CandidateSet.NoteCandidates(
16551 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16552 PDiag(diag::err_ovl_deleted_object_call)
16553 << Object.get()->getType() << (Msg != nullptr)
16554 << (Msg ? Msg->getString() : StringRef())
16555 << Object.get()->getSourceRange()),
16556 *this, OCD_AllCandidates, Args);
16557 break;
16558 }
16559 }
16560
16561 if (Best == CandidateSet.end())
16562 return true;
16563
16564 UnbridgedCasts.restore();
16565
16566 if (Best->Function == nullptr) {
16567 // Since there is no function declaration, this is one of the
16568 // surrogate candidates. Dig out the conversion function.
16569 CXXConversionDecl *Conv
16571 Best->Conversions[0].UserDefined.ConversionFunction);
16572
16573 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16574 Best->FoundDecl);
16575 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16576 return ExprError();
16577 assert(Conv == Best->FoundDecl.getDecl() &&
16578 "Found Decl & conversion-to-functionptr should be same, right?!");
16579 // We selected one of the surrogate functions that converts the
16580 // object parameter to a function pointer. Perform the conversion
16581 // on the object argument, then let BuildCallExpr finish the job.
16582
16583 // Create an implicit member expr to refer to the conversion operator.
16584 // and then call it.
16585 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16586 Conv, HadMultipleCandidates);
16587 if (Call.isInvalid())
16588 return ExprError();
16589 // Record usage of conversion in an implicit cast.
16591 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16592 nullptr, VK_PRValue, CurFPFeatureOverrides());
16593
16594 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16595 }
16596
16597 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16598
16599 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16600 // that calls this method, using Object for the implicit object
16601 // parameter and passing along the remaining arguments.
16602 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16603
16604 // An error diagnostic has already been printed when parsing the declaration.
16605 if (Method->isInvalidDecl())
16606 return ExprError();
16607
16608 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16609 unsigned NumParams = Proto->getNumParams();
16610
16611 DeclarationNameInfo OpLocInfo(
16612 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16613 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16614 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16615 Obj, HadMultipleCandidates,
16616 OpLocInfo.getLoc(),
16617 OpLocInfo.getInfo());
16618 if (NewFn.isInvalid())
16619 return true;
16620
16621 SmallVector<Expr *, 8> MethodArgs;
16622 MethodArgs.reserve(NumParams + 1);
16623
16624 bool IsError = false;
16625
16626 // Initialize the object parameter.
16628 if (Method->isExplicitObjectMemberFunction()) {
16629 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16630 } else {
16632 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16633 if (ObjRes.isInvalid())
16634 IsError = true;
16635 else
16636 Object = ObjRes;
16637 MethodArgs.push_back(Object.get());
16638 }
16639
16641 *this, MethodArgs, Method, Args, LParenLoc);
16642
16643 // If this is a variadic call, handle args passed through "...".
16644 if (Proto->isVariadic()) {
16645 // Promote the arguments (C99 6.5.2.2p7).
16646 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16648 Args[i], VariadicCallType::Method, nullptr);
16649 IsError |= Arg.isInvalid();
16650 MethodArgs.push_back(Arg.get());
16651 }
16652 }
16653
16654 if (IsError)
16655 return true;
16656
16657 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16658
16659 // Once we've built TheCall, all of the expressions are properly owned.
16660 QualType ResultTy = Method->getReturnType();
16662 ResultTy = ResultTy.getNonLValueExprType(Context);
16663
16665 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16667
16668 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16669 return true;
16670
16671 if (CheckFunctionCall(Method, TheCall, Proto))
16672 return true;
16673
16675}
16676
16678 SourceLocation OpLoc,
16679 bool *NoArrowOperatorFound) {
16680 assert(Base->getType()->isRecordType() &&
16681 "left-hand side must have class type");
16682
16684 return ExprError();
16685
16686 SourceLocation Loc = Base->getExprLoc();
16687
16688 // C++ [over.ref]p1:
16689 //
16690 // [...] An expression x->m is interpreted as (x.operator->())->m
16691 // for a class object x of type T if T::operator->() exists and if
16692 // the operator is selected as the best match function by the
16693 // overload resolution mechanism (13.3).
16694 DeclarationName OpName =
16695 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16697
16698 if (RequireCompleteType(Loc, Base->getType(),
16699 diag::err_typecheck_incomplete_tag, Base))
16700 return ExprError();
16701
16702 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16703 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16705
16706 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16707 Oper != OperEnd; ++Oper) {
16708 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16709 {}, CandidateSet,
16710 /*SuppressUserConversion=*/false);
16711 }
16712
16713 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16714
16715 // Perform overload resolution.
16717 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16718 case OR_Success:
16719 // Overload resolution succeeded; we'll build the call below.
16720 break;
16721
16722 case OR_No_Viable_Function: {
16723 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16724 if (CandidateSet.empty()) {
16725 QualType BaseType = Base->getType();
16726 if (NoArrowOperatorFound) {
16727 // Report this specific error to the caller instead of emitting a
16728 // diagnostic, as requested.
16729 *NoArrowOperatorFound = true;
16730 return ExprError();
16731 }
16732 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16733 << BaseType << Base->getSourceRange();
16734 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16735 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16736 << FixItHint::CreateReplacement(OpLoc, ".");
16737 }
16738 } else
16739 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16740 << "operator->" << Base->getSourceRange();
16741 CandidateSet.NoteCandidates(*this, Base, Cands);
16742 return ExprError();
16743 }
16744 case OR_Ambiguous:
16745 if (!R.isAmbiguous())
16746 CandidateSet.NoteCandidates(
16747 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16748 << "->" << Base->getType()
16749 << Base->getSourceRange()),
16751 return ExprError();
16752
16753 case OR_Deleted: {
16754 StringLiteral *Msg = Best->Function->getDeletedMessage();
16755 CandidateSet.NoteCandidates(
16756 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16757 << "->" << (Msg != nullptr)
16758 << (Msg ? Msg->getString() : StringRef())
16759 << Base->getSourceRange()),
16760 *this, OCD_AllCandidates, Base);
16761 return ExprError();
16762 }
16763 }
16764
16765 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16766
16767 // Convert the object parameter.
16768 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16769
16770 if (Method->isExplicitObjectMemberFunction()) {
16772 if (R.isInvalid())
16773 return ExprError();
16774 Base = R.get();
16775 } else {
16777 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16778 if (BaseResult.isInvalid())
16779 return ExprError();
16780 Base = BaseResult.get();
16781 }
16782
16783 // Build the operator call.
16784 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16785 Base, HadMultipleCandidates, OpLoc);
16786 if (FnExpr.isInvalid())
16787 return ExprError();
16788
16789 QualType ResultTy = Method->getReturnType();
16791 ResultTy = ResultTy.getNonLValueExprType(Context);
16792
16793 CallExpr *TheCall =
16794 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16795 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16796
16797 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16798 return ExprError();
16799
16800 if (CheckFunctionCall(Method, TheCall,
16801 Method->getType()->castAs<FunctionProtoType>()))
16802 return ExprError();
16803
16805}
16806
16808 DeclarationNameInfo &SuffixInfo,
16809 ArrayRef<Expr*> Args,
16810 SourceLocation LitEndLoc,
16811 TemplateArgumentListInfo *TemplateArgs) {
16812 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16813
16814 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16816 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16817 TemplateArgs);
16818
16819 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16820
16821 // Perform overload resolution. This will usually be trivial, but might need
16822 // to perform substitutions for a literal operator template.
16824 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16825 case OR_Success:
16826 case OR_Deleted:
16827 break;
16828
16830 CandidateSet.NoteCandidates(
16831 PartialDiagnosticAt(UDSuffixLoc,
16832 PDiag(diag::err_ovl_no_viable_function_in_call)
16833 << R.getLookupName()),
16834 *this, OCD_AllCandidates, Args);
16835 return ExprError();
16836
16837 case OR_Ambiguous:
16838 CandidateSet.NoteCandidates(
16839 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16840 << R.getLookupName()),
16841 *this, OCD_AmbiguousCandidates, Args);
16842 return ExprError();
16843 }
16844
16845 FunctionDecl *FD = Best->Function;
16846 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16847 nullptr, HadMultipleCandidates,
16848 SuffixInfo.getLoc(),
16849 SuffixInfo.getInfo());
16850 if (Fn.isInvalid())
16851 return true;
16852
16853 // Check the argument types. This should almost always be a no-op, except
16854 // that array-to-pointer decay is applied to string literals.
16855 Expr *ConvArgs[2];
16856 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16859 SourceLocation(), Args[ArgIdx]);
16860 if (InputInit.isInvalid())
16861 return true;
16862 ConvArgs[ArgIdx] = InputInit.get();
16863 }
16864
16865 QualType ResultTy = FD->getReturnType();
16867 ResultTy = ResultTy.getNonLValueExprType(Context);
16868
16870 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16871 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16872
16873 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16874 return ExprError();
16875
16876 if (CheckFunctionCall(FD, UDL, nullptr))
16877 return ExprError();
16878
16880}
16881
16884 SourceLocation RangeLoc,
16885 const DeclarationNameInfo &NameInfo,
16886 LookupResult &MemberLookup,
16887 OverloadCandidateSet *CandidateSet,
16888 Expr *Range, ExprResult *CallExpr) {
16889 Scope *S = nullptr;
16890
16892 if (!MemberLookup.empty()) {
16893 ExprResult MemberRef =
16894 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16895 /*IsPtr=*/false, CXXScopeSpec(),
16896 /*TemplateKWLoc=*/SourceLocation(),
16897 /*FirstQualifierInScope=*/nullptr,
16898 MemberLookup,
16899 /*TemplateArgs=*/nullptr, S);
16900 if (MemberRef.isInvalid()) {
16901 *CallExpr = ExprError();
16902 return FRS_DiagnosticIssued;
16903 }
16904 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16905 if (CallExpr->isInvalid()) {
16906 *CallExpr = ExprError();
16907 return FRS_DiagnosticIssued;
16908 }
16909 } else {
16910 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16912 NameInfo, UnresolvedSet<0>());
16913 if (FnR.isInvalid())
16914 return FRS_DiagnosticIssued;
16916
16917 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16918 CandidateSet, CallExpr);
16919 if (CandidateSet->empty() || CandidateSetError) {
16920 *CallExpr = ExprError();
16921 return FRS_NoViableFunction;
16922 }
16924 OverloadingResult OverloadResult =
16925 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16926
16927 if (OverloadResult == OR_No_Viable_Function) {
16928 *CallExpr = ExprError();
16929 return FRS_NoViableFunction;
16930 }
16931 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16932 Loc, nullptr, CandidateSet, &Best,
16933 OverloadResult,
16934 /*AllowTypoCorrection=*/false);
16935 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16936 *CallExpr = ExprError();
16937 return FRS_DiagnosticIssued;
16938 }
16939 }
16940 return FRS_Success;
16941}
16942
16944 FunctionDecl *Fn) {
16945 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16946 ExprResult SubExpr =
16947 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16948 if (SubExpr.isInvalid())
16949 return ExprError();
16950 if (SubExpr.get() == PE->getSubExpr())
16951 return PE;
16952
16953 return new (Context)
16954 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16955 }
16956
16957 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16958 ExprResult SubExpr =
16959 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16960 if (SubExpr.isInvalid())
16961 return ExprError();
16962 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16963 SubExpr.get()->getType()) &&
16964 "Implicit cast type cannot be determined from overload");
16965 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16966 if (SubExpr.get() == ICE->getSubExpr())
16967 return ICE;
16968
16969 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16970 SubExpr.get(), nullptr, ICE->getValueKind(),
16972 }
16973
16974 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16975 if (!GSE->isResultDependent()) {
16976 ExprResult SubExpr =
16977 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16978 if (SubExpr.isInvalid())
16979 return ExprError();
16980 if (SubExpr.get() == GSE->getResultExpr())
16981 return GSE;
16982
16983 // Replace the resulting type information before rebuilding the generic
16984 // selection expression.
16985 ArrayRef<Expr *> A = GSE->getAssocExprs();
16986 SmallVector<Expr *, 4> AssocExprs(A);
16987 unsigned ResultIdx = GSE->getResultIndex();
16988 AssocExprs[ResultIdx] = SubExpr.get();
16989
16990 if (GSE->isExprPredicate())
16992 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16993 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16994 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16995 ResultIdx);
16997 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16998 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16999 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17000 ResultIdx);
17001 }
17002 // Rather than fall through to the unreachable, return the original generic
17003 // selection expression.
17004 return GSE;
17005 }
17006
17007 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17008 assert(UnOp->getOpcode() == UO_AddrOf &&
17009 "Can only take the address of an overloaded function");
17010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17011 if (!Method->isImplicitObjectMemberFunction()) {
17012 // Do nothing: the address of static and
17013 // explicit object member functions is a (non-member) function pointer.
17014 } else {
17015 // Fix the subexpression, which really has to be an
17016 // UnresolvedLookupExpr holding an overloaded member function
17017 // or template.
17018 ExprResult SubExpr =
17019 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17020 if (SubExpr.isInvalid())
17021 return ExprError();
17022 if (SubExpr.get() == UnOp->getSubExpr())
17023 return UnOp;
17024
17025 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17026 SubExpr.get(), Method))
17027 return ExprError();
17028
17029 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17030 "fixed to something other than a decl ref");
17031 NestedNameSpecifier Qualifier =
17032 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17033 assert(Qualifier &&
17034 "fixed to a member ref with no nested name qualifier");
17035
17036 // We have taken the address of a pointer to member
17037 // function. Perform the computation here so that we get the
17038 // appropriate pointer to member type.
17039 QualType MemPtrType = Context.getMemberPointerType(
17040 Fn->getType(), Qualifier,
17041 cast<CXXRecordDecl>(Method->getDeclContext()));
17042 // Under the MS ABI, lock down the inheritance model now.
17043 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17044 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17045
17046 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17047 MemPtrType, VK_PRValue, OK_Ordinary,
17048 UnOp->getOperatorLoc(), false,
17050 }
17051 }
17052 ExprResult SubExpr =
17053 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17054 if (SubExpr.isInvalid())
17055 return ExprError();
17056 if (SubExpr.get() == UnOp->getSubExpr())
17057 return UnOp;
17058
17059 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17060 SubExpr.get());
17061 }
17062
17063 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17064 if (Found.getAccess() == AS_none) {
17066 }
17067 // FIXME: avoid copy.
17068 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17069 if (ULE->hasExplicitTemplateArgs()) {
17070 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17071 TemplateArgs = &TemplateArgsBuffer;
17072 }
17073
17074 QualType Type = Fn->getType();
17075 ExprValueKind ValueKind =
17076 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17077 ? VK_LValue
17078 : VK_PRValue;
17079
17080 // FIXME: Duplicated from BuildDeclarationNameExpr.
17081 if (unsigned BID = Fn->getBuiltinID()) {
17082 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17083 Type = Context.BuiltinFnTy;
17084 ValueKind = VK_PRValue;
17085 }
17086 }
17087
17089 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17090 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17091 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17092 return DRE;
17093 }
17094
17095 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17096 // FIXME: avoid copy.
17097 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17098 if (MemExpr->hasExplicitTemplateArgs()) {
17099 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17100 TemplateArgs = &TemplateArgsBuffer;
17101 }
17102
17103 Expr *Base;
17104
17105 // If we're filling in a static method where we used to have an
17106 // implicit member access, rewrite to a simple decl ref.
17107 if (MemExpr->isImplicitAccess()) {
17108 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17110 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17111 MemExpr->getQualifierLoc(), Found.getDecl(),
17112 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17113 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17114 return DRE;
17115 } else {
17116 SourceLocation Loc = MemExpr->getMemberLoc();
17117 if (MemExpr->getQualifier())
17118 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17119 Base =
17120 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17121 }
17122 } else
17123 Base = MemExpr->getBase();
17124
17125 ExprValueKind valueKind;
17126 QualType type;
17127 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17128 valueKind = VK_LValue;
17129 type = Fn->getType();
17130 } else {
17131 valueKind = VK_PRValue;
17132 type = Context.BoundMemberTy;
17133 }
17134
17135 return BuildMemberExpr(
17136 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17137 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17138 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17139 type, valueKind, OK_Ordinary, TemplateArgs);
17140 }
17141
17142 llvm_unreachable("Invalid reference to overloaded function");
17143}
17144
17150
17151bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17153 if (!PartialOverloading || !Function)
17154 return true;
17155 if (Function->isVariadic())
17156 return false;
17157 if (const auto *Proto =
17158 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17159 if (Proto->isTemplateVariadic())
17160 return false;
17161 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17162 if (const auto *Proto =
17163 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17164 if (Proto->isTemplateVariadic())
17165 return false;
17166 return true;
17167}
17168
17170 DeclarationName Name,
17171 OverloadCandidateSet &CandidateSet,
17172 FunctionDecl *Fn, MultiExprArg Args,
17173 bool IsMember) {
17174 StringLiteral *Msg = Fn->getDeletedMessage();
17175 CandidateSet.NoteCandidates(
17176 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17177 << IsMember << Name << (Msg != nullptr)
17178 << (Msg ? Msg->getString() : StringRef())
17179 << Range),
17180 *this, OCD_AllCandidates, Args);
17181}
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 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 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:463
bool isFloat() const
Definition APValue.h:468
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:794
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:944
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:910
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
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:3893
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:280
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3723
QualType getElementType() const
Definition TypeBase.h:3735
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8091
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2179
StringRef getOpcodeStr() const
Definition Expr.h:4104
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
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:4982
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4179
Pointer to a block type.
Definition TypeBase.h:3543
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
Kind getKind() const
Definition TypeBase.h:3213
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:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3056
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2975
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2979
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1977
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
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:1516
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3126
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3107
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3325
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:3276
QualType getElementType() const
Definition TypeBase.h:3286
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:5004
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4407
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4404
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1463
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:777
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:762
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:753
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
bool isPRValue() const
Definition Expr.h:390
bool isXValue() const
Definition Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:395
bool isRValue() const
Definition Expr.h:391
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
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:3338
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4208
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4047
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:412
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
ExtVectorType - Extended vector type.
Definition TypeBase.h:4268
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4193
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3762
param_iterator param_end()
Definition Decl.h:2787
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3666
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4264
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4313
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3747
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3133
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4329
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4257
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3869
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4130
bool isConsteval() const
Definition Decl.h:2482
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3710
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2862
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition Decl.cpp:3715
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5773
unsigned getNumParams() const
Definition TypeBase.h:5547
Qualifiers getMethodQuals() const
Definition TypeBase.h:5695
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5709
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:4576
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4647
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4504
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
ExtInfo getExtInfo() const
Definition TypeBase.h:4821
CallingConv getCallConv() const
Definition TypeBase.h:4820
QualType getReturnType() const
Definition TypeBase.h:4805
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4833
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:4604
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:3853
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2072
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:5299
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5414
unsigned getNumInits() const
Definition Expr.h:5329
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2495
const Expr * getInit(unsigned Init) const
Definition Expr.h:5353
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2513
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:974
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3618
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
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition Lookup.h:643
const UnresolvedSetImpl & asUnresolvedSet() const
Definition Lookup.h:354
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4352
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3553
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3475
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3461
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3582
Expr * getBase() const
Definition Expr.h:3441
void setBase(Expr *E)
Definition Expr.h:3440
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1793
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3559
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3451
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3686
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5450
QualType getPointeeType() const
Definition TypeBase.h:3672
Describes a module or submodule.
Definition Module.h:144
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7854
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7910
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:7999
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7968
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7922
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7962
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1841
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7974
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h: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:3128
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3280
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3189
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3244
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3241
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3219
decls_iterator decls_begin() const
Definition ExprCXX.h:3221
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3232
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3254
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3250
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3224
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3238
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:2182
Represents a parameter to a function.
Definition Decl.h:1790
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3058
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5076
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8376
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8370
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8381
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1225
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8292
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8332
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:8477
QualType getCanonicalType() const
Definition TypeBase.h:8344
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
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:8446
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8365
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8413
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8338
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8457
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8324
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8232
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8239
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4660
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:3636
Represents a struct/union/class.
Definition Decl.h:4324
field_range fields() const
Definition Decl.h:4527
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
QualType getPointeeType() const
Definition TypeBase.h:3592
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:1500
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1544
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:186
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp: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:10329
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:6376
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6405
RAII class to control scope of DeferDiags.
Definition Sema.h:10064
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1362
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1397
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:12476
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12510
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:856
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:10082
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:9353
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9380
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9365
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9361
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:412
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:1448
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:10412
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10415
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10421
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10419
@ AR_dependent
Definition Sema.h:1663
@ AR_accessible
Definition Sema.h:1661
@ AR_inaccessible
Definition Sema.h:1662
@ AR_delayed
Definition Sema.h:1664
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:2052
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:1660
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:1288
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:680
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:924
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:1493
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:755
ASTContext & getASTContext() const
Definition Sema.h:927
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
@ FRS_Success
Definition Sema.h:10800
@ FRS_DiagnosticIssued
Definition Sema.h:10802
@ FRS_NoViableFunction
Definition Sema.h:10801
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9346
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:10133
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:1192
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:3601
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:12174
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:920
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:1286
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:1458
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9345
MemberPointerConversionDirection
Definition Sema.h:10253
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:10440
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:640
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:15495
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:6995
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:1421
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8199
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:13963
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:7493
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:13696
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:15450
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:6761
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6730
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:10245
SourceManager & SourceMgr
Definition Sema.h:1291
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1290
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:516
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:6438
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:1428
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:8681
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:362
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
StringRef getString() const
Definition Expr.h:1867
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:678
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:732
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:717
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3538
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBlockPointerType() const
Definition TypeBase.h:8549
bool isVoidType() const
Definition TypeBase.h:8891
bool isBooleanType() const
Definition TypeBase.h:9021
bool isObjCBuiltinType() const
Definition TypeBase.h:8755
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
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:1952
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:788
bool isIncompleteArrayType() const
Definition TypeBase.h:8636
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2206
bool isFloat16Type() const
Definition TypeBase.h:8900
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:725
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2116
bool isRValueReferenceType() const
Definition TypeBase.h:8561
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:8632
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9051
bool isArrayType() const
Definition TypeBase.h:8628
bool isCharType() const
Definition Type.cpp:2133
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:8959
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2338
bool isPointerType() const
Definition TypeBase.h:8529
bool isArrayParameterType() const
Definition TypeBase.h:8644
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8935
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2574
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
bool isReferenceType() const
Definition TypeBase.h:8553
bool isEnumeralType() const
Definition TypeBase.h:8660
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2104
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8725
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9009
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2169
bool isExtVectorBoolType() const
Definition TypeBase.h:8676
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8712
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2791
bool isLValueReferenceType() const
Definition TypeBase.h:8557
bool isBitIntType() const
Definition TypeBase.h:8800
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2412
bool isAnyComplexType() const
Definition TypeBase.h:8664
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8947
bool isHalfType() const
Definition TypeBase.h:8895
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8873
bool isQueueT() const
Definition TypeBase.h:8781
bool isMemberPointerType() const
Definition TypeBase.h:8610
bool isObjCIdType() const
Definition TypeBase.h:8737
bool isMatrixType() const
Definition TypeBase.h:8692
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9027
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8773
bool isBFloat16Type() const
Definition TypeBase.h:8912
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8525
bool isObjCObjectPointerType() const
Definition TypeBase.h:8704
bool isVectorType() const
Definition TypeBase.h:8668
bool isObjCClassType() const
Definition TypeBase.h:8743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2321
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2922
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8848
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:2254
bool isAnyPointerType() const
Definition TypeBase.h:8537
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8769
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isNullPtrType() const
Definition TypeBase.h:8928
bool isRecordType() const
Definition TypeBase.h:8656
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1429
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:5039
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1405
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:230
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:811
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:822
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:818
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:814
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:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h: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:1042
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h: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
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h: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:149
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h: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:178
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:826
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:829
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:834
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:832
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:830
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:833
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:5882
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:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
Extra information about a function prototype.
Definition TypeBase.h:5354
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5359
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:10532
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10539
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13124
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13212
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13250
Abstract class used to diagnose incomplete types.
Definition Sema.h:8280
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.