clang 24.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
57
59 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
66 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
67 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
68 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
69 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
70 return ExprError();
71 // If FoundDecl is different from Fn (such as if one is a template
72 // and the other a specialization), make sure DiagnoseUseOfDecl is
73 // called on both.
74 // FIXME: This would be more comprehensively addressed by modifying
75 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
76 // being used.
77 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
78 return ExprError();
79 DeclRefExpr *DRE = new (S.Context)
80 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
81 if (HadMultipleCandidates)
82 DRE->setHadMultipleCandidates(true);
83
85 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
86 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
87 S.ResolveExceptionSpec(Loc, FPT);
88 DRE->setType(Fn->getType());
89 }
90 }
91 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
92 CK_FunctionToPointerDecay);
93}
94
95static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
96 bool InOverloadResolution,
98 bool CStyle,
99 bool AllowObjCWritebackConversion);
100
102 QualType &ToType,
103 bool InOverloadResolution,
105 bool CStyle);
107IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
109 OverloadCandidateSet& Conversions,
110 AllowedExplicit AllowExplicit,
111 bool AllowObjCConversionOnExplicit);
112
115 const StandardConversionSequence& SCS1,
116 const StandardConversionSequence& SCS2);
117
120 const StandardConversionSequence& SCS1,
121 const StandardConversionSequence& SCS2);
122
125 const StandardConversionSequence &SCS1,
126 const StandardConversionSequence &SCS2);
127
130 const StandardConversionSequence& SCS1,
131 const StandardConversionSequence& SCS2);
132
133/// GetConversionRank - Retrieve the implicit conversion rank
134/// corresponding to the given implicit conversion kind.
136 static const ImplicitConversionRank Rank[] = {
163 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Event_Conversion
166 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
167 // it was omitted by the patch that added
168 // ICK_Zero_Queue_Conversion
177 };
178 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
179 return Rank[(int)Kind];
180}
181
200
201/// GetImplicitConversionName - Return the name of this kind of
202/// implicit conversion.
204 static const char *const Name[] = {
205 "No conversion",
206 "Lvalue-to-rvalue",
207 "Array-to-pointer",
208 "Function-to-pointer",
209 "Function pointer conversion",
210 "Qualification",
211 "Integral promotion",
212 "Floating point promotion",
213 "Complex promotion",
214 "Integral conversion",
215 "Floating conversion",
216 "Complex conversion",
217 "Floating-integral conversion",
218 "Pointer conversion",
219 "Pointer-to-member conversion",
220 "Boolean conversion",
221 "Compatible-types conversion",
222 "Derived-to-base conversion",
223 "Vector conversion",
224 "SVE Vector conversion",
225 "RVV Vector conversion",
226 "Vector splat",
227 "Complex-real conversion",
228 "Block Pointer conversion",
229 "Transparent Union Conversion",
230 "Writeback conversion",
231 "OpenCL Zero Event Conversion",
232 "OpenCL Zero Queue Conversion",
233 "C specific type conversion",
234 "Incompatible pointer conversion",
235 "Fixed point conversion",
236 "HLSL vector truncation",
237 "HLSL matrix truncation",
238 "Non-decaying array conversion",
239 "HLSL vector splat",
240 "HLSL matrix splat",
241 };
242 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
243 return Name[Kind];
244}
245
246/// StandardConversionSequence - Set the standard conversion
247/// sequence to the identity conversion.
265
266/// getRank - Retrieve the rank of this standard conversion sequence
267/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
268/// implicit conversions.
281
282/// isPointerConversionToBool - Determines whether this conversion is
283/// a conversion of a pointer or pointer-to-member to bool. This is
284/// used as part of the ranking of standard conversion sequences
285/// (C++ 13.3.3.2p4).
287 // Note that FromType has not necessarily been transformed by the
288 // array-to-pointer or function-to-pointer implicit conversions, so
289 // check for their presence as well as checking whether FromType is
290 // a pointer.
291 if (getToType(1)->isBooleanType() &&
292 (getFromType()->isPointerType() ||
293 getFromType()->isMemberPointerType() ||
294 getFromType()->isObjCObjectPointerType() ||
295 getFromType()->isBlockPointerType() ||
297 return true;
298
299 return false;
300}
301
302/// isPointerConversionToVoidPointer - Determines whether this
303/// conversion is a conversion of a pointer to a void pointer. This is
304/// used as part of the ranking of standard conversion sequences (C++
305/// 13.3.3.2p4).
306bool
309 QualType FromType = getFromType();
310 QualType ToType = getToType(1);
311
312 // Note that FromType has not necessarily been transformed by the
313 // array-to-pointer implicit conversion, so check for its presence
314 // and redo the conversion to get a pointer.
316 FromType = Context.getArrayDecayedType(FromType);
317
318 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
319 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
320 return ToPtrType->getPointeeType()->isVoidType();
321
322 return false;
323}
324
325/// Skip any implicit casts which could be either part of a narrowing conversion
326/// or after one in an implicit conversion.
328 const Expr *Converted) {
329 // We can have cleanups wrapping the converted expression; these need to be
330 // preserved so that destructors run if necessary.
331 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
332 Expr *Inner =
333 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
334 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
335 EWC->getObjects());
336 }
337
338 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
339 switch (ICE->getCastKind()) {
340 case CK_NoOp:
341 case CK_IntegralCast:
342 case CK_IntegralToBoolean:
343 case CK_IntegralToFloating:
344 case CK_BooleanToSignedIntegral:
345 case CK_FloatingToIntegral:
346 case CK_FloatingToBoolean:
347 case CK_FloatingCast:
348 Converted = ICE->getSubExpr();
349 continue;
350
351 default:
352 return Converted;
353 }
354 }
355
356 return Converted;
357}
358
359/// Check if this standard conversion sequence represents a narrowing
360/// conversion, according to C++11 [dcl.init.list]p7.
361///
362/// \param Ctx The AST context.
363/// \param Converted The result of applying this standard conversion sequence.
364/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
365/// value of the expression prior to the narrowing conversion.
366/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
367/// type of the expression prior to the narrowing conversion.
368/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
369/// from floating point types to integral types should be ignored.
370/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
371/// to conform MSVC compiler behavior.
373 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
374 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
375 bool AllowRelaxedEval) const {
376 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
377 "narrowing check outside C++");
378
379 // C++11 [dcl.init.list]p7:
380 // A narrowing conversion is an implicit conversion ...
381 QualType FromType = getToType(0);
382 QualType ToType = getToType(1);
383
384 // A conversion to an enumeration type is narrowing if the conversion to
385 // the underlying type is narrowing. This only arises for expressions of
386 // the form 'Enum{init}'.
387 if (const auto *ED = ToType->getAsEnumDecl())
388 ToType = ED->getIntegerType();
389
390 switch (Second) {
391 // 'bool' is an integral type; dispatch to the right place to handle it.
393 if (FromType->isRealFloatingType())
394 goto FloatingIntegralConversion;
396 goto IntegralConversion;
397 // -- from a pointer type or pointer-to-member type to bool, or
398 return NK_Type_Narrowing;
399
400 // -- from a floating-point type to an integer type, or
401 //
402 // -- from an integer type or unscoped enumeration type to a floating-point
403 // type, except where the source is a constant expression and the actual
404 // value after conversion will fit into the target type and will produce
405 // the original value when converted back to the original type, or
407 FloatingIntegralConversion:
408 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
409 return NK_Type_Narrowing;
410 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
411 ToType->isRealFloatingType()) {
412 if (IgnoreFloatToIntegralConversion)
413 return NK_Not_Narrowing;
414 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
415 assert(Initializer && "Unknown conversion expression");
416
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
420
421 if (std::optional<llvm::APSInt> IntConstantValue =
422 Initializer->getIntegerConstantExpr(Ctx)) {
423 // Convert the integer to the floating type.
424 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
425 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
426 llvm::APFloat::rmNearestTiesToEven);
427 // And back.
428 llvm::APSInt ConvertedValue = *IntConstantValue;
429 bool ignored;
430 llvm::APFloat::opStatus Status = Result.convertToInteger(
431 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
432 // If the converted-back integer has unspecified value, or if the
433 // resulting value is different, this was a narrowing conversion.
434 if (Status == llvm::APFloat::opInvalidOp ||
435 *IntConstantValue != ConvertedValue) {
436 ConstantValue = APValue(*IntConstantValue);
437 ConstantType = Initializer->getType();
439 }
440 } else {
441 // Variables are always narrowings.
443 }
444 }
445 return NK_Not_Narrowing;
446
447 // -- from long double to double or float, or from double to float, except
448 // where the source is a constant expression and the actual value after
449 // conversion is within the range of values that can be represented (even
450 // if it cannot be represented exactly), or
452 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
453 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
454 // FromType is larger than ToType.
455 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
456
457 // If it's value-dependent, we can't tell whether it's narrowing.
458 if (Initializer->isValueDependent())
460
462 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
463 ((Ctx.getLangOpts().CPlusPlus &&
464 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue,
465 AllowRelaxedEval)))) {
466 // Constant!
467 if (Ctx.getLangOpts().C23)
468 ConstantValue = R.Val;
469 assert(ConstantValue.isFloat());
470 llvm::APFloat FloatVal = ConstantValue.getFloat();
471 // Convert the source value into the target type.
472 bool ignored;
473 llvm::APFloat Converted = FloatVal;
474 llvm::APFloat::opStatus ConvertStatus =
475 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
476 llvm::APFloat::rmNearestTiesToEven, &ignored);
477 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
478 llvm::APFloat::rmNearestTiesToEven, &ignored);
479 if (Ctx.getLangOpts().C23) {
480 if (FloatVal.isNaN() && Converted.isNaN() &&
481 !FloatVal.isSignaling() && !Converted.isSignaling()) {
482 // Quiet NaNs are considered the same value, regardless of
483 // payloads.
484 return NK_Not_Narrowing;
485 }
486 // For normal values, check exact equality.
487 if (!Converted.bitwiseIsEqual(FloatVal)) {
488 ConstantType = Initializer->getType();
490 }
491 } else {
492 // If there was no overflow, the source value is within the range of
493 // values that can be represented.
494 if (ConvertStatus & llvm::APFloat::opOverflow) {
495 ConstantType = Initializer->getType();
497 }
498 }
499 } else {
501 }
502 }
503 return NK_Not_Narrowing;
504
505 // -- from an integer type or unscoped enumeration type to an integer type
506 // that cannot represent all the values of the original type, except where
507 // (CWG2627) -- the source is a bit-field whose width w is less than that
508 // of its type (or, for an enumeration type, its underlying type) and the
509 // target type can represent all the values of a hypothetical extended
510 // integer type with width w and with the same signedness as the original
511 // type or
512 // -- the source is a constant expression and the actual value after
513 // conversion will fit into the target type and will produce the original
514 // value when converted back to the original type.
516 IntegralConversion: {
517 assert(FromType->isIntegralOrUnscopedEnumerationType());
518 assert(ToType->isIntegralOrUnscopedEnumerationType());
519 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
520 unsigned FromWidth = Ctx.getIntWidth(FromType);
521 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
522 const unsigned ToWidth = Ctx.getIntWidth(ToType);
523
524 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
525 bool ToSigned, unsigned ToWidth) {
526 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
527 !(FromSigned && !ToSigned);
528 };
529
530 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // Not all values of FromType can be represented in ToType.
534 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
535
536 bool DependentBitField = false;
537 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
538 if (BitField->getBitWidth()->isValueDependent())
539 DependentBitField = true;
540 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
541 BitFieldWidth < FromWidth) {
542 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
543 return NK_Not_Narrowing;
544
545 // The initializer will be truncated to the bit-field width
546 FromWidth = BitFieldWidth;
547 }
548 }
549
550 // If it's value-dependent, we can't tell whether it's narrowing.
551 if (Initializer->isValueDependent())
553
554 std::optional<llvm::APSInt> OptInitializerValue =
555 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
556 if (!OptInitializerValue) {
557 // If the bit-field width was dependent, it might end up being small
558 // enough to fit in the target type (unless the target type is unsigned
559 // and the source type is signed, in which case it will never fit)
560 if (DependentBitField && !(FromSigned && !ToSigned))
562
563 // Otherwise, such a conversion is always narrowing
565 }
566 llvm::APSInt &InitializerValue = *OptInitializerValue;
567 bool Narrowing = false;
568 if (FromWidth < ToWidth) {
569 // Negative -> unsigned is narrowing. Otherwise, more bits is never
570 // narrowing.
571 if (InitializerValue.isSigned() && InitializerValue.isNegative())
572 Narrowing = true;
573 } else {
574 // Add a bit to the InitializerValue so we don't have to worry about
575 // signed vs. unsigned comparisons.
576 InitializerValue =
577 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
578 // Convert the initializer to and from the target width and signed-ness.
579 llvm::APSInt ConvertedValue = InitializerValue;
580 ConvertedValue = ConvertedValue.trunc(ToWidth);
581 ConvertedValue.setIsSigned(ToSigned);
582 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
583 ConvertedValue.setIsSigned(InitializerValue.isSigned());
584 // If the result is different, this was a narrowing conversion.
585 if (ConvertedValue != InitializerValue)
586 Narrowing = true;
587 }
588 if (Narrowing) {
589 ConstantType = Initializer->getType();
590 ConstantValue = APValue(InitializerValue);
592 }
593
594 return NK_Not_Narrowing;
595 }
596 case ICK_Complex_Real:
597 if (FromType->isComplexType() && !ToType->isComplexType())
598 return NK_Type_Narrowing;
599 return NK_Not_Narrowing;
600
602 if (Ctx.getLangOpts().C23) {
603 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
605 if (Initializer->EvaluateAsRValue(R, Ctx)) {
606 ConstantValue = R.Val;
607 assert(ConstantValue.isFloat());
608 llvm::APFloat FloatVal = ConstantValue.getFloat();
609 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
610 // value, the unqualified versions of the type of the initializer and
611 // the corresponding real type of the object declared shall be
612 // compatible.
613 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
614 ConstantType = Initializer->getType();
616 }
617 }
618 }
619 return NK_Not_Narrowing;
620 default:
621 // Other kinds of conversions are not narrowings.
622 return NK_Not_Narrowing;
623 }
624}
625
626/// dump - Print this standard conversion sequence to standard
627/// error. Useful for debugging overloading issues.
628LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
629 raw_ostream &OS = llvm::errs();
630 bool PrintedSomething = false;
631 if (First != ICK_Identity) {
633 PrintedSomething = true;
634 }
635
636 if (Second != ICK_Identity) {
637 if (PrintedSomething) {
638 OS << " -> ";
639 }
641
642 if (CopyConstructor) {
643 OS << " (by copy constructor)";
644 } else if (DirectBinding) {
645 OS << " (direct reference binding)";
646 } else if (ReferenceBinding) {
647 OS << " (reference binding)";
648 }
649 PrintedSomething = true;
650 }
651
652 if (Third != ICK_Identity) {
653 if (PrintedSomething) {
654 OS << " -> ";
655 }
657 PrintedSomething = true;
658 }
659
660 if (!PrintedSomething) {
661 OS << "No conversions required";
662 }
663}
664
665/// dump - Print this user-defined conversion sequence to standard
666/// error. Useful for debugging overloading issues.
668 raw_ostream &OS = llvm::errs();
669 if (Before.First || Before.Second || Before.Third) {
670 Before.dump();
671 OS << " -> ";
672 }
674 OS << '\'' << *ConversionFunction << '\'';
675 else
676 OS << "aggregate initialization";
677 if (After.First || After.Second || After.Third) {
678 OS << " -> ";
679 After.dump();
680 }
681}
682
683/// dump - Print this implicit conversion sequence to standard
684/// error. Useful for debugging overloading issues.
686 raw_ostream &OS = llvm::errs();
688 OS << "Worst list element conversion: ";
689 switch (ConversionKind) {
691 OS << "Standard conversion: ";
692 Standard.dump();
693 break;
695 OS << "User-defined conversion: ";
696 UserDefined.dump();
697 break;
699 OS << "Ellipsis conversion";
700 break;
702 OS << "Ambiguous conversion";
703 break;
704 case BadConversion:
705 OS << "Bad conversion";
706 break;
707 }
708
709 OS << "\n";
710}
711
715
717 conversions().~ConversionSet();
718}
719
720void
726
727namespace {
728 // Structure used by DeductionFailureInfo to store
729 // template argument information.
730 struct DFIArguments {
731 TemplateArgument FirstArg;
732 TemplateArgument SecondArg;
733 };
734 // Structure used by DeductionFailureInfo to store
735 // template parameter and template argument information.
736 struct DFIParamWithArguments : DFIArguments {
737 TemplateParameter Param;
738 };
739 // Structure used by DeductionFailureInfo to store template argument
740 // information and the index of the problematic call argument.
741 struct DFIDeducedMismatchArgs : DFIArguments {
742 TemplateArgumentList *TemplateArgs;
743 unsigned CallArgIndex;
744 };
745 // Structure used by DeductionFailureInfo to store information about
746 // unsatisfied constraints.
747 struct CNSInfo {
748 TemplateArgumentList *TemplateArgs;
749 ConstraintSatisfaction Satisfaction;
750 };
751}
752
753/// Convert from Sema's representation of template deduction information
754/// to the form used in overload-candidate information.
758 TemplateDeductionInfo &Info) {
760 Result.Result = static_cast<unsigned>(TDK);
761 Result.HasDiagnostic = false;
762 switch (TDK) {
769 Result.Data = nullptr;
770 break;
771
773 Result.Data = Info.Param.getOpaqueValue();
774 break;
776 Result.Data = Info.Param.getOpaqueValue();
777 if (Info.hasSFINAEDiagnostic()) {
781 Result.HasDiagnostic = true;
782 }
783 break;
784
787 // FIXME: Should allocate from normal heap so that we can free this later.
788 auto *Saved = new (Context) DFIDeducedMismatchArgs;
789 Saved->FirstArg = Info.FirstArg;
790 Saved->SecondArg = Info.SecondArg;
791 Saved->TemplateArgs = Info.takeSugared();
792 Saved->CallArgIndex = Info.CallArgIndex;
793 Result.Data = Saved;
794 break;
795 }
796
798 // FIXME: Should allocate from normal heap so that we can free this later.
799 DFIArguments *Saved = new (Context) DFIArguments;
800 Saved->FirstArg = Info.FirstArg;
801 Saved->SecondArg = Info.SecondArg;
802 Result.Data = Saved;
803 break;
804 }
805
807 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
810 // FIXME: Should allocate from normal heap so that we can free this later.
811 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
812 Saved->Param = Info.Param;
813 Saved->FirstArg = Info.FirstArg;
814 Saved->SecondArg = Info.SecondArg;
815 Result.Data = Saved;
816 break;
817 }
818
820 Result.Data = Info.takeSugared();
821 if (Info.hasSFINAEDiagnostic()) {
825 Result.HasDiagnostic = true;
826 }
827 break;
828
830 CNSInfo *Saved = new (Context) CNSInfo;
831 Saved->TemplateArgs = Info.takeSugared();
832 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
833 Result.Data = Saved;
834 break;
835 }
836
840 llvm_unreachable("not a deduction failure");
841 }
842
843 return Result;
844}
845
847 switch (static_cast<TemplateDeductionResult>(Result)) {
856 break;
857
864 // FIXME: Destroy the data?
865 Data = nullptr;
866 break;
867
870 // FIXME: Destroy the template argument list?
871 Data = nullptr;
873 Diag->~PartialDiagnosticAt();
874 HasDiagnostic = false;
875 }
876 break;
877
879 // FIXME: Destroy the template argument list?
880 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
881 Data = nullptr;
883 Diag->~PartialDiagnosticAt();
884 HasDiagnostic = false;
885 }
886 break;
887
888 // Unhandled
891 break;
892 }
893}
894
896 if (HasDiagnostic)
897 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
898 return nullptr;
899}
900
934
970
1002
1034
1036 switch (static_cast<TemplateDeductionResult>(Result)) {
1039 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1040
1041 default:
1042 return std::nullopt;
1043 }
1044}
1045
1047 const FunctionDecl *Y) {
1048 if (!X || !Y)
1049 return false;
1050 if (X->getNumParams() != Y->getNumParams())
1051 return false;
1052 // FIXME: when do rewritten comparison operators
1053 // with explicit object parameters correspond?
1054 // https://cplusplus.github.io/CWG/issues/2797.html
1055 for (unsigned I = 0; I < X->getNumParams(); ++I)
1056 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1057 Y->getParamDecl(I)->getType()))
1058 return false;
1059 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1060 auto *FTY = Y->getDescribedFunctionTemplate();
1061 if (!FTY)
1062 return false;
1063 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1064 FTY->getTemplateParameters()))
1065 return false;
1066 }
1067 return true;
1068}
1069
1071 Expr *FirstOperand, FunctionDecl *EqFD) {
1072 assert(EqFD->getOverloadedOperator() ==
1073 OverloadedOperatorKind::OO_EqualEqual);
1074 // C++2a [over.match.oper]p4:
1075 // A non-template function or function template F named operator== is a
1076 // rewrite target with first operand o unless a search for the name operator!=
1077 // in the scope S from the instantiation context of the operator expression
1078 // finds a function or function template that would correspond
1079 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1080 // scope of the class type of o if F is a class member, and the namespace
1081 // scope of which F is a member otherwise. A function template specialization
1082 // named operator== is a rewrite target if its function template is a rewrite
1083 // target.
1085 OverloadedOperatorKind::OO_ExclaimEqual);
1086 if (isa<CXXMethodDecl>(EqFD)) {
1087 // If F is a class member, search scope is class type of first operand.
1088 QualType RHS = FirstOperand->getType();
1089 auto *RHSRec = RHS->getAsCXXRecordDecl();
1090 if (!RHSRec)
1091 return true;
1092 LookupResult Members(S, NotEqOp, OpLoc,
1094 S.LookupQualifiedName(Members, RHSRec);
1095 Members.suppressAccessDiagnostics();
1096 for (NamedDecl *Op : Members)
1097 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1098 return false;
1099 return true;
1100 }
1101 // Otherwise the search scope is the namespace scope of which F is a member.
1102 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1103 auto *NotEqFD = Op->getAsFunction();
1104 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1105 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1106 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1108 cast<Decl>(Op->getLexicalDeclContext())))
1109 return false;
1110 }
1111 return true;
1112}
1113
1115 OverloadedOperatorKind Op) const {
1117 return false;
1118 return Op == OO_EqualEqual || Op == OO_Spaceship;
1119}
1120
1122 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1123 auto Op = FD->getOverloadedOperator();
1124 if (!allowsReversed(Op))
1125 return false;
1126 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1127 assert(OriginalArgs.size() == 2);
1129 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1130 return false;
1131 }
1132 // Don't bother adding a reversed candidate that can never be a better
1133 // match than the non-reversed version.
1134 return FD->getNumNonObjectParams() != 2 ||
1136 FD->getParamDecl(1)->getType()) ||
1137 FD->hasAttr<EnableIfAttr>();
1138}
1139
1140void OverloadCandidateSet::destroyCandidates() {
1141 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1142 for (auto &C : i->Conversions)
1143 C.~ImplicitConversionSequence();
1144 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1145 i->DeductionFailure.Destroy();
1146 }
1147}
1148
1150 destroyCandidates();
1151 SlabAllocator.Reset();
1152 NumInlineBytesUsed = 0;
1153 Candidates.clear();
1154 Functions.clear();
1155 Kind = CSK;
1156 FirstDeferredCandidate = nullptr;
1157 DeferredCandidatesCount = 0;
1158 HasDeferredTemplateConstructors = false;
1159 ResolutionByPerfectCandidateIsDisabled = false;
1160}
1161
1162namespace {
1163 class UnbridgedCastsSet {
1164 struct Entry {
1165 Expr **Addr;
1166 Expr *Saved;
1167 };
1168 SmallVector<Entry, 2> Entries;
1169
1170 public:
1171 void save(Sema &S, Expr *&E) {
1172 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1173 Entry entry = { &E, E };
1174 Entries.push_back(entry);
1175 E = S.ObjC().stripARCUnbridgedCast(E);
1176 }
1177
1178 void restore() {
1179 for (SmallVectorImpl<Entry>::iterator
1180 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1181 *i->Addr = i->Saved;
1182 }
1183 };
1184}
1185
1186/// checkPlaceholderForOverload - Do any interesting placeholder-like
1187/// preprocessing on the given expression.
1188///
1189/// \param unbridgedCasts a collection to which to add unbridged casts;
1190/// without this, they will be immediately diagnosed as errors
1191///
1192/// Return true on unrecoverable error.
1193static bool
1195 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1196 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1197 // We can't handle overloaded expressions here because overload
1198 // resolution might reasonably tweak them.
1199 if (placeholder->getKind() == BuiltinType::Overload) return false;
1200
1201 // If the context potentially accepts unbridged ARC casts, strip
1202 // the unbridged cast and add it to the collection for later restoration.
1203 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1204 unbridgedCasts) {
1205 unbridgedCasts->save(S, E);
1206 return false;
1207 }
1208
1209 // Go ahead and check everything else.
1210 ExprResult result = S.CheckPlaceholderExpr(E);
1211 if (result.isInvalid())
1212 return true;
1213
1214 E = result.get();
1215 return false;
1216 }
1217
1218 // Nothing to do.
1219 return false;
1220}
1221
1222/// checkArgPlaceholdersForOverload - Check a set of call operands for
1223/// placeholders.
1225 UnbridgedCastsSet &unbridged) {
1226 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1227 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1228 return true;
1229
1230 return false;
1231}
1232
1234 const LookupResult &Old, NamedDecl *&Match,
1235 bool NewIsUsingDecl) {
1236 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1237 I != E; ++I) {
1238 NamedDecl *OldD = *I;
1239
1240 bool OldIsUsingDecl = false;
1241 if (isa<UsingShadowDecl>(OldD)) {
1242 OldIsUsingDecl = true;
1243
1244 // We can always introduce two using declarations into the same
1245 // context, even if they have identical signatures.
1246 if (NewIsUsingDecl) continue;
1247
1248 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1249 }
1250
1251 // A using-declaration does not conflict with another declaration
1252 // if one of them is hidden.
1253 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1254 continue;
1255
1256 // If either declaration was introduced by a using declaration,
1257 // we'll need to use slightly different rules for matching.
1258 // Essentially, these rules are the normal rules, except that
1259 // function templates hide function templates with different
1260 // return types or template parameter lists.
1261 bool UseMemberUsingDeclRules =
1262 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1263 !New->getFriendObjectKind();
1264
1265 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1266 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1267 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1269 continue;
1270 }
1271
1272 if (!isa<FunctionTemplateDecl>(OldD) &&
1273 !shouldLinkPossiblyHiddenDecl(*I, New))
1274 continue;
1275
1276 Match = *I;
1277 return OverloadKind::Match;
1278 }
1279
1280 // Builtins that have custom typechecking or have a reference should
1281 // not be overloadable or redeclarable.
1282 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1283 Match = *I;
1285 }
1286 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1287 // We can overload with these, which can show up when doing
1288 // redeclaration checks for UsingDecls.
1289 assert(Old.getLookupKind() == LookupUsingDeclName);
1290 } else if (isa<TagDecl>(OldD)) {
1291 // We can always overload with tags by hiding them.
1292 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1293 // Optimistically assume that an unresolved using decl will
1294 // overload; if it doesn't, we'll have to diagnose during
1295 // template instantiation.
1296 //
1297 // Exception: if the scope is dependent and this is not a class
1298 // member, the using declaration can only introduce an enumerator.
1299 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1300 Match = *I;
1302 }
1303 } else {
1304 // (C++ 13p1):
1305 // Only function declarations can be overloaded; object and type
1306 // declarations cannot be overloaded.
1307 Match = *I;
1309 }
1310 }
1311
1312 // C++ [temp.friend]p1:
1313 // For a friend function declaration that is not a template declaration:
1314 // -- if the name of the friend is a qualified or unqualified template-id,
1315 // [...], otherwise
1316 // -- if the name of the friend is a qualified-id and a matching
1317 // non-template function is found in the specified class or namespace,
1318 // the friend declaration refers to that function, otherwise,
1319 // -- if the name of the friend is a qualified-id and a matching function
1320 // template is found in the specified class or namespace, the friend
1321 // declaration refers to the deduced specialization of that function
1322 // template, otherwise
1323 // -- the name shall be an unqualified-id [...]
1324 // If we get here for a qualified friend declaration, we've just reached the
1325 // third bullet. If the type of the friend is dependent, skip this lookup
1326 // until instantiation.
1327 if (New->getFriendObjectKind() && New->getQualifier() &&
1328 !New->getDescribedFunctionTemplate() &&
1329 !New->getDependentSpecializationInfo() &&
1330 !New->getType()->isDependentType()) {
1331 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1332 TemplateSpecResult.addAllDecls(Old);
1333 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1334 /*QualifiedFriend*/true)) {
1335 New->setInvalidDecl();
1337 }
1338
1339 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1340 return OverloadKind::Match;
1341 }
1342
1344}
1345
1346template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1347 assert(D && "function decl should not be null");
1348 if (auto *A = D->getAttr<AttrT>())
1349 return !A->isImplicit();
1350 return false;
1351}
1352
1354 FunctionDecl *Old,
1355 bool UseMemberUsingDeclRules,
1356 bool ConsiderCudaAttrs,
1357 bool UseOverrideRules = false) {
1358 // C++ [basic.start.main]p2: This function shall not be overloaded.
1359 if (New->isMain())
1360 return false;
1361
1362 // MSVCRT user defined entry points cannot be overloaded.
1363 if (New->isMSVCRTEntryPoint())
1364 return false;
1365
1366 NamedDecl *OldDecl = Old;
1367 NamedDecl *NewDecl = New;
1369 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1370
1371 // C++ [temp.fct]p2:
1372 // A function template can be overloaded with other function templates
1373 // and with normal (non-template) functions.
1374 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1375 return true;
1376
1377 // Is the function New an overload of the function Old?
1378 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1379 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1380
1381 // Compare the signatures (C++ 1.3.10) of the two functions to
1382 // determine whether they are overloads. If we find any mismatch
1383 // in the signature, they are overloads.
1384
1385 // If either of these functions is a K&R-style function (no
1386 // prototype), then we consider them to have matching signatures.
1387 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1389 return false;
1390
1391 const auto *OldType = cast<FunctionProtoType>(OldQType);
1392 const auto *NewType = cast<FunctionProtoType>(NewQType);
1393
1394 // The signature of a function includes the types of its
1395 // parameters (C++ 1.3.10), which includes the presence or absence
1396 // of the ellipsis; see C++ DR 357).
1397 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1398 return true;
1399
1400 // For member-like friends, the enclosing class is part of the signature.
1401 if ((New->isMemberLikeConstrainedFriend() ||
1403 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1404 return true;
1405
1406 // Compare the parameter lists.
1407 // This can only be done once we have establish that friend functions
1408 // inhabit the same context, otherwise we might tried to instantiate
1409 // references to non-instantiated entities during constraint substitution.
1410 // GH78101.
1411 if (NewTemplate) {
1412 OldDecl = OldTemplate;
1413 NewDecl = NewTemplate;
1414 // C++ [temp.over.link]p4:
1415 // The signature of a function template consists of its function
1416 // signature, its return type and its template parameter list. The names
1417 // of the template parameters are significant only for establishing the
1418 // relationship between the template parameters and the rest of the
1419 // signature.
1420 //
1421 // We check the return type and template parameter lists for function
1422 // templates first; the remaining checks follow.
1423 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1424 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1425 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1426 bool SameReturnType = SemaRef.Context.hasSameType(
1427 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1428 // FIXME(GH58571): Match template parameter list even for non-constrained
1429 // template heads. This currently ensures that the code prior to C++20 is
1430 // not newly broken.
1431 bool ConstraintsInTemplateHead =
1434 // C++ [namespace.udecl]p11:
1435 // The set of declarations named by a using-declarator that inhabits a
1436 // class C does not include member functions and member function
1437 // templates of a base class that "correspond" to (and thus would
1438 // conflict with) a declaration of a function or function template in
1439 // C.
1440 // Comparing return types is not required for the "correspond" check to
1441 // decide whether a member introduced by a shadow declaration is hidden.
1442 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1443 !SameTemplateParameterList)
1444 return true;
1445 if (!UseMemberUsingDeclRules &&
1446 (!SameTemplateParameterList || !SameReturnType))
1447 return true;
1448 }
1449
1450 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1451 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1452
1453 int OldParamsOffset = 0;
1454 int NewParamsOffset = 0;
1455
1456 // When determining if a method is an overload from a base class, act as if
1457 // the implicit object parameter are of the same type.
1458
1459 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1461 auto ThisType = M->getFunctionObjectParameterReferenceType();
1462 if (ThisType.isConstQualified())
1463 Q.removeConst();
1464 return Q;
1465 }
1466
1467 // We do not allow overloading based off of '__restrict'.
1468 Q.removeRestrict();
1469
1470 // We may not have applied the implicit const for a constexpr member
1471 // function yet (because we haven't yet resolved whether this is a static
1472 // or non-static member function). Add it now, on the assumption that this
1473 // is a redeclaration of OldMethod.
1474 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1475 (M->isConstexpr() || M->isConsteval()) &&
1476 !isa<CXXConstructorDecl>(NewMethod))
1477 Q.addConst();
1478 return Q;
1479 };
1480
1481 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1482 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1483 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1484
1485 if (OldMethod->isExplicitObjectMemberFunction()) {
1486 BS.Quals.removeVolatile();
1487 DS.Quals.removeVolatile();
1488 }
1489
1490 return BS.Quals == DS.Quals;
1491 };
1492
1493 auto CompareType = [&](QualType Base, QualType D) {
1494 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1495 auto DS = D.getNonReferenceType().getCanonicalType().split();
1496
1497 if (!AreQualifiersEqual(BS, DS))
1498 return false;
1499
1500 if (OldMethod->isImplicitObjectMemberFunction() &&
1501 OldMethod->getParent() != NewMethod->getParent()) {
1502 CanQualType ParentType =
1503 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1504 if (ParentType.getTypePtr() != BS.Ty)
1505 return false;
1506 BS.Ty = DS.Ty;
1507 }
1508
1509 // FIXME: should we ignore some type attributes here?
1510 if (BS.Ty != DS.Ty)
1511 return false;
1512
1513 if (Base->isLValueReferenceType())
1514 return D->isLValueReferenceType();
1515 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1516 };
1517
1518 // If the function is a class member, its signature includes the
1519 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1520 auto DiagnoseInconsistentRefQualifiers = [&]() {
1521 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1522 return false;
1523 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1524 return false;
1525 if (OldMethod->isExplicitObjectMemberFunction() ||
1526 NewMethod->isExplicitObjectMemberFunction())
1527 return false;
1528 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1529 NewMethod->getRefQualifier() == RQ_None)) {
1530 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1531 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1532 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1533 return true;
1534 }
1535 return false;
1536 };
1537
1538 // We look at the parameters first, as it is the common case.
1539 // However we should not emit diagnostic before checking
1540 // the overloads do not differ by constraints or other discriminant.
1541 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1542 bool HaveInconsistentQualifiers = false;
1543
1544 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1545 OldParamsOffset++;
1546 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1547 NewParamsOffset++;
1548
1549 if (OldType->getNumParams() - OldParamsOffset !=
1550 NewType->getNumParams() - NewParamsOffset ||
1552 {OldType->param_type_begin() + OldParamsOffset,
1553 OldType->param_type_end()},
1554 {NewType->param_type_begin() + NewParamsOffset,
1555 NewType->param_type_end()},
1556 nullptr)) {
1557 return true;
1558 }
1559
1560 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1561 !NewMethod->isStatic()) {
1562 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1563 const CXXMethodDecl *New) {
1564 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1565 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1566
1567 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1568 return F->getRefQualifier() == RQ_None &&
1569 !F->isExplicitObjectMemberFunction();
1570 };
1571
1572 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1573 CompareType(OldObjectType.getNonReferenceType(),
1574 NewObjectType.getNonReferenceType()))
1575 return true;
1576 return CompareType(OldObjectType, NewObjectType);
1577 }(OldMethod, NewMethod);
1578
1579 if (!HaveCorrespondingObjectParameters) {
1580 ShouldDiagnoseInconsistentRefQualifiers = true;
1581 // CWG2554
1582 // and, if at least one is an explicit object member function, ignoring
1583 // object parameters
1584 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1585 !OldMethod->isExplicitObjectMemberFunction()))
1586 HaveInconsistentQualifiers = true;
1587 }
1588 }
1589
1590 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1591 NewMethod->isImplicitObjectMemberFunction())
1592 ShouldDiagnoseInconsistentRefQualifiers = true;
1593
1594 if (!UseOverrideRules &&
1595 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1596 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1597 OldRC = Old->getTrailingRequiresClause();
1598 if (!NewRC != !OldRC)
1599 return true;
1600 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1601 return true;
1602 if (NewRC &&
1603 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1604 NewDecl, NewRC.ConstraintExpr))
1605 return true;
1606 }
1607
1608 // Though pass_object_size is placed on parameters and takes an argument, we
1609 // consider it to be a function-level modifier for the sake of function
1610 // identity. Either the function has one or more parameters with
1611 // pass_object_size or it doesn't.
1614 return true;
1615
1616 // enable_if attributes are an order-sensitive part of the signature.
1618 NewI = New->specific_attr_begin<EnableIfAttr>(),
1619 NewE = New->specific_attr_end<EnableIfAttr>(),
1620 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1621 OldE = Old->specific_attr_end<EnableIfAttr>();
1622 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1623 if (NewI == NewE || OldI == OldE)
1624 return true;
1625 llvm::FoldingSetNodeID NewID, OldID;
1626 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1627 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1628 if (NewID != OldID)
1629 return true;
1630 }
1631
1632 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1633 DiagnoseInconsistentRefQualifiers()) ||
1634 HaveInconsistentQualifiers)
1635 return true;
1636
1637 // At this point, it is known that the two functions have the same signature.
1638 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1639 // Don't allow overloading of destructors. (In theory we could, but it
1640 // would be a giant change to clang.)
1642 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1643 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1644 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1645 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1646 "Unexpected invalid target.");
1647
1648 // Allow overloading of functions with same signature and different CUDA
1649 // target attributes.
1650 if (NewTarget != OldTarget) {
1651 // Special case: non-constexpr function is allowed to override
1652 // constexpr virtual function
1653 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1654 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1659 return false;
1660 }
1661 return true;
1662 }
1663 }
1664 }
1665 }
1666
1667 // The signatures match; this is not an overload.
1668 return false;
1669}
1670
1672 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1673 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1674 ConsiderCudaAttrs);
1675}
1676
1678 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1679 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1680 /*UseMemberUsingDeclRules=*/false,
1681 /*ConsiderCudaAttrs=*/true,
1682 /*UseOverrideRules=*/true);
1683}
1684
1685/// Tries a user-defined conversion from From to ToType.
1686///
1687/// Produces an implicit conversion sequence for when a standard conversion
1688/// is not an option. See TryImplicitConversion for more information.
1691 bool SuppressUserConversions,
1692 AllowedExplicit AllowExplicit,
1693 bool InOverloadResolution,
1694 bool CStyle,
1695 bool AllowObjCWritebackConversion,
1696 bool AllowObjCConversionOnExplicit) {
1698
1699 if (SuppressUserConversions) {
1700 // We're not in the case above, so there is no conversion that
1701 // we can perform.
1703 return ICS;
1704 }
1705
1706 // Attempt user-defined conversion.
1707 OverloadCandidateSet Conversions(From->getExprLoc(),
1709 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1710 Conversions, AllowExplicit,
1711 AllowObjCConversionOnExplicit)) {
1712 case OR_Success:
1713 case OR_Deleted:
1714 ICS.setUserDefined();
1715 // C++ [over.ics.user]p4:
1716 // A conversion of an expression of class type to the same class
1717 // type is given Exact Match rank, and a conversion of an
1718 // expression of class type to a base class of that type is
1719 // given Conversion rank, in spite of the fact that a copy
1720 // constructor (i.e., a user-defined conversion function) is
1721 // called for those cases.
1723 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1724 QualType FromType;
1725 SourceLocation FromLoc;
1726 // C++11 [over.ics.list]p6, per DR2137:
1727 // C++17 [over.ics.list]p6:
1728 // If C is not an initializer-list constructor and the initializer list
1729 // has a single element of type cv U, where U is X or a class derived
1730 // from X, the implicit conversion sequence has Exact Match rank if U is
1731 // X, or Conversion rank if U is derived from X.
1732 bool FromListInit = false;
1733 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1734 InitList && InitList->getNumInits() == 1 &&
1736 const Expr *SingleInit = InitList->getInit(0);
1737 FromType = SingleInit->getType();
1738 FromLoc = SingleInit->getBeginLoc();
1739 FromListInit = true;
1740 } else {
1741 FromType = From->getType();
1742 FromLoc = From->getBeginLoc();
1743 }
1744 QualType FromCanon =
1746 QualType ToCanon
1748 if ((FromCanon == ToCanon ||
1749 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1750 // Turn this into a "standard" conversion sequence, so that it
1751 // gets ranked with standard conversion sequences.
1753 ICS.setStandard();
1755 ICS.Standard.setFromType(FromType);
1756 ICS.Standard.setAllToTypes(ToType);
1757 ICS.Standard.FromBracedInitList = FromListInit;
1760 if (ToCanon != FromCanon)
1762 }
1763 }
1764 break;
1765
1766 case OR_Ambiguous:
1767 ICS.setAmbiguous();
1768 ICS.Ambiguous.setFromType(From->getType());
1769 ICS.Ambiguous.setToType(ToType);
1770 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1771 Cand != Conversions.end(); ++Cand)
1772 if (Cand->Best)
1773 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1774 break;
1775
1776 // Fall through.
1779 break;
1780 }
1781
1782 return ICS;
1783}
1784
1785/// TryImplicitConversion - Attempt to perform an implicit conversion
1786/// from the given expression (Expr) to the given type (ToType). This
1787/// function returns an implicit conversion sequence that can be used
1788/// to perform the initialization. Given
1789///
1790/// void f(float f);
1791/// void g(int i) { f(i); }
1792///
1793/// this routine would produce an implicit conversion sequence to
1794/// describe the initialization of f from i, which will be a standard
1795/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1796/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1797//
1798/// Note that this routine only determines how the conversion can be
1799/// performed; it does not actually perform the conversion. As such,
1800/// it will not produce any diagnostics if no conversion is available,
1801/// but will instead return an implicit conversion sequence of kind
1802/// "BadConversion".
1803///
1804/// If @p SuppressUserConversions, then user-defined conversions are
1805/// not permitted.
1806/// If @p AllowExplicit, then explicit user-defined conversions are
1807/// permitted.
1808///
1809/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1810/// writeback conversion, which allows __autoreleasing id* parameters to
1811/// be initialized with __strong id* or __weak id* arguments.
1812static ImplicitConversionSequence
1814 bool SuppressUserConversions,
1815 AllowedExplicit AllowExplicit,
1816 bool InOverloadResolution,
1817 bool CStyle,
1818 bool AllowObjCWritebackConversion,
1819 bool AllowObjCConversionOnExplicit) {
1821 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1822 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1823 ICS.setStandard();
1824 return ICS;
1825 }
1826
1827 if (!S.getLangOpts().CPlusPlus) {
1829 return ICS;
1830 }
1831
1832 // C++ [over.ics.user]p4:
1833 // A conversion of an expression of class type to the same class
1834 // type is given Exact Match rank, and a conversion of an
1835 // expression of class type to a base class of that type is
1836 // given Conversion rank, in spite of the fact that a copy/move
1837 // constructor (i.e., a user-defined conversion function) is
1838 // called for those cases.
1839 QualType FromType = From->getType();
1840 if (ToType->isRecordType() &&
1841 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1842 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1843 ICS.setStandard();
1845 ICS.Standard.setFromType(FromType);
1846 ICS.Standard.setAllToTypes(ToType);
1847
1848 // We don't actually check at this point whether there is a valid
1849 // copy/move constructor, since overloading just assumes that it
1850 // exists. When we actually perform initialization, we'll find the
1851 // appropriate constructor to copy the returned object, if needed.
1852 ICS.Standard.CopyConstructor = nullptr;
1853
1854 // In HLSL, a conversion of an expression of class type to the same class
1855 // type needs implicit LvaluetoRvalue conversion.
1856 if (S.getLangOpts().HLSL)
1858
1859 // Determine whether this is considered a derived-to-base conversion.
1860 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1862
1863 return ICS;
1864 }
1865
1866 if (S.getLangOpts().HLSL) {
1867 // Handle conversion of the HLSL resource types.
1868 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1869 if (FromTy->isHLSLAttributedResourceType()) {
1870 // Attributed resource types can convert to other attributed
1871 // resource types with the same attributes and contained types,
1872 // or to __hlsl_resource_t without any attributes.
1873 bool CanConvert = false;
1874 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1875 if (ToTy->isHLSLAttributedResourceType()) {
1876 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1877 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1878 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1879 FromResType->getWrappedType()) &&
1880 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1881 FromResType->getContainedType()) &&
1882 ToResType->getAttrs() == FromResType->getAttrs())
1883 CanConvert = true;
1884 } else if (ToTy->isHLSLResourceType()) {
1885 CanConvert = true;
1886 }
1887 if (CanConvert) {
1888 ICS.setStandard();
1890 ICS.Standard.setFromType(FromType);
1891 ICS.Standard.setAllToTypes(ToType);
1892 return ICS;
1893 }
1894 }
1895 }
1896
1897 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1898 AllowExplicit, InOverloadResolution, CStyle,
1899 AllowObjCWritebackConversion,
1900 AllowObjCConversionOnExplicit);
1901}
1902
1903ImplicitConversionSequence
1905 bool SuppressUserConversions,
1906 AllowedExplicit AllowExplicit,
1907 bool InOverloadResolution,
1908 bool CStyle,
1909 bool AllowObjCWritebackConversion) {
1910 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1911 AllowExplicit, InOverloadResolution, CStyle,
1912 AllowObjCWritebackConversion,
1913 /*AllowObjCConversionOnExplicit=*/false);
1914}
1915
1917 AssignmentAction Action,
1918 bool AllowExplicit) {
1919 if (checkPlaceholderForOverload(*this, From))
1920 return ExprError();
1921
1922 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1923 bool AllowObjCWritebackConversion =
1924 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1925 Action == AssignmentAction::Sending);
1926 if (getLangOpts().ObjC)
1927 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1928 From->getType(), From);
1930 *this, From, ToType,
1931 /*SuppressUserConversions=*/false,
1932 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1933 /*InOverloadResolution=*/false,
1934 /*CStyle=*/false, AllowObjCWritebackConversion,
1935 /*AllowObjCConversionOnExplicit=*/false);
1936 return PerformImplicitConversion(From, ToType, ICS, Action);
1937}
1938
1940 QualType &ResultTy) const {
1941 bool Changed = IsFunctionConversion(FromType, ToType);
1942 if (Changed)
1943 ResultTy = ToType;
1944 return Changed;
1945}
1946
1947bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1948 if (Context.hasSameUnqualifiedType(FromType, ToType))
1949 return false;
1950
1951 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1952 // or F(t noexcept) -> F(t)
1953 // where F adds one of the following at most once:
1954 // - a pointer
1955 // - a member pointer
1956 // - a block pointer
1957 // Changes here need matching changes in FindCompositePointerType.
1958 CanQualType CanTo = Context.getCanonicalType(ToType);
1959 CanQualType CanFrom = Context.getCanonicalType(FromType);
1960 Type::TypeClass TyClass = CanTo->getTypeClass();
1961 if (TyClass != CanFrom->getTypeClass()) return false;
1962 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1963 if (TyClass == Type::Pointer) {
1964 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1965 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1966 } else if (TyClass == Type::BlockPointer) {
1967 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1968 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1969 } else if (TyClass == Type::MemberPointer) {
1970 auto ToMPT = CanTo.castAs<MemberPointerType>();
1971 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1972 // A function pointer conversion cannot change the class of the function.
1973 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1974 FromMPT->getMostRecentCXXRecordDecl()))
1975 return false;
1976 CanTo = ToMPT->getPointeeType();
1977 CanFrom = FromMPT->getPointeeType();
1978 } else {
1979 return false;
1980 }
1981
1982 TyClass = CanTo->getTypeClass();
1983 if (TyClass != CanFrom->getTypeClass()) return false;
1984 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1985 return false;
1986 }
1987
1988 const auto *FromFn = cast<FunctionType>(CanFrom);
1989 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1990
1991 const auto *ToFn = cast<FunctionType>(CanTo);
1992 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1993
1994 bool Changed = false;
1995
1996 // Drop 'noreturn' if not present in target type.
1997 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1998 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1999 Changed = true;
2000 }
2001
2002 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
2003 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
2004
2005 if (FromFPT && ToFPT) {
2006 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2007 QualType NewTy = Context.getFunctionType(
2008 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2009 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2010 ToFPT->hasCFIUncheckedCallee()));
2011 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2012 FromFn = FromFPT;
2013 Changed = true;
2014 }
2015 }
2016
2017 // Drop 'noexcept' if not present in target type.
2018 if (FromFPT && ToFPT) {
2019 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2020 FromFn = cast<FunctionType>(
2021 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2022 EST_None)
2023 .getTypePtr());
2024 Changed = true;
2025 }
2026
2027 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2028 // only if the ExtParameterInfo lists of the two function prototypes can be
2029 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2031 bool CanUseToFPT, CanUseFromFPT;
2032 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2033 CanUseFromFPT, NewParamInfos) &&
2034 CanUseToFPT && !CanUseFromFPT) {
2035 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2036 ExtInfo.ExtParameterInfos =
2037 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2038 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2039 FromFPT->getParamTypes(), ExtInfo);
2040 FromFn = QT->getAs<FunctionType>();
2041 Changed = true;
2042 }
2043
2044 if (Context.hasAnyFunctionEffects()) {
2045 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2046
2047 // Transparently add/drop effects; here we are concerned with
2048 // language rules/canonicalization. Adding/dropping effects is a warning.
2049 const auto FromFX = FromFPT->getFunctionEffects();
2050 const auto ToFX = ToFPT->getFunctionEffects();
2051 if (FromFX != ToFX) {
2052 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2053 ExtInfo.FunctionEffects = ToFX;
2054 QualType QT = Context.getFunctionType(
2055 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2056 FromFn = QT->getAs<FunctionType>();
2057 Changed = true;
2058 }
2059 }
2060 }
2061
2062 if (!Changed)
2063 return false;
2064
2065 assert(QualType(FromFn, 0).isCanonical());
2066 if (QualType(FromFn, 0) != CanTo) return false;
2067
2068 return true;
2069}
2070
2071/// Determine whether the conversion from FromType to ToType is a valid
2072/// floating point conversion.
2073///
2074static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2075 QualType ToType) {
2076 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2077 return false;
2078 // FIXME: disable conversions between long double, __ibm128 and __float128
2079 // if their representation is different until there is back end support
2080 // We of course allow this conversion if long double is really double.
2081
2082 // Conversions between bfloat16 and float16 are currently not supported.
2083 if ((FromType->isBFloat16Type() &&
2084 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2085 (ToType->isBFloat16Type() &&
2086 (FromType->isFloat16Type() || FromType->isHalfType())))
2087 return false;
2088
2089 // Conversions between IEEE-quad and IBM-extended semantics are not
2090 // permitted.
2091 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2092 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2093 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2094 &ToSem == &llvm::APFloat::IEEEquad()) ||
2095 (&FromSem == &llvm::APFloat::IEEEquad() &&
2096 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2097 return false;
2098 return true;
2099}
2100
2102 QualType ToType,
2104 Expr *From) {
2105 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2106 return true;
2107
2108 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2110 return true;
2111 }
2112
2113 if (IsFloatingPointConversion(S, FromType, ToType)) {
2115 return true;
2116 }
2117
2118 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2120 return true;
2121 }
2122
2123 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2125 ToType->isRealFloatingType())) {
2127 return true;
2128 }
2129
2130 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2132 return true;
2133 }
2134
2135 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2136 ToType->isIntegralType(S.Context)) {
2138 return true;
2139 }
2140
2141 return false;
2142}
2143
2144/// Determine whether the conversion from FromType to ToType is a valid
2145/// matrix conversion.
2146///
2147/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2148/// conversion.
2149static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2151 ImplicitConversionKind &ElConv, Expr *From,
2152 bool InOverloadResolution, bool CStyle) {
2153 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2154 if (!S.getLangOpts().HLSL)
2155 return false;
2156
2157 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2158 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2159
2160 // If both arguments are matrix, handle possible matrix truncation and
2161 // element conversion.
2162 if (ToMatrixType && FromMatrixType) {
2163 unsigned FromCols = FromMatrixType->getNumColumns();
2164 unsigned ToCols = ToMatrixType->getNumColumns();
2165 if (FromCols < ToCols)
2166 return false;
2167
2168 unsigned FromRows = FromMatrixType->getNumRows();
2169 unsigned ToRows = ToMatrixType->getNumRows();
2170 if (FromRows < ToRows)
2171 return false;
2172
2173 if (FromRows == ToRows && FromCols == ToCols)
2174 ElConv = ICK_Identity;
2175 else
2177
2178 QualType FromElTy = FromMatrixType->getElementType();
2179 QualType ToElTy = ToMatrixType->getElementType();
2180 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2181 return true;
2182 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2183 }
2184
2185 // Matrix splat from any arithmetic type to a matrix.
2186 if (ToMatrixType && FromType->isArithmeticType()) {
2187 ElConv = ICK_HLSL_Matrix_Splat;
2188 QualType ToElTy = ToMatrixType->getElementType();
2189 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2190 }
2191 if (FromMatrixType && !ToMatrixType) {
2193 QualType FromElTy = FromMatrixType->getElementType();
2194 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2195 return true;
2196 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2197 }
2198
2199 return false;
2200}
2201
2202/// Determine whether the conversion from FromType to ToType is a valid
2203/// vector conversion.
2204///
2205/// \param ICK Will be set to the vector conversion kind, if this is a vector
2206/// conversion.
2207static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2209 ImplicitConversionKind &ElConv, Expr *From,
2210 bool InOverloadResolution, bool CStyle) {
2211 // We need at least one of these types to be a vector type to have a vector
2212 // conversion.
2213 if (!ToType->isVectorType() && !FromType->isVectorType())
2214 return false;
2215
2216 // Identical types require no conversions.
2217 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2218 return false;
2219
2220 // HLSL allows implicit truncation of vector types.
2221 if (S.getLangOpts().HLSL) {
2222 auto *ToExtType = ToType->getAs<ExtVectorType>();
2223 auto *FromExtType = FromType->getAs<ExtVectorType>();
2224
2225 // If both arguments are vectors, handle possible vector truncation and
2226 // element conversion.
2227 if (ToExtType && FromExtType) {
2228 unsigned FromElts = FromExtType->getNumElements();
2229 unsigned ToElts = ToExtType->getNumElements();
2230 if (FromElts < ToElts)
2231 return false;
2232 if (FromElts == ToElts)
2233 ElConv = ICK_Identity;
2234 else
2236
2237 QualType FromElTy = FromExtType->getElementType();
2238 QualType ToElTy = ToExtType->getElementType();
2239 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2240 return true;
2241 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2242 }
2243 if (FromExtType && !ToExtType) {
2245 QualType FromElTy = FromExtType->getElementType();
2246 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2247 return true;
2248 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2249 }
2250 // Fallthrough for the case where ToType is a vector and FromType is not.
2251 }
2252
2253 // There are no conversions between extended vector types, only identity.
2254 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2255 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2256 // Implicit conversions require the same number of elements.
2257 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2258 return false;
2259
2260 // Permit implicit conversions from integral values to boolean vectors.
2261 if (ToType->isExtVectorBoolType() &&
2262 FromExtType->getElementType()->isIntegerType()) {
2264 return true;
2265 }
2266 // There are no other conversions between extended vector types.
2267 return false;
2268 }
2269
2270 // Vector splat from any arithmetic type to a vector.
2271 if (FromType->isArithmeticType()) {
2272 if (S.getLangOpts().HLSL) {
2273 ElConv = ICK_HLSL_Vector_Splat;
2274 QualType ToElTy = ToExtType->getElementType();
2275 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2276 From);
2277 }
2278 ICK = ICK_Vector_Splat;
2279 return true;
2280 }
2281 }
2282
2283 if (ToType->isSVESizelessBuiltinType() ||
2284 FromType->isSVESizelessBuiltinType())
2285 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2286 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2288 return true;
2289 }
2290
2291 if (ToType->isRVVSizelessBuiltinType() ||
2292 FromType->isRVVSizelessBuiltinType())
2293 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2294 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2296 return true;
2297 }
2298
2299 // We can perform the conversion between vector types in the following cases:
2300 // 1)vector types are equivalent AltiVec and GCC vector types
2301 // 2)lax vector conversions are permitted and the vector types are of the
2302 // same size
2303 // 3)the destination type does not have the ARM MVE strict-polymorphism
2304 // attribute, which inhibits lax vector conversion for overload resolution
2305 // only
2306 if (ToType->isVectorType() && FromType->isVectorType()) {
2307 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2308 (S.isLaxVectorConversion(FromType, ToType) &&
2309 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2310 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2311 S.isLaxVectorConversion(FromType, ToType) &&
2312 S.anyAltivecTypes(FromType, ToType) &&
2313 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2314 !InOverloadResolution && !CStyle) {
2315 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2316 << FromType << ToType;
2317 }
2319 return true;
2320 }
2321 }
2322
2323 return false;
2324}
2325
2326static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2327 bool InOverloadResolution,
2328 StandardConversionSequence &SCS,
2329 bool CStyle);
2330
2331static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2332 QualType ToType,
2333 bool InOverloadResolution,
2334 StandardConversionSequence &SCS,
2335 bool CStyle);
2336
2337/// IsStandardConversion - Determines whether there is a standard
2338/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2339/// expression From to the type ToType. Standard conversion sequences
2340/// only consider non-class types; for conversions that involve class
2341/// types, use TryImplicitConversion. If a conversion exists, SCS will
2342/// contain the standard conversion sequence required to perform this
2343/// conversion and this routine will return true. Otherwise, this
2344/// routine will return false and the value of SCS is unspecified.
2345static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2346 bool InOverloadResolution,
2348 bool CStyle,
2349 bool AllowObjCWritebackConversion) {
2350 QualType FromType = From->getType();
2351
2352 // Standard conversions (C++ [conv])
2354 SCS.IncompatibleObjC = false;
2355 SCS.setFromType(FromType);
2356 SCS.CopyConstructor = nullptr;
2357
2358 // There are no standard conversions for class types in C++, so
2359 // abort early. When overloading in C, however, we do permit them.
2360 if (S.getLangOpts().CPlusPlus &&
2361 (FromType->isRecordType() || ToType->isRecordType()))
2362 return false;
2363
2364 // The first conversion can be an lvalue-to-rvalue conversion,
2365 // array-to-pointer conversion, or function-to-pointer conversion
2366 // (C++ 4p1).
2367
2368 if (FromType == S.Context.OverloadTy) {
2369 DeclAccessPair AccessPair;
2370 if (FunctionDecl *Fn
2371 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2372 AccessPair)) {
2373 // We were able to resolve the address of the overloaded function,
2374 // so we can convert to the type of that function.
2375 FromType = Fn->getType();
2376 SCS.setFromType(FromType);
2377
2378 // we can sometimes resolve &foo<int> regardless of ToType, so check
2379 // if the type matches (identity) or we are converting to bool
2381 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2382 // if the function type matches except for [[noreturn]], it's ok
2383 if (!S.IsFunctionConversion(FromType,
2385 // otherwise, only a boolean conversion is standard
2386 if (!ToType->isBooleanType())
2387 return false;
2388 }
2389
2390 // Check if the "from" expression is taking the address of an overloaded
2391 // function and recompute the FromType accordingly. Take advantage of the
2392 // fact that non-static member functions *must* have such an address-of
2393 // expression.
2394 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2395 if (Method && !Method->isStatic() &&
2396 !Method->isExplicitObjectMemberFunction()) {
2397 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2398 "Non-unary operator on non-static member address");
2399 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2400 == UO_AddrOf &&
2401 "Non-address-of operator on non-static member address");
2402 FromType = S.Context.getMemberPointerType(
2403 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2404 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2405 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2406 UO_AddrOf &&
2407 "Non-address-of operator for overloaded function expression");
2408 FromType = S.Context.getPointerType(FromType);
2409 }
2410 } else {
2411 return false;
2412 }
2413 }
2414
2415 bool argIsLValue = From->isGLValue();
2416 // To handle conversion from ArrayParameterType to ConstantArrayType
2417 // this block must be above the one below because Array parameters
2418 // do not decay and when handling HLSLOutArgExprs and
2419 // the From expression is an LValue.
2420 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2421 ToType->isConstantArrayType()) {
2422 // HLSL constant array parameters do not decay, so if the argument is a
2423 // constant array and the parameter is an ArrayParameterType we have special
2424 // handling here.
2425 if (ToType->isArrayParameterType()) {
2426 FromType = S.Context.getArrayParameterType(FromType);
2427 } else if (FromType->isArrayParameterType()) {
2428 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2429 FromType = APT->getConstantArrayType(S.Context);
2430 }
2431
2433
2434 // Don't consider qualifiers, which include things like address spaces
2435 if (FromType.getCanonicalType().getUnqualifiedType() !=
2437 return false;
2438
2439 SCS.setAllToTypes(ToType);
2440 return true;
2441 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2442 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2443 // Lvalue-to-rvalue conversion (C++11 4.1):
2444 // A glvalue (3.10) of a non-function, non-array type T can
2445 // be converted to a prvalue.
2446
2448
2449 // C11 6.3.2.1p2:
2450 // ... if the lvalue has atomic type, the value has the non-atomic version
2451 // of the type of the lvalue ...
2452 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2453 FromType = Atomic->getValueType();
2454
2455 // If T is a non-class type, the type of the rvalue is the
2456 // cv-unqualified version of T. Otherwise, the type of the rvalue
2457 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2458 // just strip the qualifiers because they don't matter.
2459 FromType = FromType.getUnqualifiedType();
2460 } else if (FromType->isArrayType()) {
2461 // Array-to-pointer conversion (C++ 4.2)
2463
2464 // An lvalue or rvalue of type "array of N T" or "array of unknown
2465 // bound of T" can be converted to an rvalue of type "pointer to
2466 // T" (C++ 4.2p1).
2467 FromType = S.Context.getArrayDecayedType(FromType);
2468
2469 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2470 // This conversion is deprecated in C++03 (D.4)
2472
2473 // For the purpose of ranking in overload resolution
2474 // (13.3.3.1.1), this conversion is considered an
2475 // array-to-pointer conversion followed by a qualification
2476 // conversion (4.4). (C++ 4.2p2)
2477 SCS.Second = ICK_Identity;
2480 SCS.setAllToTypes(FromType);
2481 return true;
2482 }
2483 } else if (FromType->isFunctionType() && argIsLValue) {
2484 // Function-to-pointer conversion (C++ 4.3).
2486
2487 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2488 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2490 return false;
2491
2492 // An lvalue of function type T can be converted to an rvalue of
2493 // type "pointer to T." The result is a pointer to the
2494 // function. (C++ 4.3p1).
2495 FromType = S.Context.getPointerType(FromType);
2496 } else {
2497 // We don't require any conversions for the first step.
2498 SCS.First = ICK_Identity;
2499 }
2500 SCS.setToType(0, FromType);
2501
2502 // The second conversion can be an integral promotion, floating
2503 // point promotion, integral conversion, floating point conversion,
2504 // floating-integral conversion, pointer conversion,
2505 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2506 // For overloading in C, this can also be a "compatible-type"
2507 // conversion.
2508 bool IncompatibleObjC = false;
2510 ImplicitConversionKind DimensionICK = ICK_Identity;
2511 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2512 // The unqualified versions of the types are the same: there's no
2513 // conversion to do.
2514 SCS.Second = ICK_Identity;
2515 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2516 // Integral promotion (C++ 4.5).
2518 FromType = ToType.getUnqualifiedType();
2519 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2520 // Floating point promotion (C++ 4.6).
2522 FromType = ToType.getUnqualifiedType();
2523 } else if (S.IsComplexPromotion(FromType, ToType)) {
2524 // Complex promotion (Clang extension)
2526 FromType = ToType.getUnqualifiedType();
2527 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2528 // OverflowBehaviorType promotions
2530 FromType = ToType.getUnqualifiedType();
2531 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2532 // OverflowBehaviorType conversions
2534 FromType = ToType.getUnqualifiedType();
2535 } else if (ToType->isBooleanType() &&
2536 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2537 FromType->isBlockPointerType() ||
2538 FromType->isMemberPointerType())) {
2539 // Boolean conversions (C++ 4.12).
2541 FromType = S.Context.BoolTy;
2542 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2543 ToType->isIntegralType(S.Context)) {
2544 // Integral conversions (C++ 4.7).
2546 FromType = ToType.getUnqualifiedType();
2547 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2548 // Complex conversions (C99 6.3.1.6)
2550 FromType = ToType.getUnqualifiedType();
2551 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2552 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2553 // Complex-real conversions (C99 6.3.1.7)
2555 FromType = ToType.getUnqualifiedType();
2556 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2557 // Floating point conversions (C++ 4.8).
2559 FromType = ToType.getUnqualifiedType();
2560 } else if ((FromType->isRealFloatingType() &&
2561 ToType->isIntegralType(S.Context)) ||
2563 ToType->isRealFloatingType())) {
2564
2565 // Floating-integral conversions (C++ 4.9).
2567 FromType = ToType.getUnqualifiedType();
2568 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2570 } else if (AllowObjCWritebackConversion &&
2571 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2573 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2574 FromType, IncompatibleObjC)) {
2575 // Pointer conversions (C++ 4.10).
2577 SCS.IncompatibleObjC = IncompatibleObjC;
2578 FromType = FromType.getUnqualifiedType();
2579 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2580 InOverloadResolution, FromType)) {
2581 // Pointer to member conversions (4.11).
2583 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2584 From, InOverloadResolution, CStyle)) {
2585 SCS.Second = SecondICK;
2586 SCS.Dimension = DimensionICK;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2589 From, InOverloadResolution, CStyle)) {
2590 SCS.Second = SecondICK;
2591 SCS.Dimension = DimensionICK;
2592 FromType = ToType.getUnqualifiedType();
2593 } else if (!S.getLangOpts().CPlusPlus &&
2594 S.Context.typesAreCompatible(ToType, FromType)) {
2595 // Compatible conversions (Clang extension for C function overloading)
2597 FromType = ToType.getUnqualifiedType();
2599 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2601 FromType = ToType;
2602 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2603 CStyle)) {
2604 // tryAtomicConversion has updated the standard conversion sequence
2605 // appropriately.
2606 return true;
2608 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2609 return true;
2610 } else if (ToType->isEventT() &&
2612 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2614 FromType = ToType;
2615 } else if (ToType->isQueueT() &&
2617 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2619 FromType = ToType;
2620 } else if (ToType->isSamplerT() &&
2623 FromType = ToType;
2624 } else if ((ToType->isFixedPointType() &&
2625 FromType->isConvertibleToFixedPointType()) ||
2626 (FromType->isFixedPointType() &&
2627 ToType->isConvertibleToFixedPointType())) {
2629 FromType = ToType;
2630 } else {
2631 // No second conversion required.
2632 SCS.Second = ICK_Identity;
2633 }
2634 SCS.setToType(1, FromType);
2635
2636 // The third conversion can be a function pointer conversion or a
2637 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2638 bool ObjCLifetimeConversion;
2639 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2640 // Function pointer conversions (removing 'noexcept') including removal of
2641 // 'noreturn' (Clang extension).
2643 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2644 ObjCLifetimeConversion)) {
2646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2647 FromType = ToType;
2648 } else {
2649 // No conversion required
2650 SCS.Third = ICK_Identity;
2651 }
2652
2653 // C++ [over.best.ics]p6:
2654 // [...] Any difference in top-level cv-qualification is
2655 // subsumed by the initialization itself and does not constitute
2656 // a conversion. [...]
2657 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2658 QualType CanonTo = S.Context.getCanonicalType(ToType);
2659 if (CanonFrom.getLocalUnqualifiedType()
2660 == CanonTo.getLocalUnqualifiedType() &&
2661 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2662 FromType = ToType;
2663 CanonFrom = CanonTo;
2664 }
2665
2666 SCS.setToType(2, FromType);
2667
2668 if (CanonFrom == CanonTo)
2669 return true;
2670
2671 // If we have not converted the argument type to the parameter type,
2672 // this is a bad conversion sequence, unless we're resolving an overload in C.
2673 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2674 return false;
2675
2676 ExprResult ER = ExprResult{From};
2677 AssignConvertType Conv =
2679 /*Diagnose=*/false,
2680 /*DiagnoseCFAudited=*/false,
2681 /*ConvertRHS=*/false);
2682 ImplicitConversionKind SecondConv;
2683 switch (Conv) {
2685 case AssignConvertType::
2686 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2687 SecondConv = ICK_C_Only_Conversion;
2688 break;
2689 // For our purposes, discarding qualifiers is just as bad as using an
2690 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2691 // qualifiers, as well.
2696 break;
2697 default:
2698 return false;
2699 }
2700
2701 // First can only be an lvalue conversion, so we pretend that this was the
2702 // second conversion. First should already be valid from earlier in the
2703 // function.
2704 SCS.Second = SecondConv;
2705 SCS.setToType(1, ToType);
2706
2707 // Third is Identity, because Second should rank us worse than any other
2708 // conversion. This could also be ICK_Qualification, but it's simpler to just
2709 // lump everything in with the second conversion, and we don't gain anything
2710 // from making this ICK_Qualification.
2711 SCS.Third = ICK_Identity;
2712 SCS.setToType(2, ToType);
2713 return true;
2714}
2715
2716static bool
2718 QualType &ToType,
2719 bool InOverloadResolution,
2721 bool CStyle) {
2722
2723 const RecordType *UT = ToType->getAsUnionType();
2724 if (!UT)
2725 return false;
2726 // The field to initialize within the transparent union.
2727 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2728 if (!UD->hasAttr<TransparentUnionAttr>())
2729 return false;
2730 // It's compatible if the expression matches any of the fields.
2731 for (const auto *it : UD->fields()) {
2732 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2733 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2734 ToType = it->getType();
2735 return true;
2736 }
2737 }
2738 return false;
2739}
2740
2741bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2742 const BuiltinType *To = ToType->getAs<BuiltinType>();
2743 // All integers are built-in.
2744 if (!To) {
2745 return false;
2746 }
2747
2748 // An rvalue of type char, signed char, unsigned char, short int, or
2749 // unsigned short int can be converted to an rvalue of type int if
2750 // int can represent all the values of the source type; otherwise,
2751 // the source rvalue can be converted to an rvalue of type unsigned
2752 // int (C++ 4.5p1).
2753 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2754 !FromType->isEnumeralType()) {
2755 if ( // We can promote any signed, promotable integer type to an int
2756 (FromType->isSignedIntegerType() ||
2757 // We can promote any unsigned integer type whose size is
2758 // less than int to an int.
2759 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2760 return To->getKind() == BuiltinType::Int;
2761 }
2762
2763 return To->getKind() == BuiltinType::UInt;
2764 }
2765
2766 // C++11 [conv.prom]p3:
2767 // A prvalue of an unscoped enumeration type whose underlying type is not
2768 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2769 // following types that can represent all the values of the enumeration
2770 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2771 // unsigned int, long int, unsigned long int, long long int, or unsigned
2772 // long long int. If none of the types in that list can represent all the
2773 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2774 // type can be converted to an rvalue a prvalue of the extended integer type
2775 // with lowest integer conversion rank (4.13) greater than the rank of long
2776 // long in which all the values of the enumeration can be represented. If
2777 // there are two such extended types, the signed one is chosen.
2778 // C++11 [conv.prom]p4:
2779 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2780 // can be converted to a prvalue of its underlying type. Moreover, if
2781 // integral promotion can be applied to its underlying type, a prvalue of an
2782 // unscoped enumeration type whose underlying type is fixed can also be
2783 // converted to a prvalue of the promoted underlying type.
2784 if (const auto *FromED = FromType->getAsEnumDecl()) {
2785 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2786 // provided for a scoped enumeration.
2787 if (FromED->isScoped())
2788 return false;
2789
2790 // We can perform an integral promotion to the underlying type of the enum,
2791 // even if that's not the promoted type. Note that the check for promoting
2792 // the underlying type is based on the type alone, and does not consider
2793 // the bitfield-ness of the actual source expression.
2794 if (FromED->isFixed()) {
2795 QualType Underlying = FromED->getIntegerType();
2796 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2797 IsIntegralPromotion(nullptr, Underlying, ToType);
2798 }
2799
2800 // We have already pre-calculated the promotion type, so this is trivial.
2801 if (ToType->isIntegerType() &&
2802 isCompleteType(From->getBeginLoc(), FromType))
2803 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2804
2805 // C++ [conv.prom]p5:
2806 // If the bit-field has an enumerated type, it is treated as any other
2807 // value of that type for promotion purposes.
2808 //
2809 // ... so do not fall through into the bit-field checks below in C++.
2810 if (getLangOpts().CPlusPlus)
2811 return false;
2812 }
2813
2814 // C++0x [conv.prom]p2:
2815 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2816 // to an rvalue a prvalue of the first of the following types that can
2817 // represent all the values of its underlying type: int, unsigned int,
2818 // long int, unsigned long int, long long int, or unsigned long long int.
2819 // If none of the types in that list can represent all the values of its
2820 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2821 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2822 // type.
2823 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2824 ToType->isIntegerType()) {
2825 // Determine whether the type we're converting from is signed or
2826 // unsigned.
2827 bool FromIsSigned = FromType->isSignedIntegerType();
2828 uint64_t FromSize = Context.getTypeSize(FromType);
2829
2830 // The types we'll try to promote to, in the appropriate
2831 // order. Try each of these types.
2832 QualType PromoteTypes[6] = {
2833 Context.IntTy, Context.UnsignedIntTy,
2834 Context.LongTy, Context.UnsignedLongTy ,
2835 Context.LongLongTy, Context.UnsignedLongLongTy
2836 };
2837 for (int Idx = 0; Idx < 6; ++Idx) {
2838 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2839 if (FromSize < ToSize ||
2840 (FromSize == ToSize &&
2841 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2842 // We found the type that we can promote to. If this is the
2843 // type we wanted, we have a promotion. Otherwise, no
2844 // promotion.
2845 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2846 }
2847 }
2848 }
2849
2850 // An rvalue for an integral bit-field (9.6) can be converted to an
2851 // rvalue of type int if int can represent all the values of the
2852 // bit-field; otherwise, it can be converted to unsigned int if
2853 // unsigned int can represent all the values of the bit-field. If
2854 // the bit-field is larger yet, no integral promotion applies to
2855 // it. If the bit-field has an enumerated type, it is treated as any
2856 // other value of that type for promotion purposes (C++ 4.5p3).
2857 // FIXME: We should delay checking of bit-fields until we actually perform the
2858 // conversion.
2859 //
2860 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2861 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2862 // bit-fields and those whose underlying type is larger than int) for GCC
2863 // compatibility.
2864 if (From) {
2865 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2866 std::optional<llvm::APSInt> BitWidth;
2867 if (FromType->isIntegralType(Context) &&
2868 (BitWidth =
2869 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2870 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2871 ToSize = Context.getTypeSize(ToType);
2872
2873 // Are we promoting to an int from a bitfield that fits in an int?
2874 if (*BitWidth < ToSize ||
2875 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2876 return To->getKind() == BuiltinType::Int;
2877 }
2878
2879 // Are we promoting to an unsigned int from an unsigned bitfield
2880 // that fits into an unsigned int?
2881 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2882 return To->getKind() == BuiltinType::UInt;
2883 }
2884
2885 return false;
2886 }
2887 }
2888 }
2889
2890 // An rvalue of type bool can be converted to an rvalue of type int,
2891 // with false becoming zero and true becoming one (C++ 4.5p4).
2892 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2893 return true;
2894 }
2895
2896 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2897 // integral type.
2898 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2899 ToType->isIntegerType())
2900 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2901
2902 return false;
2903}
2904
2906 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2907 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2908 /// An rvalue of type float can be converted to an rvalue of type
2909 /// double. (C++ 4.6p1).
2910 if (FromBuiltin->getKind() == BuiltinType::Float &&
2911 ToBuiltin->getKind() == BuiltinType::Double)
2912 return true;
2913
2914 // C99 6.3.1.5p1:
2915 // When a float is promoted to double or long double, or a
2916 // double is promoted to long double [...].
2917 if (!getLangOpts().CPlusPlus &&
2918 (FromBuiltin->getKind() == BuiltinType::Float ||
2919 FromBuiltin->getKind() == BuiltinType::Double) &&
2920 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2921 ToBuiltin->getKind() == BuiltinType::Float128 ||
2922 ToBuiltin->getKind() == BuiltinType::Ibm128))
2923 return true;
2924
2925 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2926 // or not native half types are enabled.
2927 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2928 (ToBuiltin->getKind() == BuiltinType::Float ||
2929 ToBuiltin->getKind() == BuiltinType::Double))
2930 return true;
2931
2932 // Half can be promoted to float.
2933 if (!getLangOpts().NativeHalfType &&
2934 FromBuiltin->getKind() == BuiltinType::Half &&
2935 ToBuiltin->getKind() == BuiltinType::Float)
2936 return true;
2937 }
2938
2939 return false;
2940}
2941
2943 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2944 if (!FromComplex)
2945 return false;
2946
2947 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2948 if (!ToComplex)
2949 return false;
2950
2951 return IsFloatingPointPromotion(FromComplex->getElementType(),
2952 ToComplex->getElementType()) ||
2953 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2954 ToComplex->getElementType());
2955}
2956
2958 if (!getLangOpts().OverflowBehaviorTypes)
2959 return false;
2960
2961 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2962 return false;
2963
2964 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2965}
2966
2968 QualType ToType) {
2969 if (!getLangOpts().OverflowBehaviorTypes)
2970 return false;
2971
2972 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2973 if (ToType->isBooleanType())
2974 return false;
2975 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2976 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2977 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2978 if (ToED->isScoped())
2979 return false;
2980 }
2981 return true;
2982 }
2983
2984 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2985 return true;
2986
2987 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2988 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2989
2990 return false;
2991}
2992
2993/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2994/// the pointer type FromPtr to a pointer to type ToPointee, with the
2995/// same type qualifiers as FromPtr has on its pointee type. ToType,
2996/// if non-empty, will be a pointer to ToType that may or may not have
2997/// the right set of qualifiers on its pointee.
2998///
2999static QualType
3001 QualType ToPointee, QualType ToType,
3002 ASTContext &Context,
3003 bool StripObjCLifetime = false) {
3004 assert((FromPtr->getTypeClass() == Type::Pointer ||
3005 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3006 "Invalid similarly-qualified pointer type");
3007
3008 /// Conversions to 'id' subsume cv-qualifier conversions.
3009 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3010 return ToType.getUnqualifiedType();
3011
3012 QualType CanonFromPointee
3013 = Context.getCanonicalType(FromPtr->getPointeeType());
3014 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3015 Qualifiers Quals = CanonFromPointee.getQualifiers();
3016
3017 if (StripObjCLifetime)
3018 Quals.removeObjCLifetime();
3019
3020 // Exact qualifier match -> return the pointer type we're converting to.
3021 if (CanonToPointee.getLocalQualifiers() == Quals) {
3022 // ToType is exactly what we need. Return it.
3023 if (!ToType.isNull())
3024 return ToType.getUnqualifiedType();
3025
3026 // Build a pointer to ToPointee. It has the right qualifiers
3027 // already.
3028 if (isa<ObjCObjectPointerType>(ToType))
3029 return Context.getObjCObjectPointerType(ToPointee);
3030 return Context.getPointerType(ToPointee);
3031 }
3032
3033 // Just build a canonical type that has the right qualifiers.
3034 QualType QualifiedCanonToPointee
3035 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3036
3037 if (isa<ObjCObjectPointerType>(ToType))
3038 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3039 return Context.getPointerType(QualifiedCanonToPointee);
3040}
3041
3043 bool InOverloadResolution,
3044 ASTContext &Context) {
3045 // Handle value-dependent integral null pointer constants correctly.
3046 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3047 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3049 return !InOverloadResolution;
3050
3051 return Expr->isNullPointerConstant(Context,
3052 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3054}
3055
3057 bool InOverloadResolution,
3058 QualType& ConvertedType,
3059 bool &IncompatibleObjC) {
3060 IncompatibleObjC = false;
3061 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3062 IncompatibleObjC))
3063 return true;
3064
3065 // Conversion from a null pointer constant to any Objective-C pointer type.
3066 if (ToType->isObjCObjectPointerType() &&
3067 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3068 ConvertedType = ToType;
3069 return true;
3070 }
3071
3072 // Blocks: Block pointers can be converted to void*.
3073 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3074 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3075 ConvertedType = ToType;
3076 return true;
3077 }
3078 // Blocks: A null pointer constant can be converted to a block
3079 // pointer type.
3080 if (ToType->isBlockPointerType() &&
3081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3082 ConvertedType = ToType;
3083 return true;
3084 }
3085
3086 // If the left-hand-side is nullptr_t, the right side can be a null
3087 // pointer constant.
3088 if (ToType->isNullPtrType() &&
3089 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3090 ConvertedType = ToType;
3091 return true;
3092 }
3093
3094 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3095 if (!ToTypePtr)
3096 return false;
3097
3098 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3099 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3100 ConvertedType = ToType;
3101 return true;
3102 }
3103
3104 // Beyond this point, both types need to be pointers
3105 // , including objective-c pointers.
3106 QualType ToPointeeType = ToTypePtr->getPointeeType();
3107 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3108 !getLangOpts().ObjCAutoRefCount) {
3109 ConvertedType = BuildSimilarlyQualifiedPointerType(
3110 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3111 Context);
3112 return true;
3113 }
3114 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3115 if (!FromTypePtr)
3116 return false;
3117
3118 QualType FromPointeeType = FromTypePtr->getPointeeType();
3119
3120 // If the unqualified pointee types are the same, this can't be a
3121 // pointer conversion, so don't do all of the work below.
3122 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3123 return false;
3124
3125 // An rvalue of type "pointer to cv T," where T is an object type,
3126 // can be converted to an rvalue of type "pointer to cv void" (C++
3127 // 4.10p2).
3128 if (FromPointeeType->isIncompleteOrObjectType() &&
3129 ToPointeeType->isVoidType()) {
3130 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3131 ToPointeeType,
3132 ToType, Context,
3133 /*StripObjCLifetime=*/true);
3134 return true;
3135 }
3136
3137 // MSVC allows implicit function to void* type conversion.
3138 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3139 ToPointeeType->isVoidType()) {
3140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3141 ToPointeeType,
3142 ToType, Context);
3143 return true;
3144 }
3145
3146 // When we're overloading in C, we allow a special kind of pointer
3147 // conversion for compatible-but-not-identical pointee types.
3148 if (!getLangOpts().CPlusPlus &&
3149 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3150 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3151 ToPointeeType,
3152 ToType, Context);
3153 return true;
3154 }
3155
3156 // C++ [conv.ptr]p3:
3157 //
3158 // An rvalue of type "pointer to cv D," where D is a class type,
3159 // can be converted to an rvalue of type "pointer to cv B," where
3160 // B is a base class (clause 10) of D. If B is an inaccessible
3161 // (clause 11) or ambiguous (10.2) base class of D, a program that
3162 // necessitates this conversion is ill-formed. The result of the
3163 // conversion is a pointer to the base class sub-object of the
3164 // derived class object. The null pointer value is converted to
3165 // the null pointer value of the destination type.
3166 //
3167 // Note that we do not check for ambiguity or inaccessibility
3168 // here. That is handled by CheckPointerConversion.
3169 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3170 ToPointeeType->isRecordType() &&
3171 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3172 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3173 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3174 ToPointeeType,
3175 ToType, Context);
3176 return true;
3177 }
3178
3179 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3180 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3181 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3182 ToPointeeType,
3183 ToType, Context);
3184 return true;
3185 }
3186
3187 return false;
3188}
3189
3190/// Adopt the given qualifiers for the given type.
3192 Qualifiers TQs = T.getQualifiers();
3193
3194 // Check whether qualifiers already match.
3195 if (TQs == Qs)
3196 return T;
3197
3198 if (Qs.compatiblyIncludes(TQs, Context))
3199 return Context.getQualifiedType(T, Qs);
3200
3201 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3202}
3203
3205 QualType& ConvertedType,
3206 bool &IncompatibleObjC) {
3207 if (!getLangOpts().ObjC)
3208 return false;
3209
3210 // The set of qualifiers on the type we're converting from.
3211 Qualifiers FromQualifiers = FromType.getQualifiers();
3212
3213 // First, we handle all conversions on ObjC object pointer types.
3214 const ObjCObjectPointerType* ToObjCPtr =
3215 ToType->getAs<ObjCObjectPointerType>();
3216 const ObjCObjectPointerType *FromObjCPtr =
3217 FromType->getAs<ObjCObjectPointerType>();
3218
3219 if (ToObjCPtr && FromObjCPtr) {
3220 // If the pointee types are the same (ignoring qualifications),
3221 // then this is not a pointer conversion.
3222 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3223 FromObjCPtr->getPointeeType()))
3224 return false;
3225
3226 // Conversion between Objective-C pointers.
3227 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3228 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3229 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3230 if (getLangOpts().CPlusPlus && LHS && RHS &&
3232 FromObjCPtr->getPointeeType(), getASTContext()))
3233 return false;
3234 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3235 ToObjCPtr->getPointeeType(),
3236 ToType, Context);
3237 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3238 return true;
3239 }
3240
3241 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3242 // Okay: this is some kind of implicit downcast of Objective-C
3243 // interfaces, which is permitted. However, we're going to
3244 // complain about it.
3245 IncompatibleObjC = true;
3246 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3247 ToObjCPtr->getPointeeType(),
3248 ToType, Context);
3249 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3250 return true;
3251 }
3252 }
3253 // Beyond this point, both types need to be C pointers or block pointers.
3254 QualType ToPointeeType;
3255 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3256 ToPointeeType = ToCPtr->getPointeeType();
3257 else if (const BlockPointerType *ToBlockPtr =
3258 ToType->getAs<BlockPointerType>()) {
3259 // Objective C++: We're able to convert from a pointer to any object
3260 // to a block pointer type.
3261 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3262 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3263 return true;
3264 }
3265 ToPointeeType = ToBlockPtr->getPointeeType();
3266 }
3267 else if (FromType->getAs<BlockPointerType>() &&
3268 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3269 // Objective C++: We're able to convert from a block pointer type to a
3270 // pointer to any object.
3271 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3272 return true;
3273 }
3274 else
3275 return false;
3276
3277 QualType FromPointeeType;
3278 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3279 FromPointeeType = FromCPtr->getPointeeType();
3280 else if (const BlockPointerType *FromBlockPtr =
3281 FromType->getAs<BlockPointerType>())
3282 FromPointeeType = FromBlockPtr->getPointeeType();
3283 else
3284 return false;
3285
3286 // If we have pointers to pointers, recursively check whether this
3287 // is an Objective-C conversion.
3288 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3289 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3290 IncompatibleObjC)) {
3291 // We always complain about this conversion.
3292 IncompatibleObjC = true;
3293 ConvertedType = Context.getPointerType(ConvertedType);
3294 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3295 return true;
3296 }
3297 // Allow conversion of pointee being objective-c pointer to another one;
3298 // as in I* to id.
3299 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3300 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3301 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3302 IncompatibleObjC)) {
3303
3304 ConvertedType = Context.getPointerType(ConvertedType);
3305 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3306 return true;
3307 }
3308
3309 // If we have pointers to functions or blocks, check whether the only
3310 // differences in the argument and result types are in Objective-C
3311 // pointer conversions. If so, we permit the conversion (but
3312 // complain about it).
3313 const FunctionProtoType *FromFunctionType
3314 = FromPointeeType->getAs<FunctionProtoType>();
3315 const FunctionProtoType *ToFunctionType
3316 = ToPointeeType->getAs<FunctionProtoType>();
3317 if (FromFunctionType && ToFunctionType) {
3318 // If the function types are exactly the same, this isn't an
3319 // Objective-C pointer conversion.
3320 if (Context.getCanonicalType(FromPointeeType)
3321 == Context.getCanonicalType(ToPointeeType))
3322 return false;
3323
3324 // Perform the quick checks that will tell us whether these
3325 // function types are obviously different.
3326 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3327 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3328 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3329 return false;
3330
3331 bool HasObjCConversion = false;
3332 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3333 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3334 // Okay, the types match exactly. Nothing to do.
3335 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3336 ToFunctionType->getReturnType(),
3337 ConvertedType, IncompatibleObjC)) {
3338 // Okay, we have an Objective-C pointer conversion.
3339 HasObjCConversion = true;
3340 } else {
3341 // Function types are too different. Abort.
3342 return false;
3343 }
3344
3345 // Check argument types.
3346 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3347 ArgIdx != NumArgs; ++ArgIdx) {
3348 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3349 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3350 if (Context.getCanonicalType(FromArgType)
3351 == Context.getCanonicalType(ToArgType)) {
3352 // Okay, the types match exactly. Nothing to do.
3353 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3354 ConvertedType, IncompatibleObjC)) {
3355 // Okay, we have an Objective-C pointer conversion.
3356 HasObjCConversion = true;
3357 } else {
3358 // Argument types are too different. Abort.
3359 return false;
3360 }
3361 }
3362
3363 if (HasObjCConversion) {
3364 // We had an Objective-C conversion. Allow this pointer
3365 // conversion, but complain about it.
3366 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3367 IncompatibleObjC = true;
3368 return true;
3369 }
3370 }
3371
3372 return false;
3373}
3374
3376 QualType& ConvertedType) {
3377 QualType ToPointeeType;
3378 if (const BlockPointerType *ToBlockPtr =
3379 ToType->getAs<BlockPointerType>())
3380 ToPointeeType = ToBlockPtr->getPointeeType();
3381 else
3382 return false;
3383
3384 QualType FromPointeeType;
3385 if (const BlockPointerType *FromBlockPtr =
3386 FromType->getAs<BlockPointerType>())
3387 FromPointeeType = FromBlockPtr->getPointeeType();
3388 else
3389 return false;
3390 // We have pointer to blocks, check whether the only
3391 // differences in the argument and result types are in Objective-C
3392 // pointer conversions. If so, we permit the conversion.
3393
3394 const FunctionProtoType *FromFunctionType
3395 = FromPointeeType->getAs<FunctionProtoType>();
3396 const FunctionProtoType *ToFunctionType
3397 = ToPointeeType->getAs<FunctionProtoType>();
3398
3399 if (!FromFunctionType || !ToFunctionType)
3400 return false;
3401
3402 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3403 return true;
3404
3405 // Perform the quick checks that will tell us whether these
3406 // function types are obviously different.
3407 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3408 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3409 return false;
3410
3411 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3412 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3413 if (FromEInfo != ToEInfo)
3414 return false;
3415
3416 bool IncompatibleObjC = false;
3417 if (Context.hasSameType(FromFunctionType->getReturnType(),
3418 ToFunctionType->getReturnType())) {
3419 // Okay, the types match exactly. Nothing to do.
3420 } else {
3421 QualType RHS = FromFunctionType->getReturnType();
3422 QualType LHS = ToFunctionType->getReturnType();
3423 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3424 !RHS.hasQualifiers() && LHS.hasQualifiers())
3425 LHS = LHS.getUnqualifiedType();
3426
3427 if (Context.hasSameType(RHS,LHS)) {
3428 // OK exact match.
3429 } else if (isObjCPointerConversion(RHS, LHS,
3430 ConvertedType, IncompatibleObjC)) {
3431 if (IncompatibleObjC)
3432 return false;
3433 // Okay, we have an Objective-C pointer conversion.
3434 }
3435 else
3436 return false;
3437 }
3438
3439 // Check argument types.
3440 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3441 ArgIdx != NumArgs; ++ArgIdx) {
3442 IncompatibleObjC = false;
3443 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3444 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3445 if (Context.hasSameType(FromArgType, ToArgType)) {
3446 // Okay, the types match exactly. Nothing to do.
3447 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3448 ConvertedType, IncompatibleObjC)) {
3449 if (IncompatibleObjC)
3450 return false;
3451 // Okay, we have an Objective-C pointer conversion.
3452 } else
3453 // Argument types are too different. Abort.
3454 return false;
3455 }
3456
3458 bool CanUseToFPT, CanUseFromFPT;
3459 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3460 CanUseToFPT, CanUseFromFPT,
3461 NewParamInfos))
3462 return false;
3463
3464 ConvertedType = ToType;
3465 return true;
3466}
3467
3468enum {
3476};
3477
3478/// Attempts to get the FunctionProtoType from a Type. Handles
3479/// MemberFunctionPointers properly.
3481 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3482 return FPT;
3483
3484 if (auto *MPT = FromType->getAs<MemberPointerType>())
3485 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3486
3487 return nullptr;
3488}
3489
3491 QualType FromType, QualType ToType) {
3492 // If either type is not valid, include no extra info.
3493 if (FromType.isNull() || ToType.isNull()) {
3494 PDiag << ft_default;
3495 return;
3496 }
3497
3498 // Get the function type from the pointers.
3499 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3500 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3501 *ToMember = ToType->castAs<MemberPointerType>();
3502 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3503 ToMember->getMostRecentCXXRecordDecl())) {
3505 if (ToMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 ToMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << ToMember->getQualifier();
3510 if (FromMember->isSugared())
3511 PDiag << Context.getCanonicalTagType(
3512 FromMember->getMostRecentCXXRecordDecl());
3513 else
3514 PDiag << FromMember->getQualifier();
3515 return;
3516 }
3517 FromType = FromMember->getPointeeType();
3518 ToType = ToMember->getPointeeType();
3519 }
3520
3521 if (FromType->isPointerType())
3522 FromType = FromType->getPointeeType();
3523 if (ToType->isPointerType())
3524 ToType = ToType->getPointeeType();
3525
3526 // Remove references.
3527 FromType = FromType.getNonReferenceType();
3528 ToType = ToType.getNonReferenceType();
3529
3530 // Don't print extra info for non-specialized template functions.
3531 if (FromType->isInstantiationDependentType() &&
3532 !FromType->getAs<TemplateSpecializationType>()) {
3533 PDiag << ft_default;
3534 return;
3535 }
3536
3537 // No extra info for same types.
3538 if (Context.hasSameType(FromType, ToType)) {
3539 PDiag << ft_default;
3540 return;
3541 }
3542
3543 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3544 *ToFunction = tryGetFunctionProtoType(ToType);
3545
3546 // Both types need to be function types.
3547 if (!FromFunction || !ToFunction) {
3548 PDiag << ft_default;
3549 return;
3550 }
3551
3552 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3553 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3554 << FromFunction->getNumParams();
3555 return;
3556 }
3557
3558 // Handle different parameter types.
3559 unsigned ArgPos;
3560 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3561 PDiag << ft_parameter_mismatch << ArgPos + 1
3562 << ToFunction->getParamType(ArgPos)
3563 << FromFunction->getParamType(ArgPos);
3564 return;
3565 }
3566
3567 // Handle different return type.
3568 if (!Context.hasSameType(FromFunction->getReturnType(),
3569 ToFunction->getReturnType())) {
3570 PDiag << ft_return_type << ToFunction->getReturnType()
3571 << FromFunction->getReturnType();
3572 return;
3573 }
3574
3575 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3576 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3577 << FromFunction->getMethodQuals();
3578 return;
3579 }
3580
3581 // Handle exception specification differences on canonical type (in C++17
3582 // onwards).
3584 ->isNothrow() !=
3585 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3586 ->isNothrow()) {
3587 PDiag << ft_noexcept;
3588 return;
3589 }
3590
3591 // Unable to find a difference, so add no extra info.
3592 PDiag << ft_default;
3593}
3594
3596 ArrayRef<QualType> New, unsigned *ArgPos,
3597 bool Reversed) {
3598 assert(llvm::size(Old) == llvm::size(New) &&
3599 "Can't compare parameters of functions with different number of "
3600 "parameters!");
3601
3602 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3603 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3604 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3605
3606 // Ignore address spaces in pointee type. This is to disallow overloading
3607 // on __ptr32/__ptr64 address spaces.
3608 QualType OldType =
3609 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3610 QualType NewType =
3611 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3612
3613 if (!Context.hasSameType(OldType, NewType)) {
3614 if (ArgPos)
3615 *ArgPos = Idx;
3616 return false;
3617 }
3618 }
3619 return true;
3620}
3621
3623 const FunctionProtoType *NewType,
3624 unsigned *ArgPos, bool Reversed) {
3625 return FunctionParamTypesAreEqual(OldType->param_types(),
3626 NewType->param_types(), ArgPos, Reversed);
3627}
3628
3630 const FunctionDecl *NewFunction,
3631 unsigned *ArgPos,
3632 bool Reversed) {
3633
3634 if (OldFunction->getNumNonObjectParams() !=
3635 NewFunction->getNumNonObjectParams())
3636 return false;
3637
3638 unsigned OldIgnore =
3640 unsigned NewIgnore =
3642
3643 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3644 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3645
3646 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3647 NewPT->param_types().slice(NewIgnore),
3648 ArgPos, Reversed);
3649}
3650
3652 CastKind &Kind,
3653 CXXCastPath& BasePath,
3654 bool IgnoreBaseAccess,
3655 bool Diagnose) {
3656 QualType FromType = From->getType();
3657 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3658
3659 Kind = CK_BitCast;
3660
3661 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3664 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3665 DiagRuntimeBehavior(From->getExprLoc(), From,
3666 PDiag(diag::warn_impcast_bool_to_null_pointer)
3667 << ToType << From->getSourceRange());
3668 else if (!isUnevaluatedContext())
3669 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3670 << ToType << From->getSourceRange();
3671 }
3672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3673 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3674 QualType FromPointeeType = FromPtrType->getPointeeType(),
3675 ToPointeeType = ToPtrType->getPointeeType();
3676
3677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3678 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3679 // We must have a derived-to-base conversion. Check an
3680 // ambiguous or inaccessible conversion.
3681 unsigned InaccessibleID = 0;
3682 unsigned AmbiguousID = 0;
3683 if (Diagnose) {
3684 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3685 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3686 }
3688 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3689 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3690 &BasePath, IgnoreBaseAccess))
3691 return true;
3692
3693 // The conversion was successful.
3694 Kind = CK_DerivedToBase;
3695 }
3696
3697 if (Diagnose && !IsCStyleOrFunctionalCast &&
3698 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3699 assert(getLangOpts().MSVCCompat &&
3700 "this should only be possible with MSVCCompat!");
3701 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3702 << From->getSourceRange();
3703 }
3704 }
3705 } else if (const ObjCObjectPointerType *ToPtrType =
3706 ToType->getAs<ObjCObjectPointerType>()) {
3707 if (const ObjCObjectPointerType *FromPtrType =
3708 FromType->getAs<ObjCObjectPointerType>()) {
3709 // Objective-C++ conversions are always okay.
3710 // FIXME: We should have a different class of conversions for the
3711 // Objective-C++ implicit conversions.
3712 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3713 return false;
3714 } else if (FromType->isBlockPointerType()) {
3715 Kind = CK_BlockPointerToObjCPointerCast;
3716 } else {
3717 Kind = CK_CPointerToObjCPointerCast;
3718 }
3719 } else if (ToType->isBlockPointerType()) {
3720 if (!FromType->isBlockPointerType())
3721 Kind = CK_AnyPointerToBlockPointerCast;
3722 }
3723
3724 // We shouldn't fall into this case unless it's valid for other
3725 // reasons.
3727 Kind = CK_NullToPointer;
3728
3729 return false;
3730}
3731
3733 QualType ToType,
3734 bool InOverloadResolution,
3735 QualType &ConvertedType) {
3736 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3737 if (!ToTypePtr)
3738 return false;
3739
3740 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3742 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3744 ConvertedType = ToType;
3745 return true;
3746 }
3747
3748 // Otherwise, both types have to be member pointers.
3749 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3750 if (!FromTypePtr)
3751 return false;
3752
3753 // A pointer to member of B can be converted to a pointer to member of D,
3754 // where D is derived from B (C++ 4.11p2).
3755 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3756 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3757
3758 if (!declaresSameEntity(FromClass, ToClass) &&
3759 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3760 ConvertedType = Context.getMemberPointerType(
3761 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3762 return true;
3763 }
3764
3765 return false;
3766}
3767
3769 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3770 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3771 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3772 // Lock down the inheritance model right now in MS ABI, whether or not the
3773 // pointee types are the same.
3774 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3775 (void)isCompleteType(CheckLoc, FromType);
3776 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3777 }
3778
3779 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3780 if (!FromPtrType) {
3781 // This must be a null pointer to member pointer conversion
3782 Kind = CK_NullToMemberPointer;
3784 }
3785
3786 // T == T, modulo cv
3788 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3789 ToPtrType->getPointeeType()))
3791
3792 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3793 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3794
3795 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3796 const CXXRecordDecl *Cls) {
3797 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3798 PD << Qual;
3799 else
3800 PD << Context.getCanonicalTagType(Cls);
3801 };
3802 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3803 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3804 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3805 return PD;
3806 };
3807
3808 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3810 std::swap(Base, Derived);
3811
3812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3813 /*DetectVirtual=*/true);
3814 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3816
3817 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3818 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3819 PD << int(Direction);
3820 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3821 Diag(CheckLoc, PD);
3823 }
3824
3825 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3826 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3827 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3828 Diag(CheckLoc, PD);
3830 }
3831
3832 // Must be a base to derived member conversion.
3833 BuildBasePathArray(Paths, BasePath);
3835 ? CK_DerivedToBaseMemberPointer
3836 : CK_BaseToDerivedMemberPointer;
3837
3838 if (!IgnoreBaseAccess)
3839 switch (CheckBaseClassAccess(
3840 CheckLoc, Base, Derived, Paths.front(),
3842 ? diag::err_upcast_to_inaccessible_base
3843 : diag::err_downcast_from_inaccessible_base,
3844 [&](PartialDiagnostic &PD) {
3845 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3846 DerivedQual = ToPtrType->getQualifier();
3847 if (Direction == MemberPointerConversionDirection::Upcast)
3848 std::swap(BaseQual, DerivedQual);
3849 DiagCls(PD, DerivedQual, Derived);
3850 DiagCls(PD, BaseQual, Base);
3851 })) {
3853 case Sema::AR_delayed:
3854 case Sema::AR_dependent:
3855 // Optimistically assume that the delayed and dependent cases
3856 // will work out.
3857 break;
3858
3861 }
3862
3864}
3865
3866/// Determine whether the lifetime conversion between the two given
3867/// qualifiers sets is nontrivial.
3869 Qualifiers ToQuals) {
3870 // Converting anything to const __unsafe_unretained is trivial.
3871 if (ToQuals.hasConst() &&
3873 return false;
3874
3875 return true;
3876}
3877
3878/// Perform a single iteration of the loop for checking if a qualification
3879/// conversion is valid.
3880///
3881/// Specifically, check whether any change between the qualifiers of \p
3882/// FromType and \p ToType is permissible, given knowledge about whether every
3883/// outer layer is const-qualified.
3885 bool CStyle, bool IsTopLevel,
3886 bool &PreviousToQualsIncludeConst,
3887 bool &ObjCLifetimeConversion,
3888 const ASTContext &Ctx) {
3889 Qualifiers FromQuals = FromType.getQualifiers();
3890 Qualifiers ToQuals = ToType.getQualifiers();
3891
3892 // Ignore __unaligned qualifier.
3893 FromQuals.removeUnaligned();
3894
3895 // Objective-C ARC:
3896 // Check Objective-C lifetime conversions.
3897 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3898 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3899 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3900 ObjCLifetimeConversion = true;
3901 FromQuals.removeObjCLifetime();
3902 ToQuals.removeObjCLifetime();
3903 } else {
3904 // Qualification conversions cannot cast between different
3905 // Objective-C lifetime qualifiers.
3906 return false;
3907 }
3908 }
3909
3910 // Allow addition/removal of GC attributes but not changing GC attributes.
3911 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3912 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3913 FromQuals.removeObjCGCAttr();
3914 ToQuals.removeObjCGCAttr();
3915 }
3916
3917 // __ptrauth qualifiers must match exactly.
3918 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3919 return false;
3920
3921 // -- for every j > 0, if const is in cv 1,j then const is in cv
3922 // 2,j, and similarly for volatile.
3923 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3924 return false;
3925
3926 // If address spaces mismatch:
3927 // - in top level it is only valid to convert to addr space that is a
3928 // superset in all cases apart from C-style casts where we allow
3929 // conversions between overlapping address spaces.
3930 // - in non-top levels it is not a valid conversion.
3931 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3932 (!IsTopLevel ||
3933 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3934 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3935 return false;
3936
3937 // -- if the cv 1,j and cv 2,j are different, then const is in
3938 // every cv for 0 < k < j.
3939 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3940 !PreviousToQualsIncludeConst)
3941 return false;
3942
3943 // The following wording is from C++20, where the result of the conversion
3944 // is T3, not T2.
3945 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3946 // "array of unknown bound of"
3947 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3948 return false;
3949
3950 // -- if the resulting P3,i is different from P1,i [...], then const is
3951 // added to every cv 3_k for 0 < k < i.
3952 if (!CStyle && FromType->isConstantArrayType() &&
3953 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3954 return false;
3955
3956 // Keep track of whether all prior cv-qualifiers in the "to" type
3957 // include const.
3958 PreviousToQualsIncludeConst =
3959 PreviousToQualsIncludeConst && ToQuals.hasConst();
3960 return true;
3961}
3962
3963bool
3965 bool CStyle, bool &ObjCLifetimeConversion) {
3966 FromType = Context.getCanonicalType(FromType);
3967 ToType = Context.getCanonicalType(ToType);
3968 ObjCLifetimeConversion = false;
3969
3970 // If FromType and ToType are the same type, this is not a
3971 // qualification conversion.
3972 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3973 return false;
3974
3975 // (C++ 4.4p4):
3976 // A conversion can add cv-qualifiers at levels other than the first
3977 // in multi-level pointers, subject to the following rules: [...]
3978 bool PreviousToQualsIncludeConst = true;
3979 bool UnwrappedAnyPointer = false;
3980 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3981 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3982 !UnwrappedAnyPointer,
3983 PreviousToQualsIncludeConst,
3984 ObjCLifetimeConversion, getASTContext()))
3985 return false;
3986 UnwrappedAnyPointer = true;
3987 }
3988
3989 // We are left with FromType and ToType being the pointee types
3990 // after unwrapping the original FromType and ToType the same number
3991 // of times. If we unwrapped any pointers, and if FromType and
3992 // ToType have the same unqualified type (since we checked
3993 // qualifiers above), then this is a qualification conversion.
3994 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3995}
3996
3997/// - Determine whether this is a conversion from a scalar type to an
3998/// atomic type.
3999///
4000/// If successful, updates \c SCS's second and third steps in the conversion
4001/// sequence to finish the conversion.
4002static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4003 bool InOverloadResolution,
4005 bool CStyle) {
4006 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4007 if (!ToAtomic)
4008 return false;
4009
4011 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4012 InOverloadResolution, InnerSCS,
4013 CStyle, /*AllowObjCWritebackConversion=*/false))
4014 return false;
4015
4016 SCS.Second = InnerSCS.Second;
4017 SCS.setToType(1, InnerSCS.getToType(1));
4018 SCS.Third = InnerSCS.Third;
4021 SCS.setToType(2, InnerSCS.getToType(2));
4022 return true;
4023}
4024
4026 QualType ToType,
4027 bool InOverloadResolution,
4029 bool CStyle) {
4030 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4031 if (!ToOBT)
4032 return false;
4033
4034 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4035 QualType FromType = From->getType();
4036 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4037 return false;
4038
4040 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4041 InOverloadResolution, InnerSCS, CStyle,
4042 /*AllowObjCWritebackConversion=*/false))
4043 return false;
4044
4045 SCS.Second = InnerSCS.Second;
4046 SCS.setToType(1, InnerSCS.getToType(1));
4047 SCS.Third = InnerSCS.Third;
4050 SCS.setToType(2, InnerSCS.getToType(2));
4051 return true;
4052}
4053
4056 QualType Type) {
4057 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4058 if (CtorType->getNumParams() > 0) {
4059 QualType FirstArg = CtorType->getParamType(0);
4060 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4061 return true;
4062 }
4063 return false;
4064}
4065
4066static OverloadingResult
4068 CXXRecordDecl *To,
4070 OverloadCandidateSet &CandidateSet,
4071 bool AllowExplicit) {
4073 for (auto *D : S.LookupConstructors(To)) {
4074 auto Info = getConstructorInfo(D);
4075 if (!Info)
4076 continue;
4077
4078 bool Usable = !Info.Constructor->isInvalidDecl() &&
4079 S.isInitListConstructor(Info.Constructor);
4080 if (Usable) {
4081 bool SuppressUserConversions = false;
4082 if (Info.ConstructorTmpl)
4083 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4084 /*ExplicitArgs*/ nullptr, From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false,
4087 AllowExplicit);
4088 else
4089 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4090 CandidateSet, SuppressUserConversions,
4091 /*PartialOverloading*/ false, AllowExplicit);
4092 }
4093 }
4094
4095 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4096
4098 switch (auto Result =
4099 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4100 case OR_Deleted:
4101 case OR_Success: {
4102 // Record the standard conversion we used and the conversion function.
4104 QualType ThisType = Constructor->getFunctionObjectParameterType();
4105 // Initializer lists don't have conversions as such.
4107 User.HadMultipleCandidates = HadMultipleCandidates;
4109 User.FoundConversionFunction = Best->FoundDecl;
4111 User.After.setFromType(ThisType);
4112 User.After.setAllToTypes(ToType);
4113 return Result;
4114 }
4115
4117 return OR_No_Viable_Function;
4118 case OR_Ambiguous:
4119 return OR_Ambiguous;
4120 }
4121
4122 llvm_unreachable("Invalid OverloadResult!");
4123}
4124
4125/// Determines whether there is a user-defined conversion sequence
4126/// (C++ [over.ics.user]) that converts expression From to the type
4127/// ToType. If such a conversion exists, User will contain the
4128/// user-defined conversion sequence that performs such a conversion
4129/// and this routine will return true. Otherwise, this routine returns
4130/// false and User is unspecified.
4131///
4132/// \param AllowExplicit true if the conversion should consider C++0x
4133/// "explicit" conversion functions as well as non-explicit conversion
4134/// functions (C++0x [class.conv.fct]p2).
4135///
4136/// \param AllowObjCConversionOnExplicit true if the conversion should
4137/// allow an extra Objective-C pointer conversion on uses of explicit
4138/// constructors. Requires \c AllowExplicit to also be set.
4139static OverloadingResult
4142 OverloadCandidateSet &CandidateSet,
4143 AllowedExplicit AllowExplicit,
4144 bool AllowObjCConversionOnExplicit) {
4145 assert(AllowExplicit != AllowedExplicit::None ||
4146 !AllowObjCConversionOnExplicit);
4148
4149 // Whether we will only visit constructors.
4150 bool ConstructorsOnly = false;
4151
4152 // If the type we are conversion to is a class type, enumerate its
4153 // constructors.
4154 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4155 // C++ [over.match.ctor]p1:
4156 // When objects of class type are direct-initialized (8.5), or
4157 // copy-initialized from an expression of the same or a
4158 // derived class type (8.5), overload resolution selects the
4159 // constructor. [...] For copy-initialization, the candidate
4160 // functions are all the converting constructors (12.3.1) of
4161 // that class. The argument list is the expression-list within
4162 // the parentheses of the initializer.
4163 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4164 (From->getType()->isRecordType() &&
4165 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4166 ConstructorsOnly = true;
4167
4168 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4169 // We're not going to find any constructors.
4170 } else if (auto *ToRecordDecl =
4171 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4172 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4173
4174 Expr **Args = &From;
4175 unsigned NumArgs = 1;
4176 bool ListInitializing = false;
4177 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4178 // But first, see if there is an init-list-constructor that will work.
4180 S, From, ToType, ToRecordDecl, User, CandidateSet,
4181 AllowExplicit == AllowedExplicit::All);
4183 return Result;
4184 // Never mind.
4185 CandidateSet.clear(
4187
4188 // If we're list-initializing, we pass the individual elements as
4189 // arguments, not the entire list.
4190 Args = InitList->getInits();
4191 NumArgs = InitList->getNumInits();
4192 ListInitializing = true;
4193 }
4194
4195 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4196 auto Info = getConstructorInfo(D);
4197 if (!Info)
4198 continue;
4199
4200 bool Usable = !Info.Constructor->isInvalidDecl();
4201 if (!ListInitializing)
4202 Usable = Usable && Info.Constructor->isConvertingConstructor(
4203 /*AllowExplicit*/ true);
4204 if (Usable) {
4205 bool SuppressUserConversions = !ConstructorsOnly;
4206 // C++20 [over.best.ics.general]/4.5:
4207 // if the target is the first parameter of a constructor [of class
4208 // X] and the constructor [...] is a candidate by [...] the second
4209 // phase of [over.match.list] when the initializer list has exactly
4210 // one element that is itself an initializer list, [...] and the
4211 // conversion is to X or reference to cv X, user-defined conversion
4212 // sequences are not considered.
4213 if (SuppressUserConversions && ListInitializing) {
4214 SuppressUserConversions =
4215 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4216 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4217 ToType);
4218 }
4219 if (Info.ConstructorTmpl)
4221 Info.ConstructorTmpl, Info.FoundDecl,
4222 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4223 CandidateSet, SuppressUserConversions,
4224 /*PartialOverloading*/ false,
4225 AllowExplicit == AllowedExplicit::All);
4226 else
4227 // Allow one user-defined conversion when user specifies a
4228 // From->ToType conversion via an static cast (c-style, etc).
4229 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4230 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4231 SuppressUserConversions,
4232 /*PartialOverloading*/ false,
4233 AllowExplicit == AllowedExplicit::All);
4234 }
4235 }
4236 }
4237 }
4238
4239 // Enumerate conversion functions, if we're allowed to.
4240 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4241 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4242 // No conversion functions from incomplete types.
4243 } else if (const RecordType *FromRecordType =
4244 From->getType()->getAsCanonical<RecordType>()) {
4245 if (auto *FromRecordDecl =
4246 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4247 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4248 // Add all of the conversion functions as candidates.
4249 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4250 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4251 DeclAccessPair FoundDecl = I.getPair();
4252 NamedDecl *D = FoundDecl.getDecl();
4253 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4254 if (isa<UsingShadowDecl>(D))
4255 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4256
4257 CXXConversionDecl *Conv;
4258 FunctionTemplateDecl *ConvTemplate;
4259 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4260 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4261 else
4262 Conv = cast<CXXConversionDecl>(D);
4263
4264 if (ConvTemplate)
4266 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4267 CandidateSet, AllowObjCConversionOnExplicit,
4268 AllowExplicit != AllowedExplicit::None);
4269 else
4270 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4271 CandidateSet, AllowObjCConversionOnExplicit,
4272 AllowExplicit != AllowedExplicit::None);
4273 }
4274 }
4275 }
4276
4277 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4278
4280 switch (auto Result =
4281 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4282 case OR_Success:
4283 case OR_Deleted:
4284 // Record the standard conversion we used and the conversion function.
4286 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4287 // C++ [over.ics.user]p1:
4288 // If the user-defined conversion is specified by a
4289 // constructor (12.3.1), the initial standard conversion
4290 // sequence converts the source type to the type required by
4291 // the argument of the constructor.
4292 //
4293 if (isa<InitListExpr>(From)) {
4294 // Initializer lists don't have conversions as such.
4296 User.Before.FromBracedInitList = true;
4297 } else {
4298 if (Best->Conversions[0].isEllipsis())
4299 User.EllipsisConversion = true;
4300 else {
4301 User.Before = Best->Conversions[0].Standard;
4302 User.EllipsisConversion = false;
4303 }
4304 }
4305 User.HadMultipleCandidates = HadMultipleCandidates;
4307 User.FoundConversionFunction = Best->FoundDecl;
4309 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4310 User.After.setAllToTypes(ToType);
4311 return Result;
4312 }
4313 if (CXXConversionDecl *Conversion
4314 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4315
4316 assert(Best->HasFinalConversion);
4317
4318 // C++ [over.ics.user]p1:
4319 //
4320 // [...] If the user-defined conversion is specified by a
4321 // conversion function (12.3.2), the initial standard
4322 // conversion sequence converts the source type to the
4323 // implicit object parameter of the conversion function.
4324 User.Before = Best->Conversions[0].Standard;
4325 User.HadMultipleCandidates = HadMultipleCandidates;
4326 User.ConversionFunction = Conversion;
4327 User.FoundConversionFunction = Best->FoundDecl;
4328 User.EllipsisConversion = false;
4329
4330 // C++ [over.ics.user]p2:
4331 // The second standard conversion sequence converts the
4332 // result of the user-defined conversion to the target type
4333 // for the sequence. Since an implicit conversion sequence
4334 // is an initialization, the special rules for
4335 // initialization by user-defined conversion apply when
4336 // selecting the best user-defined conversion for a
4337 // user-defined conversion sequence (see 13.3.3 and
4338 // 13.3.3.1).
4339 User.After = Best->FinalConversion;
4340 return Result;
4341 }
4342 llvm_unreachable("Not a constructor or conversion function?");
4343
4345 return OR_No_Viable_Function;
4346
4347 case OR_Ambiguous:
4348 return OR_Ambiguous;
4349 }
4350
4351 llvm_unreachable("Invalid OverloadResult!");
4352}
4353
4354bool
4357 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4359 OverloadingResult OvResult =
4360 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4361 CandidateSet, AllowedExplicit::None, false);
4362
4363 if (!(OvResult == OR_Ambiguous ||
4364 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4365 return false;
4366
4367 auto Cands = CandidateSet.CompleteCandidates(
4368 *this,
4370 From);
4371 if (OvResult == OR_Ambiguous)
4372 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4373 << From->getType() << ToType << From->getSourceRange();
4374 else { // OR_No_Viable_Function && !CandidateSet.empty()
4375 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4376 diag::err_typecheck_nonviable_condition_incomplete,
4377 From->getType(), From->getSourceRange()))
4378 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4379 << false << From->getType() << From->getSourceRange() << ToType;
4380 }
4381
4382 CandidateSet.NoteCandidates(
4383 *this, From, Cands);
4384 return true;
4385}
4386
4387// Helper for compareConversionFunctions that gets the FunctionType that the
4388// conversion-operator return value 'points' to, or nullptr.
4389static const FunctionType *
4391 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4392 const PointerType *RetPtrTy =
4393 ConvFuncTy->getReturnType()->getAs<PointerType>();
4394
4395 if (!RetPtrTy)
4396 return nullptr;
4397
4398 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4399}
4400
4401/// Compare the user-defined conversion functions or constructors
4402/// of two user-defined conversion sequences to determine whether any ordering
4403/// is possible.
4406 FunctionDecl *Function2) {
4407 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4408 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4409 if (!Conv1 || !Conv2)
4411
4412 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4414
4415 // Objective-C++:
4416 // If both conversion functions are implicitly-declared conversions from
4417 // a lambda closure type to a function pointer and a block pointer,
4418 // respectively, always prefer the conversion to a function pointer,
4419 // because the function pointer is more lightweight and is more likely
4420 // to keep code working.
4421 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4422 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4423 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4424 if (Block1 != Block2)
4425 return Block1 ? ImplicitConversionSequence::Worse
4427 }
4428
4429 // In order to support multiple calling conventions for the lambda conversion
4430 // operator (such as when the free and member function calling convention is
4431 // different), prefer the 'free' mechanism, followed by the calling-convention
4432 // of operator(). The latter is in place to support the MSVC-like solution of
4433 // defining ALL of the possible conversions in regards to calling-convention.
4434 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4435 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4436
4437 if (Conv1FuncRet && Conv2FuncRet &&
4438 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4439 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4440 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4441
4442 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4443 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4444
4445 CallingConv CallOpCC =
4446 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4448 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4450 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4451
4452 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4453 for (CallingConv CC : PrefOrder) {
4454 if (Conv1CC == CC)
4456 if (Conv2CC == CC)
4458 }
4459 }
4460
4462}
4463
4470
4471/// CompareImplicitConversionSequences - Compare two implicit
4472/// conversion sequences to determine whether one is better than the
4473/// other or if they are indistinguishable (C++ 13.3.3.2).
4476 const ImplicitConversionSequence& ICS1,
4477 const ImplicitConversionSequence& ICS2)
4478{
4479 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4480 // conversion sequences (as defined in 13.3.3.1)
4481 // -- a standard conversion sequence (13.3.3.1.1) is a better
4482 // conversion sequence than a user-defined conversion sequence or
4483 // an ellipsis conversion sequence, and
4484 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4485 // conversion sequence than an ellipsis conversion sequence
4486 // (13.3.3.1.3).
4487 //
4488 // C++0x [over.best.ics]p10:
4489 // For the purpose of ranking implicit conversion sequences as
4490 // described in 13.3.3.2, the ambiguous conversion sequence is
4491 // treated as a user-defined sequence that is indistinguishable
4492 // from any other user-defined conversion sequence.
4493
4494 // String literal to 'char *' conversion has been deprecated in C++03. It has
4495 // been removed from C++11. We still accept this conversion, if it happens at
4496 // the best viable function. Otherwise, this conversion is considered worse
4497 // than ellipsis conversion. Consider this as an extension; this is not in the
4498 // standard. For example:
4499 //
4500 // int &f(...); // #1
4501 // void f(char*); // #2
4502 // void g() { int &r = f("foo"); }
4503 //
4504 // In C++03, we pick #2 as the best viable function.
4505 // In C++11, we pick #1 as the best viable function, because ellipsis
4506 // conversion is better than string-literal to char* conversion (since there
4507 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4508 // convert arguments, #2 would be the best viable function in C++11.
4509 // If the best viable function has this conversion, a warning will be issued
4510 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4511
4512 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4515 // Ill-formedness must not differ
4516 ICS1.isBad() == ICS2.isBad())
4520
4521 if (ICS1.getKindRank() < ICS2.getKindRank())
4523 if (ICS2.getKindRank() < ICS1.getKindRank())
4525
4526 // The following checks require both conversion sequences to be of
4527 // the same kind.
4528 if (ICS1.getKind() != ICS2.getKind())
4530
4533
4534 // Two implicit conversion sequences of the same form are
4535 // indistinguishable conversion sequences unless one of the
4536 // following rules apply: (C++ 13.3.3.2p3):
4537
4538 // List-initialization sequence L1 is a better conversion sequence than
4539 // list-initialization sequence L2 if:
4540 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4541 // if not that,
4542 // — L1 and L2 convert to arrays of the same element type, and either the
4543 // number of elements n_1 initialized by L1 is less than the number of
4544 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4545 // an array of unknown bound and L1 does not,
4546 // even if one of the other rules in this paragraph would otherwise apply.
4547 if (!ICS1.isBad()) {
4548 bool StdInit1 = false, StdInit2 = false;
4551 nullptr);
4554 nullptr);
4555 if (StdInit1 != StdInit2)
4556 return StdInit1 ? ImplicitConversionSequence::Better
4558
4561 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4563 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4565 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4566 CAT2->getElementType())) {
4567 // Both to arrays of the same element type
4568 if (CAT1->getSize() != CAT2->getSize())
4569 // Different sized, the smaller wins
4570 return CAT1->getSize().ult(CAT2->getSize())
4575 // One is incomplete, it loses
4579 }
4580 }
4581 }
4582
4583 if (ICS1.isStandard())
4584 // Standard conversion sequence S1 is a better conversion sequence than
4585 // standard conversion sequence S2 if [...]
4587 ICS1.Standard, ICS2.Standard);
4588 else if (ICS1.isUserDefined()) {
4589 // With lazy template loading, it is possible to find non-canonical
4590 // FunctionDecls, depending on when redecl chains are completed. Make sure
4591 // to compare the canonical decls of conversion functions. This avoids
4592 // ambiguity problems for templated conversion operators.
4593 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4594 if (ConvFunc1)
4595 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4596 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4597 if (ConvFunc2)
4598 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4599 // User-defined conversion sequence U1 is a better conversion
4600 // sequence than another user-defined conversion sequence U2 if
4601 // they contain the same user-defined conversion function or
4602 // constructor and if the second standard conversion sequence of
4603 // U1 is better than the second standard conversion sequence of
4604 // U2 (C++ 13.3.3.2p3).
4605 if (ConvFunc1 == ConvFunc2)
4607 ICS1.UserDefined.After,
4608 ICS2.UserDefined.After);
4609 else
4613 }
4614
4615 return Result;
4616}
4617
4618// Per 13.3.3.2p3, compare the given standard conversion sequences to
4619// determine if one is a proper subset of the other.
4622 const StandardConversionSequence& SCS1,
4623 const StandardConversionSequence& SCS2) {
4626
4627 // the identity conversion sequence is considered to be a subsequence of
4628 // any non-identity conversion sequence
4629 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4631 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4633
4634 if (SCS1.Second != SCS2.Second) {
4635 if (SCS1.Second == ICK_Identity)
4637 else if (SCS2.Second == ICK_Identity)
4639 else
4641 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4643
4644 if (SCS1.Third == SCS2.Third) {
4645 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4647 }
4648
4649 if (SCS1.Third == ICK_Identity)
4653
4654 if (SCS2.Third == ICK_Identity)
4658
4660}
4661
4662/// Determine whether one of the given reference bindings is better
4663/// than the other based on what kind of bindings they are.
4664static bool
4666 const StandardConversionSequence &SCS2) {
4667 // C++0x [over.ics.rank]p3b4:
4668 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4669 // implicit object parameter of a non-static member function declared
4670 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4671 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4672 // lvalue reference to a function lvalue and S2 binds an rvalue
4673 // reference*.
4674 //
4675 // FIXME: Rvalue references. We're going rogue with the above edits,
4676 // because the semantics in the current C++0x working paper (N3225 at the
4677 // time of this writing) break the standard definition of std::forward
4678 // and std::reference_wrapper when dealing with references to functions.
4679 // Proposed wording changes submitted to CWG for consideration.
4682 return false;
4683
4684 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4685 SCS2.IsLvalueReference) ||
4688}
4689
4695
4696/// Returns kind of fixed enum promotion the \a SCS uses.
4697static FixedEnumPromotion
4699
4700 if (SCS.Second != ICK_Integral_Promotion)
4702
4703 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4704 if (!Enum)
4706
4707 if (!Enum->isFixed())
4709
4710 QualType UnderlyingType = Enum->getIntegerType();
4711 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4713
4715}
4716
4717/// CompareStandardConversionSequences - Compare two standard
4718/// conversion sequences to determine whether one is better than the
4719/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4722 const StandardConversionSequence& SCS1,
4723 const StandardConversionSequence& SCS2)
4724{
4725 // Standard conversion sequence S1 is a better conversion sequence
4726 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4727
4728 // -- S1 is a proper subsequence of S2 (comparing the conversion
4729 // sequences in the canonical form defined by 13.3.3.1.1,
4730 // excluding any Lvalue Transformation; the identity conversion
4731 // sequence is considered to be a subsequence of any
4732 // non-identity conversion sequence) or, if not that,
4735 return CK;
4736
4737 // -- the rank of S1 is better than the rank of S2 (by the rules
4738 // defined below), or, if not that,
4739 ImplicitConversionRank Rank1 = SCS1.getRank();
4740 ImplicitConversionRank Rank2 = SCS2.getRank();
4741 if (Rank1 < Rank2)
4743 else if (Rank2 < Rank1)
4745
4746 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4747 // are indistinguishable unless one of the following rules
4748 // applies:
4749
4750 // A conversion that is not a conversion of a pointer, or
4751 // pointer to member, to bool is better than another conversion
4752 // that is such a conversion.
4754 return SCS2.isPointerConversionToBool()
4757
4758 // C++14 [over.ics.rank]p4b2:
4759 // This is retroactively applied to C++11 by CWG 1601.
4760 //
4761 // A conversion that promotes an enumeration whose underlying type is fixed
4762 // to its underlying type is better than one that promotes to the promoted
4763 // underlying type, if the two are different.
4766 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4767 FEP1 != FEP2)
4771
4772 // C++ [over.ics.rank]p4b2:
4773 //
4774 // If class B is derived directly or indirectly from class A,
4775 // conversion of B* to A* is better than conversion of B* to
4776 // void*, and conversion of A* to void* is better than conversion
4777 // of B* to void*.
4778 bool SCS1ConvertsToVoid
4780 bool SCS2ConvertsToVoid
4782 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4783 // Exactly one of the conversion sequences is a conversion to
4784 // a void pointer; it's the worse conversion.
4785 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4787 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4788 // Neither conversion sequence converts to a void pointer; compare
4789 // their derived-to-base conversions.
4791 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4792 return DerivedCK;
4793 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4794 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4795 // Both conversion sequences are conversions to void
4796 // pointers. Compare the source types to determine if there's an
4797 // inheritance relationship in their sources.
4798 QualType FromType1 = SCS1.getFromType();
4799 QualType FromType2 = SCS2.getFromType();
4800
4801 // Adjust the types we're converting from via the array-to-pointer
4802 // conversion, if we need to.
4803 if (SCS1.First == ICK_Array_To_Pointer)
4804 FromType1 = S.Context.getArrayDecayedType(FromType1);
4805 if (SCS2.First == ICK_Array_To_Pointer)
4806 FromType2 = S.Context.getArrayDecayedType(FromType2);
4807
4808 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4809 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4810
4811 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4813 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4815
4816 // Objective-C++: If one interface is more specific than the
4817 // other, it is the better one.
4818 const ObjCObjectPointerType* FromObjCPtr1
4819 = FromType1->getAs<ObjCObjectPointerType>();
4820 const ObjCObjectPointerType* FromObjCPtr2
4821 = FromType2->getAs<ObjCObjectPointerType>();
4822 if (FromObjCPtr1 && FromObjCPtr2) {
4823 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4824 FromObjCPtr2);
4825 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4826 FromObjCPtr1);
4827 if (AssignLeft != AssignRight) {
4828 return AssignLeft? ImplicitConversionSequence::Better
4830 }
4831 }
4832 }
4833
4834 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4835 // Check for a better reference binding based on the kind of bindings.
4836 if (isBetterReferenceBindingKind(SCS1, SCS2))
4838 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4840 }
4841
4842 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4843 // bullet 3).
4845 = CompareQualificationConversions(S, SCS1, SCS2))
4846 return QualCK;
4847
4850 return ObtCK;
4851
4852 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4853 // C++ [over.ics.rank]p3b4:
4854 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4855 // which the references refer are the same type except for
4856 // top-level cv-qualifiers, and the type to which the reference
4857 // initialized by S2 refers is more cv-qualified than the type
4858 // to which the reference initialized by S1 refers.
4859 QualType T1 = SCS1.getToType(2);
4860 QualType T2 = SCS2.getToType(2);
4861 T1 = S.Context.getCanonicalType(T1);
4862 T2 = S.Context.getCanonicalType(T2);
4863 Qualifiers T1Quals, T2Quals;
4864 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4865 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4866 if (UnqualT1 == UnqualT2) {
4867 // Objective-C++ ARC: If the references refer to objects with different
4868 // lifetimes, prefer bindings that don't change lifetime.
4874 }
4875
4876 // If the type is an array type, promote the element qualifiers to the
4877 // type for comparison.
4878 if (isa<ArrayType>(T1) && T1Quals)
4879 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4880 if (isa<ArrayType>(T2) && T2Quals)
4881 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4882 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4884 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4886 }
4887 }
4888
4889 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4890 // floating-to-integral conversion if the integral conversion
4891 // is between types of the same size.
4892 // For example:
4893 // void f(float);
4894 // void f(int);
4895 // int main {
4896 // long a;
4897 // f(a);
4898 // }
4899 // Here, MSVC will call f(int) instead of generating a compile error
4900 // as clang will do in standard mode.
4901 if (S.getLangOpts().MSVCCompat &&
4904 SCS2.Second == ICK_Floating_Integral &&
4905 S.Context.getTypeSize(SCS1.getFromType()) ==
4906 S.Context.getTypeSize(SCS1.getToType(2)))
4908
4909 // Prefer a compatible vector conversion over a lax vector conversion
4910 // For example:
4911 //
4912 // typedef float __v4sf __attribute__((__vector_size__(16)));
4913 // void f(vector float);
4914 // void f(vector signed int);
4915 // int main() {
4916 // __v4sf a;
4917 // f(a);
4918 // }
4919 // Here, we'd like to choose f(vector float) and not
4920 // report an ambiguous call error
4921 if (SCS1.Second == ICK_Vector_Conversion &&
4922 SCS2.Second == ICK_Vector_Conversion) {
4923 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4924 SCS1.getFromType(), SCS1.getToType(2));
4925 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4926 SCS2.getFromType(), SCS2.getToType(2));
4927
4928 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4929 return SCS1IsCompatibleVectorConversion
4932 }
4933
4934 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4936 bool SCS1IsCompatibleSVEVectorConversion =
4937 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4938 bool SCS2IsCompatibleSVEVectorConversion =
4939 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4940
4941 if (SCS1IsCompatibleSVEVectorConversion !=
4942 SCS2IsCompatibleSVEVectorConversion)
4943 return SCS1IsCompatibleSVEVectorConversion
4946 }
4947
4948 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4950 bool SCS1IsCompatibleRVVVectorConversion =
4952 bool SCS2IsCompatibleRVVVectorConversion =
4954
4955 if (SCS1IsCompatibleRVVVectorConversion !=
4956 SCS2IsCompatibleRVVVectorConversion)
4957 return SCS1IsCompatibleRVVVectorConversion
4960 }
4962}
4963
4964/// CompareOverflowBehaviorConversions - Compares two standard conversion
4965/// sequences to determine whether they can be ranked based on their
4966/// OverflowBehaviorType's underlying type.
4982
4983/// CompareQualificationConversions - Compares two standard conversion
4984/// sequences to determine whether they can be ranked based on their
4985/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4988 const StandardConversionSequence& SCS1,
4989 const StandardConversionSequence& SCS2) {
4990 // C++ [over.ics.rank]p3:
4991 // -- S1 and S2 differ only in their qualification conversion and
4992 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4993 // [C++98]
4994 // [...] and the cv-qualification signature of type T1 is a proper subset
4995 // of the cv-qualification signature of type T2, and S1 is not the
4996 // deprecated string literal array-to-pointer conversion (4.2).
4997 // [C++2a]
4998 // [...] where T1 can be converted to T2 by a qualification conversion.
4999 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5000 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5002
5003 // FIXME: the example in the standard doesn't use a qualification
5004 // conversion (!)
5005 QualType T1 = SCS1.getToType(2);
5006 QualType T2 = SCS2.getToType(2);
5007 T1 = S.Context.getCanonicalType(T1);
5008 T2 = S.Context.getCanonicalType(T2);
5009 assert(!T1->isReferenceType() && !T2->isReferenceType());
5010 Qualifiers T1Quals, T2Quals;
5011 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5012 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5013
5014 // If the types are the same, we won't learn anything by unwrapping
5015 // them.
5016 if (UnqualT1 == UnqualT2)
5018
5019 // Don't ever prefer a standard conversion sequence that uses the deprecated
5020 // string literal array to pointer conversion.
5021 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5022 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5023
5024 // Objective-C++ ARC:
5025 // Prefer qualification conversions not involving a change in lifetime
5026 // to qualification conversions that do change lifetime.
5029 CanPick1 = false;
5032 CanPick2 = false;
5033
5034 bool ObjCLifetimeConversion;
5035 if (CanPick1 &&
5036 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5037 CanPick1 = false;
5038 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5039 // directions, so we can't short-cut this second check in general.
5040 if (CanPick2 &&
5041 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5042 CanPick2 = false;
5043
5044 if (CanPick1 != CanPick2)
5045 return CanPick1 ? ImplicitConversionSequence::Better
5048}
5049
5050/// CompareDerivedToBaseConversions - Compares two standard conversion
5051/// sequences to determine whether they can be ranked based on their
5052/// various kinds of derived-to-base conversions (C++
5053/// [over.ics.rank]p4b3). As part of these checks, we also look at
5054/// conversions between Objective-C interface types.
5057 const StandardConversionSequence& SCS1,
5058 const StandardConversionSequence& SCS2) {
5059 QualType FromType1 = SCS1.getFromType();
5060 QualType ToType1 = SCS1.getToType(1);
5061 QualType FromType2 = SCS2.getFromType();
5062 QualType ToType2 = SCS2.getToType(1);
5063
5064 // Adjust the types we're converting from via the array-to-pointer
5065 // conversion, if we need to.
5066 if (SCS1.First == ICK_Array_To_Pointer)
5067 FromType1 = S.Context.getArrayDecayedType(FromType1);
5068 if (SCS2.First == ICK_Array_To_Pointer)
5069 FromType2 = S.Context.getArrayDecayedType(FromType2);
5070
5071 // Canonicalize all of the types.
5072 FromType1 = S.Context.getCanonicalType(FromType1);
5073 ToType1 = S.Context.getCanonicalType(ToType1);
5074 FromType2 = S.Context.getCanonicalType(FromType2);
5075 ToType2 = S.Context.getCanonicalType(ToType2);
5076
5077 // C++ [over.ics.rank]p4b3:
5078 //
5079 // If class B is derived directly or indirectly from class A and
5080 // class C is derived directly or indirectly from B,
5081 //
5082 // Compare based on pointer conversions.
5083 if (SCS1.Second == ICK_Pointer_Conversion &&
5085 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5086 FromType1->isPointerType() && FromType2->isPointerType() &&
5087 ToType1->isPointerType() && ToType2->isPointerType()) {
5088 QualType FromPointee1 =
5090 QualType ToPointee1 =
5092 QualType FromPointee2 =
5094 QualType ToPointee2 =
5096
5097 // -- conversion of C* to B* is better than conversion of C* to A*,
5098 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5099 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5101 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5103 }
5104
5105 // -- conversion of B* to A* is better than conversion of C* to A*,
5106 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5107 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5109 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5111 }
5112 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5114 const ObjCObjectPointerType *FromPtr1
5115 = FromType1->getAs<ObjCObjectPointerType>();
5116 const ObjCObjectPointerType *FromPtr2
5117 = FromType2->getAs<ObjCObjectPointerType>();
5118 const ObjCObjectPointerType *ToPtr1
5119 = ToType1->getAs<ObjCObjectPointerType>();
5120 const ObjCObjectPointerType *ToPtr2
5121 = ToType2->getAs<ObjCObjectPointerType>();
5122
5123 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5124 // Apply the same conversion ranking rules for Objective-C pointer types
5125 // that we do for C++ pointers to class types. However, we employ the
5126 // Objective-C pseudo-subtyping relationship used for assignment of
5127 // Objective-C pointer types.
5128 bool FromAssignLeft
5129 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5130 bool FromAssignRight
5131 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5132 bool ToAssignLeft
5133 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5134 bool ToAssignRight
5135 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5136
5137 // A conversion to an a non-id object pointer type or qualified 'id'
5138 // type is better than a conversion to 'id'.
5139 if (ToPtr1->isObjCIdType() &&
5140 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5142 if (ToPtr2->isObjCIdType() &&
5143 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5145
5146 // A conversion to a non-id object pointer type is better than a
5147 // conversion to a qualified 'id' type
5148 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5150 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5152
5153 // A conversion to an a non-Class object pointer type or qualified 'Class'
5154 // type is better than a conversion to 'Class'.
5155 if (ToPtr1->isObjCClassType() &&
5156 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5158 if (ToPtr2->isObjCClassType() &&
5159 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5161
5162 // A conversion to a non-Class object pointer type is better than a
5163 // conversion to a qualified 'Class' type.
5164 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5166 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5168
5169 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5170 if (S.Context.hasSameType(FromType1, FromType2) &&
5171 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5172 (ToAssignLeft != ToAssignRight)) {
5173 if (FromPtr1->isSpecialized()) {
5174 // "conversion of B<A> * to B * is better than conversion of B * to
5175 // C *.
5176 bool IsFirstSame =
5177 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5178 bool IsSecondSame =
5179 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5180 if (IsFirstSame) {
5181 if (!IsSecondSame)
5183 } else if (IsSecondSame)
5185 }
5186 return ToAssignLeft? ImplicitConversionSequence::Worse
5188 }
5189
5190 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5191 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5192 (FromAssignLeft != FromAssignRight))
5193 return FromAssignLeft? ImplicitConversionSequence::Better
5195 }
5196 }
5197
5198 // Ranking of member-pointer types.
5199 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5200 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5201 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5202 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5203 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5204 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5205 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5206 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5207 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5208 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5209 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5210 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5211 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5212 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5214 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5216 }
5217 // conversion of B::* to C::* is better than conversion of A::* to C::*
5218 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5219 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5221 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5223 }
5224 }
5225
5226 if (SCS1.Second == ICK_Derived_To_Base) {
5227 // -- conversion of C to B is better than conversion of C to A,
5228 // -- binding of an expression of type C to a reference of type
5229 // B& is better than binding an expression of type C to a
5230 // reference of type A&,
5231 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5232 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5233 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5235 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5237 }
5238
5239 // -- conversion of B to A is better than conversion of C to A.
5240 // -- binding of an expression of type B to a reference of type
5241 // A& is better than binding an expression of type C to a
5242 // reference of type A&,
5243 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5244 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5245 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5247 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5249 }
5250 }
5251
5253}
5254
5256 if (!T.getQualifiers().hasUnaligned())
5257 return T;
5258
5259 Qualifiers Q;
5260 T = Ctx.getUnqualifiedArrayType(T, Q);
5261 Q.removeUnaligned();
5262 return Ctx.getQualifiedType(T, Q);
5263}
5264
5267 QualType OrigT1, QualType OrigT2,
5268 ReferenceConversions *ConvOut) {
5269 assert(!OrigT1->isReferenceType() &&
5270 "T1 must be the pointee type of the reference type");
5271 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5272
5273 QualType T1 = Context.getCanonicalType(OrigT1);
5274 QualType T2 = Context.getCanonicalType(OrigT2);
5275 Qualifiers T1Quals, T2Quals;
5276 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5277 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5278
5279 ReferenceConversions ConvTmp;
5280 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5281 Conv = ReferenceConversions();
5282
5283 // C++2a [dcl.init.ref]p4:
5284 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5285 // reference-related to "cv2 T2" if T1 is similar to T2, or
5286 // T1 is a base class of T2.
5287 // "cv1 T1" is reference-compatible with "cv2 T2" if
5288 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5289 // "pointer to cv1 T1" via a standard conversion sequence.
5290
5291 // Check for standard conversions we can apply to pointers: derived-to-base
5292 // conversions, ObjC pointer conversions, and function pointer conversions.
5293 // (Qualification conversions are checked last.)
5294 if (UnqualT1 == UnqualT2) {
5295 // Nothing to do.
5296 } else if (isCompleteType(Loc, OrigT2) &&
5297 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5298 Conv |= ReferenceConversions::DerivedToBase;
5299 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5300 UnqualT2->isObjCObjectOrInterfaceType() &&
5301 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5302 Conv |= ReferenceConversions::ObjC;
5303 else if (UnqualT2->isFunctionType() &&
5304 IsFunctionConversion(UnqualT2, UnqualT1)) {
5305 Conv |= ReferenceConversions::Function;
5306 // No need to check qualifiers; function types don't have them.
5307 return Ref_Compatible;
5308 }
5309 bool ConvertedReferent = Conv != 0;
5310
5311 // We can have a qualification conversion. Compute whether the types are
5312 // similar at the same time.
5313 bool PreviousToQualsIncludeConst = true;
5314 bool TopLevel = true;
5315 do {
5316 if (T1 == T2)
5317 break;
5318
5319 // We will need a qualification conversion.
5320 Conv |= ReferenceConversions::Qualification;
5321
5322 // Track whether we performed a qualification conversion anywhere other
5323 // than the top level. This matters for ranking reference bindings in
5324 // overload resolution.
5325 if (!TopLevel)
5326 Conv |= ReferenceConversions::NestedQualification;
5327
5328 // MS compiler ignores __unaligned qualifier for references; do the same.
5329 T1 = withoutUnaligned(Context, T1);
5330 T2 = withoutUnaligned(Context, T2);
5331
5332 // If we find a qualifier mismatch, the types are not reference-compatible,
5333 // but are still be reference-related if they're similar.
5334 bool ObjCLifetimeConversion = false;
5335 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5336 PreviousToQualsIncludeConst,
5337 ObjCLifetimeConversion, getASTContext()))
5338 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5339 ? Ref_Related
5341
5342 // FIXME: Should we track this for any level other than the first?
5343 if (ObjCLifetimeConversion)
5344 Conv |= ReferenceConversions::ObjCLifetime;
5345
5346 TopLevel = false;
5347 } while (Context.UnwrapSimilarTypes(T1, T2));
5348
5349 // At this point, if the types are reference-related, we must either have the
5350 // same inner type (ignoring qualifiers), or must have already worked out how
5351 // to convert the referent.
5352 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5355}
5356
5357/// Look for a user-defined conversion to a value reference-compatible
5358/// with DeclType. Return true if something definite is found.
5359static bool
5361 QualType DeclType, SourceLocation DeclLoc,
5362 Expr *Init, QualType T2, bool AllowRvalues,
5363 bool AllowExplicit) {
5364 assert(T2->isRecordType() && "Can only find conversions of record types.");
5365 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5366 OverloadCandidateSet CandidateSet(
5368 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5369 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5370 NamedDecl *D = *I;
5372 if (isa<UsingShadowDecl>(D))
5373 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5374
5375 FunctionTemplateDecl *ConvTemplate
5376 = dyn_cast<FunctionTemplateDecl>(D);
5377 CXXConversionDecl *Conv;
5378 if (ConvTemplate)
5379 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5380 else
5381 Conv = cast<CXXConversionDecl>(D);
5382
5383 if (AllowRvalues) {
5384 // If we are initializing an rvalue reference, don't permit conversion
5385 // functions that return lvalues.
5386 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5387 const ReferenceType *RefType
5389 if (RefType && !RefType->getPointeeType()->isFunctionType())
5390 continue;
5391 }
5392
5393 if (!ConvTemplate &&
5395 DeclLoc,
5396 Conv->getConversionType()
5401 continue;
5402 } else {
5403 // If the conversion function doesn't return a reference type,
5404 // it can't be considered for this conversion. An rvalue reference
5405 // is only acceptable if its referencee is a function type.
5406
5407 const ReferenceType *RefType =
5409 if (!RefType ||
5410 (!RefType->isLValueReferenceType() &&
5411 !RefType->getPointeeType()->isFunctionType()))
5412 continue;
5413 }
5414
5415 if (ConvTemplate)
5417 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5418 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5419 else
5421 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5422 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5423 }
5424
5425 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5426
5428 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5429 case OR_Success:
5430
5431 assert(Best->HasFinalConversion);
5432
5433 // C++ [over.ics.ref]p1:
5434 //
5435 // [...] If the parameter binds directly to the result of
5436 // applying a conversion function to the argument
5437 // expression, the implicit conversion sequence is a
5438 // user-defined conversion sequence (13.3.3.1.2), with the
5439 // second standard conversion sequence either an identity
5440 // conversion or, if the conversion function returns an
5441 // entity of a type that is a derived class of the parameter
5442 // type, a derived-to-base Conversion.
5443 if (!Best->FinalConversion.DirectBinding)
5444 return false;
5445
5446 ICS.setUserDefined();
5447 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5448 ICS.UserDefined.After = Best->FinalConversion;
5449 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5450 ICS.UserDefined.ConversionFunction = Best->Function;
5451 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5452 ICS.UserDefined.EllipsisConversion = false;
5453 assert(ICS.UserDefined.After.ReferenceBinding &&
5455 "Expected a direct reference binding!");
5456 return true;
5457
5458 case OR_Ambiguous:
5459 ICS.setAmbiguous();
5460 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5461 Cand != CandidateSet.end(); ++Cand)
5462 if (Cand->Best)
5463 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5464 return true;
5465
5467 case OR_Deleted:
5468 // There was no suitable conversion, or we found a deleted
5469 // conversion; continue with other checks.
5470 return false;
5471 }
5472
5473 llvm_unreachable("Invalid OverloadResult!");
5474}
5475
5476/// Compute an implicit conversion sequence for reference
5477/// initialization.
5478static ImplicitConversionSequence
5480 SourceLocation DeclLoc,
5481 bool SuppressUserConversions,
5482 bool AllowExplicit) {
5483 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5484
5485 // Most paths end in a failed conversion.
5488
5489 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5490 QualType T2 = Init->getType();
5491
5492 // If the initializer is the address of an overloaded function, try
5493 // to resolve the overloaded function. If all goes well, T2 is the
5494 // type of the resulting function.
5495 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5498 false, Found))
5499 T2 = Fn->getType();
5500 }
5501
5502 // Compute some basic properties of the types and the initializer.
5503 bool isRValRef = DeclType->isRValueReferenceType();
5504 Expr::Classification InitCategory = Init->Classify(S.Context);
5505
5507 Sema::ReferenceCompareResult RefRelationship =
5508 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5509
5510 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5511 ICS.setStandard();
5513 // FIXME: A reference binding can be a function conversion too. We should
5514 // consider that when ordering reference-to-function bindings.
5515 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5517 : (RefConv & Sema::ReferenceConversions::ObjC)
5519 : ICK_Identity;
5521 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5522 // a reference binding that performs a non-top-level qualification
5523 // conversion as a qualification conversion, not as an identity conversion.
5524 ICS.Standard.Third = (RefConv &
5525 Sema::ReferenceConversions::NestedQualification)
5527 : ICK_Identity;
5528 ICS.Standard.setFromType(T2);
5529 ICS.Standard.setToType(0, T2);
5530 ICS.Standard.setToType(1, T1);
5531 ICS.Standard.setToType(2, T1);
5532 ICS.Standard.ReferenceBinding = true;
5533 ICS.Standard.DirectBinding = BindsDirectly;
5534 ICS.Standard.IsLvalueReference = !isRValRef;
5536 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5539 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5540 ICS.Standard.FromBracedInitList = false;
5541 ICS.Standard.CopyConstructor = nullptr;
5543 };
5544
5545 // C++0x [dcl.init.ref]p5:
5546 // A reference to type "cv1 T1" is initialized by an expression
5547 // of type "cv2 T2" as follows:
5548
5549 // -- If reference is an lvalue reference and the initializer expression
5550 if (!isRValRef) {
5551 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5552 // reference-compatible with "cv2 T2," or
5553 //
5554 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5555 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5556 // C++ [over.ics.ref]p1:
5557 // When a parameter of reference type binds directly (8.5.3)
5558 // to an argument expression, the implicit conversion sequence
5559 // is the identity conversion, unless the argument expression
5560 // has a type that is a derived class of the parameter type,
5561 // in which case the implicit conversion sequence is a
5562 // derived-to-base Conversion (13.3.3.1).
5563 SetAsReferenceBinding(/*BindsDirectly=*/true);
5564
5565 // Nothing more to do: the inaccessibility/ambiguity check for
5566 // derived-to-base conversions is suppressed when we're
5567 // computing the implicit conversion sequence (C++
5568 // [over.best.ics]p2).
5569 return ICS;
5570 }
5571
5572 // -- has a class type (i.e., T2 is a class type), where T1 is
5573 // not reference-related to T2, and can be implicitly
5574 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5575 // is reference-compatible with "cv3 T3" 92) (this
5576 // conversion is selected by enumerating the applicable
5577 // conversion functions (13.3.1.6) and choosing the best
5578 // one through overload resolution (13.3)),
5579 if (!SuppressUserConversions && T2->isRecordType() &&
5580 S.isCompleteType(DeclLoc, T2) &&
5581 RefRelationship == Sema::Ref_Incompatible) {
5582 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5583 Init, T2, /*AllowRvalues=*/false,
5584 AllowExplicit))
5585 return ICS;
5586 }
5587 }
5588
5589 // -- Otherwise, the reference shall be an lvalue reference to a
5590 // non-volatile const type (i.e., cv1 shall be const), or the reference
5591 // shall be an rvalue reference.
5592 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5593 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5595 return ICS;
5596 }
5597
5598 // -- If the initializer expression
5599 //
5600 // -- is an xvalue, class prvalue, array prvalue or function
5601 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5602 if (RefRelationship == Sema::Ref_Compatible &&
5603 (InitCategory.isXValue() ||
5604 (InitCategory.isPRValue() &&
5605 (T2->isRecordType() || T2->isArrayType())) ||
5606 (InitCategory.isLValue() && T2->isFunctionType()))) {
5607 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5608 // binding unless we're binding to a class prvalue.
5609 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5610 // allow the use of rvalue references in C++98/03 for the benefit of
5611 // standard library implementors; therefore, we need the xvalue check here.
5612 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5613 !(InitCategory.isPRValue() || T2->isRecordType()));
5614 return ICS;
5615 }
5616
5617 // -- has a class type (i.e., T2 is a class type), where T1 is not
5618 // reference-related to T2, and can be implicitly converted to
5619 // an xvalue, class prvalue, or function lvalue of type
5620 // "cv3 T3", where "cv1 T1" is reference-compatible with
5621 // "cv3 T3",
5622 //
5623 // then the reference is bound to the value of the initializer
5624 // expression in the first case and to the result of the conversion
5625 // in the second case (or, in either case, to an appropriate base
5626 // class subobject).
5627 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5628 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5629 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5630 Init, T2, /*AllowRvalues=*/true,
5631 AllowExplicit)) {
5632 // In the second case, if the reference is an rvalue reference
5633 // and the second standard conversion sequence of the
5634 // user-defined conversion sequence includes an lvalue-to-rvalue
5635 // conversion, the program is ill-formed.
5636 if (ICS.isUserDefined() && isRValRef &&
5639
5640 return ICS;
5641 }
5642
5643 // A temporary of function type cannot be created; don't even try.
5644 if (T1->isFunctionType())
5645 return ICS;
5646
5647 // -- Otherwise, a temporary of type "cv1 T1" is created and
5648 // initialized from the initializer expression using the
5649 // rules for a non-reference copy initialization (8.5). The
5650 // reference is then bound to the temporary. If T1 is
5651 // reference-related to T2, cv1 must be the same
5652 // cv-qualification as, or greater cv-qualification than,
5653 // cv2; otherwise, the program is ill-formed.
5654 if (RefRelationship == Sema::Ref_Related) {
5655 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5656 // we would be reference-compatible or reference-compatible with
5657 // added qualification. But that wasn't the case, so the reference
5658 // initialization fails.
5659 //
5660 // Note that we only want to check address spaces and cvr-qualifiers here.
5661 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5662 Qualifiers T1Quals = T1.getQualifiers();
5663 Qualifiers T2Quals = T2.getQualifiers();
5664 T1Quals.removeObjCGCAttr();
5665 T1Quals.removeObjCLifetime();
5666 T2Quals.removeObjCGCAttr();
5667 T2Quals.removeObjCLifetime();
5668 // MS compiler ignores __unaligned qualifier for references; do the same.
5669 T1Quals.removeUnaligned();
5670 T2Quals.removeUnaligned();
5671 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5672 return ICS;
5673 }
5674
5675 // If at least one of the types is a class type, the types are not
5676 // related, and we aren't allowed any user conversions, the
5677 // reference binding fails. This case is important for breaking
5678 // recursion, since TryImplicitConversion below will attempt to
5679 // create a temporary through the use of a copy constructor.
5680 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5681 (T1->isRecordType() || T2->isRecordType()))
5682 return ICS;
5683
5684 // If T1 is reference-related to T2 and the reference is an rvalue
5685 // reference, the initializer expression shall not be an lvalue.
5686 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5687 Init->Classify(S.Context).isLValue()) {
5689 return ICS;
5690 }
5691
5692 // C++ [over.ics.ref]p2:
5693 // When a parameter of reference type is not bound directly to
5694 // an argument expression, the conversion sequence is the one
5695 // required to convert the argument expression to the
5696 // underlying type of the reference according to
5697 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5698 // to copy-initializing a temporary of the underlying type with
5699 // the argument expression. Any difference in top-level
5700 // cv-qualification is subsumed by the initialization itself
5701 // and does not constitute a conversion.
5702 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5703 AllowedExplicit::None,
5704 /*InOverloadResolution=*/false,
5705 /*CStyle=*/false,
5706 /*AllowObjCWritebackConversion=*/false,
5707 /*AllowObjCConversionOnExplicit=*/false);
5708
5709 // Of course, that's still a reference binding.
5710 if (ICS.isStandard()) {
5711 ICS.Standard.ReferenceBinding = true;
5712 ICS.Standard.IsLvalueReference = !isRValRef;
5713 ICS.Standard.BindsToFunctionLvalue = false;
5714 ICS.Standard.BindsToRvalue = true;
5717 } else if (ICS.isUserDefined()) {
5718 const ReferenceType *LValRefType =
5721
5722 // C++ [over.ics.ref]p3:
5723 // Except for an implicit object parameter, for which see 13.3.1, a
5724 // standard conversion sequence cannot be formed if it requires [...]
5725 // binding an rvalue reference to an lvalue other than a function
5726 // lvalue.
5727 // Note that the function case is not possible here.
5728 if (isRValRef && LValRefType) {
5730 return ICS;
5731 }
5732
5734 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5736 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5740 }
5741
5742 return ICS;
5743}
5744
5745static ImplicitConversionSequence
5746TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5747 bool SuppressUserConversions,
5748 bool InOverloadResolution,
5749 bool AllowObjCWritebackConversion,
5750 bool AllowExplicit = false);
5751
5752/// TryListConversion - Try to copy-initialize a value of type ToType from the
5753/// initializer list From.
5754static ImplicitConversionSequence
5756 bool SuppressUserConversions,
5757 bool InOverloadResolution,
5758 bool AllowObjCWritebackConversion) {
5759 // C++11 [over.ics.list]p1:
5760 // When an argument is an initializer list, it is not an expression and
5761 // special rules apply for converting it to a parameter type.
5762
5764 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5765
5766 // We need a complete type for what follows. With one C++20 exception,
5767 // incomplete types can never be initialized from init lists.
5768 QualType InitTy = ToType;
5769 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5770 if (AT && S.getLangOpts().CPlusPlus20)
5771 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5772 // C++20 allows list initialization of an incomplete array type.
5773 InitTy = IAT->getElementType();
5774 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5775 return Result;
5776
5777 // C++20 [over.ics.list]/2:
5778 // If the initializer list is a designated-initializer-list, a conversion
5779 // is only possible if the parameter has an aggregate type
5780 //
5781 // FIXME: The exception for reference initialization here is not part of the
5782 // language rules, but follow other compilers in adding it as a tentative DR
5783 // resolution.
5784 bool IsDesignatedInit = From->hasDesignatedInit();
5785 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5786 IsDesignatedInit)
5787 return Result;
5788
5789 // Per DR1467 and DR2137:
5790 // If the parameter type is an aggregate class X and the initializer list
5791 // has a single element of type cv U, where U is X or a class derived from
5792 // X, the implicit conversion sequence is the one required to convert the
5793 // element to the parameter type.
5794 //
5795 // Otherwise, if the parameter type is a character array [... ]
5796 // and the initializer list has a single element that is an
5797 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5798 // implicit conversion sequence is the identity conversion.
5799 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5800 if (ToType->isRecordType() && ToType->isAggregateType()) {
5801 QualType InitType = From->getInit(0)->getType();
5802 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5803 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5804 return TryCopyInitialization(S, From->getInit(0), ToType,
5805 SuppressUserConversions,
5806 InOverloadResolution,
5807 AllowObjCWritebackConversion);
5808 }
5809
5810 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5811 InitializedEntity Entity =
5813 /*Consumed=*/false);
5814 if (S.CanPerformCopyInitialization(Entity, From)) {
5815 Result.setStandard();
5816 Result.Standard.setAsIdentityConversion();
5817 Result.Standard.setFromType(ToType);
5818 Result.Standard.setAllToTypes(ToType);
5819 return Result;
5820 }
5821 }
5822 }
5823
5824 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5825 // C++11 [over.ics.list]p2:
5826 // If the parameter type is std::initializer_list<X> or "array of X" and
5827 // all the elements can be implicitly converted to X, the implicit
5828 // conversion sequence is the worst conversion necessary to convert an
5829 // element of the list to X.
5830 //
5831 // C++14 [over.ics.list]p3:
5832 // Otherwise, if the parameter type is "array of N X", if the initializer
5833 // list has exactly N elements or if it has fewer than N elements and X is
5834 // default-constructible, and if all the elements of the initializer list
5835 // can be implicitly converted to X, the implicit conversion sequence is
5836 // the worst conversion necessary to convert an element of the list to X.
5837 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5838 unsigned e = From->getNumInits();
5841 QualType());
5842 QualType ContTy = ToType;
5843 bool IsUnbounded = false;
5844 if (AT) {
5845 InitTy = AT->getElementType();
5846 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5847 if (CT->getSize().ult(e)) {
5848 // Too many inits, fatally bad
5850 ToType);
5851 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5852 return Result;
5853 }
5854 if (CT->getSize().ugt(e)) {
5855 // Need an init from empty {}, is there one?
5856 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5857 From->getEndLoc(), /*isExplicit=*/false);
5858 EmptyList.setType(S.Context.VoidTy);
5859 DfltElt = TryListConversion(
5860 S, &EmptyList, InitTy, SuppressUserConversions,
5861 InOverloadResolution, AllowObjCWritebackConversion);
5862 if (DfltElt.isBad()) {
5863 // No {} init, fatally bad
5865 ToType);
5866 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5867 return Result;
5868 }
5869 }
5870 } else {
5871 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5872 IsUnbounded = true;
5873 if (!e) {
5874 // Cannot convert to zero-sized.
5876 ToType);
5877 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5878 return Result;
5879 }
5880 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5881 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5883 }
5884 }
5885
5886 Result.setStandard();
5887 Result.Standard.setAsIdentityConversion();
5888 Result.Standard.setFromType(InitTy);
5889 Result.Standard.setAllToTypes(InitTy);
5890 for (unsigned i = 0; i < e; ++i) {
5891 Expr *Init = From->getInit(i);
5893 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5894 AllowObjCWritebackConversion);
5895
5896 // Keep the worse conversion seen so far.
5897 // FIXME: Sequences are not totally ordered, so 'worse' can be
5898 // ambiguous. CWG has been informed.
5900 Result) ==
5902 Result = ICS;
5903 // Bail as soon as we find something unconvertible.
5904 if (Result.isBad()) {
5905 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5906 return Result;
5907 }
5908 }
5909 }
5910
5911 // If we needed any implicit {} initialization, compare that now.
5912 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5913 // has been informed that this might not be the best thing.
5914 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5915 S, From->getEndLoc(), DfltElt, Result) ==
5917 Result = DfltElt;
5918 // Record the type being initialized so that we may compare sequences
5919 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5920 return Result;
5921 }
5922
5923 // C++14 [over.ics.list]p4:
5924 // C++11 [over.ics.list]p3:
5925 // Otherwise, if the parameter is a non-aggregate class X and overload
5926 // resolution chooses a single best constructor [...] the implicit
5927 // conversion sequence is a user-defined conversion sequence. If multiple
5928 // constructors are viable but none is better than the others, the
5929 // implicit conversion sequence is a user-defined conversion sequence.
5930 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5931 // This function can deal with initializer lists.
5932 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5933 AllowedExplicit::None,
5934 InOverloadResolution, /*CStyle=*/false,
5935 AllowObjCWritebackConversion,
5936 /*AllowObjCConversionOnExplicit=*/false);
5937 }
5938
5939 // C++14 [over.ics.list]p5:
5940 // C++11 [over.ics.list]p4:
5941 // Otherwise, if the parameter has an aggregate type which can be
5942 // initialized from the initializer list [...] the implicit conversion
5943 // sequence is a user-defined conversion sequence.
5944 if (ToType->isAggregateType()) {
5945 // Type is an aggregate, argument is an init list. At this point it comes
5946 // down to checking whether the initialization works.
5947 // FIXME: Find out whether this parameter is consumed or not.
5948 InitializedEntity Entity =
5950 /*Consumed=*/false);
5952 From)) {
5953 Result.setUserDefined();
5954 Result.UserDefined.Before.setAsIdentityConversion();
5955 // Initializer lists don't have a type.
5956 Result.UserDefined.Before.setFromType(QualType());
5957 Result.UserDefined.Before.setAllToTypes(QualType());
5958
5959 Result.UserDefined.After.setAsIdentityConversion();
5960 Result.UserDefined.After.setFromType(ToType);
5961 Result.UserDefined.After.setAllToTypes(ToType);
5962 Result.UserDefined.ConversionFunction = nullptr;
5963 }
5964 return Result;
5965 }
5966
5967 // C++14 [over.ics.list]p6:
5968 // C++11 [over.ics.list]p5:
5969 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5970 if (ToType->isReferenceType()) {
5971 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5972 // mention initializer lists in any way. So we go by what list-
5973 // initialization would do and try to extrapolate from that.
5974
5975 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5976
5977 // If the initializer list has a single element that is reference-related
5978 // to the parameter type, we initialize the reference from that.
5979 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5980 Expr *Init = From->getInit(0);
5981
5982 QualType T2 = Init->getType();
5983
5984 // If the initializer is the address of an overloaded function, try
5985 // to resolve the overloaded function. If all goes well, T2 is the
5986 // type of the resulting function.
5987 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5990 Init, ToType, false, Found))
5991 T2 = Fn->getType();
5992 }
5993
5994 // Compute some basic properties of the types and the initializer.
5995 Sema::ReferenceCompareResult RefRelationship =
5996 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5997
5998 if (RefRelationship >= Sema::Ref_Related) {
5999 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
6000 SuppressUserConversions,
6001 /*AllowExplicit=*/false);
6002 }
6003 }
6004
6005 // Otherwise, we bind the reference to a temporary created from the
6006 // initializer list.
6007 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6008 InOverloadResolution,
6009 AllowObjCWritebackConversion);
6010 if (Result.isFailure())
6011 return Result;
6012 assert(!Result.isEllipsis() &&
6013 "Sub-initialization cannot result in ellipsis conversion.");
6014
6015 // Can we even bind to a temporary?
6016 if (ToType->isRValueReferenceType() ||
6017 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6018 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6019 Result.UserDefined.After;
6020 SCS.ReferenceBinding = true;
6022 SCS.BindsToRvalue = true;
6023 SCS.BindsToFunctionLvalue = false;
6026 SCS.FromBracedInitList = false;
6027
6028 } else
6030 From, ToType);
6031 return Result;
6032 }
6033
6034 // C++14 [over.ics.list]p7:
6035 // C++11 [over.ics.list]p6:
6036 // Otherwise, if the parameter type is not a class:
6037 if (!ToType->isRecordType()) {
6038 // - if the initializer list has one element that is not itself an
6039 // initializer list, the implicit conversion sequence is the one
6040 // required to convert the element to the parameter type.
6041 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6042 // single integer.
6043 unsigned NumInits = From->getNumInits();
6044 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6045 !isa<EmbedExpr>(From->getInit(0))) {
6047 S, From->getInit(0), ToType, SuppressUserConversions,
6048 InOverloadResolution, AllowObjCWritebackConversion);
6049 if (Result.isStandard())
6050 Result.Standard.FromBracedInitList = true;
6051 }
6052 // - if the initializer list has no elements, the implicit conversion
6053 // sequence is the identity conversion.
6054 else if (NumInits == 0) {
6055 Result.setStandard();
6056 Result.Standard.setAsIdentityConversion();
6057 Result.Standard.setFromType(ToType);
6058 Result.Standard.setAllToTypes(ToType);
6059 }
6060 return Result;
6061 }
6062
6063 // C++14 [over.ics.list]p8:
6064 // C++11 [over.ics.list]p7:
6065 // In all cases other than those enumerated above, no conversion is possible
6066 return Result;
6067}
6068
6069/// TryCopyInitialization - Try to copy-initialize a value of type
6070/// ToType from the expression From. Return the implicit conversion
6071/// sequence required to pass this argument, which may be a bad
6072/// conversion sequence (meaning that the argument cannot be passed to
6073/// a parameter of this type). If @p SuppressUserConversions, then we
6074/// do not permit any user-defined conversion sequences.
6075static ImplicitConversionSequence
6077 bool SuppressUserConversions,
6078 bool InOverloadResolution,
6079 bool AllowObjCWritebackConversion,
6080 bool AllowExplicit) {
6081 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6082 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6083 InOverloadResolution,AllowObjCWritebackConversion);
6084
6085 if (ToType->isReferenceType())
6086 return TryReferenceInit(S, From, ToType,
6087 /*FIXME:*/ From->getBeginLoc(),
6088 SuppressUserConversions, AllowExplicit);
6089
6090 return TryImplicitConversion(S, From, ToType,
6091 SuppressUserConversions,
6092 AllowedExplicit::None,
6093 InOverloadResolution,
6094 /*CStyle=*/false,
6095 AllowObjCWritebackConversion,
6096 /*AllowObjCConversionOnExplicit=*/false);
6097}
6098
6099static bool TryCopyInitialization(const CanQualType FromQTy,
6100 const CanQualType ToQTy,
6101 Sema &S,
6102 SourceLocation Loc,
6103 ExprValueKind FromVK) {
6104 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6106 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6107
6108 return !ICS.isBad();
6109}
6110
6111/// TryObjectArgumentInitialization - Try to initialize the object
6112/// parameter of the given member function (@c Method) from the
6113/// expression @p From.
6115 Sema &S, SourceLocation Loc, QualType FromType,
6116 Expr::Classification FromClassification, CXXMethodDecl *Method,
6117 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6118 QualType ExplicitParameterType = QualType(),
6119 bool SuppressUserConversion = false) {
6120
6121 // We need to have an object of class type.
6122 if (const auto *PT = FromType->getAs<PointerType>()) {
6123 FromType = PT->getPointeeType();
6124
6125 // When we had a pointer, it's implicitly dereferenced, so we
6126 // better have an lvalue.
6127 assert(FromClassification.isLValue());
6128 }
6129
6130 auto ValueKindFromClassification = [](Expr::Classification C) {
6131 if (C.isPRValue())
6132 return clang::VK_PRValue;
6133 if (C.isXValue())
6134 return VK_XValue;
6135 return clang::VK_LValue;
6136 };
6137
6138 if (Method->isExplicitObjectMemberFunction()) {
6139 if (ExplicitParameterType.isNull())
6140 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6141 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6142 ValueKindFromClassification(FromClassification));
6144 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6145 /*InOverloadResolution=*/true, false);
6146 if (ICS.isBad())
6147 ICS.Bad.FromExpr = nullptr;
6148 return ICS;
6149 }
6150
6151 assert(FromType->isRecordType());
6152
6153 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6154 // C++98 [class.dtor]p2:
6155 // A destructor can be invoked for a const, volatile or const volatile
6156 // object.
6157 // C++98 [over.match.funcs]p4:
6158 // For static member functions, the implicit object parameter is considered
6159 // to match any object (since if the function is selected, the object is
6160 // discarded).
6161 Qualifiers Quals = Method->getMethodQualifiers();
6162 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6163 Quals.addConst();
6164 Quals.addVolatile();
6165 }
6166
6167 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6168
6169 // Set up the conversion sequence as a "bad" conversion, to allow us
6170 // to exit early.
6172
6173 // C++0x [over.match.funcs]p4:
6174 // For non-static member functions, the type of the implicit object
6175 // parameter is
6176 //
6177 // - "lvalue reference to cv X" for functions declared without a
6178 // ref-qualifier or with the & ref-qualifier
6179 // - "rvalue reference to cv X" for functions declared with the &&
6180 // ref-qualifier
6181 //
6182 // where X is the class of which the function is a member and cv is the
6183 // cv-qualification on the member function declaration.
6184 //
6185 // However, when finding an implicit conversion sequence for the argument, we
6186 // are not allowed to perform user-defined conversions
6187 // (C++ [over.match.funcs]p5). We perform a simplified version of
6188 // reference binding here, that allows class rvalues to bind to
6189 // non-constant references.
6190
6191 // First check the qualifiers.
6192 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6193 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6194 if (ImplicitParamType.getCVRQualifiers() !=
6195 FromTypeCanon.getLocalCVRQualifiers() &&
6196 !ImplicitParamType.isAtLeastAsQualifiedAs(
6197 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6199 FromType, ImplicitParamType);
6200 return ICS;
6201 }
6202
6203 if (FromTypeCanon.hasAddressSpace()) {
6204 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6205 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6206 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6207 S.getASTContext())) {
6209 FromType, ImplicitParamType);
6210 return ICS;
6211 }
6212 }
6213
6214 // Check that we have either the same type or a derived type. It
6215 // affects the conversion rank.
6216 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6217 ImplicitConversionKind SecondKind;
6218 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6219 SecondKind = ICK_Identity;
6220 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6221 SecondKind = ICK_Derived_To_Base;
6222 } else if (!Method->isExplicitObjectMemberFunction()) {
6224 FromType, ImplicitParamType);
6225 return ICS;
6226 }
6227
6228 // Check the ref-qualifier.
6229 switch (Method->getRefQualifier()) {
6230 case RQ_None:
6231 // Do nothing; we don't care about lvalueness or rvalueness.
6232 break;
6233
6234 case RQ_LValue:
6235 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6236 // non-const lvalue reference cannot bind to an rvalue
6238 ImplicitParamType);
6239 return ICS;
6240 }
6241 break;
6242
6243 case RQ_RValue:
6244 if (!FromClassification.isRValue()) {
6245 // rvalue reference cannot bind to an lvalue
6247 ImplicitParamType);
6248 return ICS;
6249 }
6250 break;
6251 }
6252
6253 // Success. Mark this as a reference binding.
6254 ICS.setStandard();
6256 ICS.Standard.Second = SecondKind;
6257 ICS.Standard.setFromType(FromType);
6258 ICS.Standard.setAllToTypes(ImplicitParamType);
6259 ICS.Standard.ReferenceBinding = true;
6260 ICS.Standard.DirectBinding = true;
6261 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6262 ICS.Standard.BindsToFunctionLvalue = false;
6263 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6264 ICS.Standard.FromBracedInitList = false;
6266 = (Method->getRefQualifier() == RQ_None);
6267 return ICS;
6268}
6269
6270/// PerformObjectArgumentInitialization - Perform initialization of
6271/// the implicit object parameter for the given Method with the given
6272/// expression.
6274 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6276 QualType FromRecordType, DestType;
6277 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6278
6279 if (getLangOpts().HLSL &&
6282 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6283 /*BasePath=*/nullptr, VK_PRValue,
6285 }
6286
6287 Expr::Classification FromClassification;
6288 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6289 FromRecordType = PT->getPointeeType();
6290 DestType = Method->getThisType();
6291 FromClassification = Expr::Classification::makeSimpleLValue();
6292 } else {
6293 FromRecordType = From->getType();
6294 DestType = ImplicitParamRecordType;
6295 FromClassification = From->Classify(Context);
6296
6297 // CWG2813 [expr.call]p6:
6298 // If the function is an implicit object member function, the object
6299 // expression of the class member access shall be a glvalue [...]
6300 if (From->isPRValue()) {
6301 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6302 Method->getRefQualifier() !=
6304 }
6305 }
6306
6307 // Note that we always use the true parent context when performing
6308 // the actual argument initialization.
6310 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6311 Method->getParent());
6312 if (ICS.isBad()) {
6313 switch (ICS.Bad.Kind) {
6315 Qualifiers FromQs = FromRecordType.getQualifiers();
6316 Qualifiers ToQs = DestType.getQualifiers();
6317 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6318 if (CVR) {
6319 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6320 << Method->getDeclName() << FromRecordType << (CVR - 1)
6321 << From->getSourceRange();
6322 Diag(Method->getLocation(), diag::note_previous_decl)
6323 << Method->getDeclName();
6324 return ExprError();
6325 }
6326 break;
6327 }
6328
6331 bool IsRValueQualified =
6332 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6333 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6334 << Method->getDeclName() << FromClassification.isRValue()
6335 << IsRValueQualified;
6336 Diag(Method->getLocation(), diag::note_previous_decl)
6337 << Method->getDeclName();
6338 return ExprError();
6339 }
6340
6343 break;
6344
6347 llvm_unreachable("Lists are not objects");
6348 }
6349
6350 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6351 << ImplicitParamRecordType << FromRecordType
6352 << From->getSourceRange();
6353 }
6354
6355 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6356 ExprResult FromRes =
6357 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6358 if (FromRes.isInvalid())
6359 return ExprError();
6360 From = FromRes.get();
6361 }
6362
6363 if (!Context.hasSameType(From->getType(), DestType)) {
6364 CastKind CK;
6365 QualType PteeTy = DestType->getPointeeType();
6366 LangAS DestAS =
6367 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6368 if (FromRecordType.getAddressSpace() != DestAS)
6369 CK = CK_AddressSpaceConversion;
6370 else
6371 CK = CK_NoOp;
6372 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6373 }
6374 return From;
6375}
6376
6377/// TryContextuallyConvertToBool - Attempt to contextually convert the
6378/// expression From to bool (C++0x [conv]p3).
6381 // C++ [dcl.init]/17.8:
6382 // - Otherwise, if the initialization is direct-initialization, the source
6383 // type is std::nullptr_t, and the destination type is bool, the initial
6384 // value of the object being initialized is false.
6385 if (From->getType()->isNullPtrType())
6387 S.Context.BoolTy,
6388 From->isGLValue());
6389
6390 // All other direct-initialization of bool is equivalent to an implicit
6391 // conversion to bool in which explicit conversions are permitted.
6392 return TryImplicitConversion(S, From, S.Context.BoolTy,
6393 /*SuppressUserConversions=*/false,
6394 AllowedExplicit::Conversions,
6395 /*InOverloadResolution=*/false,
6396 /*CStyle=*/false,
6397 /*AllowObjCWritebackConversion=*/false,
6398 /*AllowObjCConversionOnExplicit=*/false);
6399}
6400
6402 if (checkPlaceholderForOverload(*this, From))
6403 return ExprError();
6404 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6405 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6406
6408 if (!ICS.isBad())
6409 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6412 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6413 << From->getType() << From->getSourceRange();
6414 return ExprError();
6415}
6416
6417/// Check that the specified conversion is permitted in a converted constant
6418/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6419/// is acceptable.
6422 // Since we know that the target type is an integral or unscoped enumeration
6423 // type, most conversion kinds are impossible. All possible First and Third
6424 // conversions are fine.
6425 switch (SCS.Second) {
6426 case ICK_Identity:
6428 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6430 return true;
6431
6433 // Conversion from an integral or unscoped enumeration type to bool is
6434 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6435 // conversion, so we allow it in a converted constant expression.
6436 //
6437 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6438 // a lot of popular code. We should at least add a warning for this
6439 // (non-conforming) extension.
6441 SCS.getToType(2)->isBooleanType();
6442
6444 case ICK_Pointer_Member:
6445 // C++1z: null pointer conversions and null member pointer conversions are
6446 // only permitted if the source type is std::nullptr_t.
6447 return SCS.getFromType()->isNullPtrType();
6448
6461 case ICK_Vector_Splat:
6462 case ICK_Complex_Real:
6472 return false;
6473
6478 llvm_unreachable("found a first conversion kind in Second");
6479
6481 case ICK_Qualification:
6482 llvm_unreachable("found a third conversion kind in Second");
6483
6485 break;
6486 }
6487
6488 llvm_unreachable("unknown conversion kind");
6489}
6490
6491/// BuildConvertedConstantExpression - Check that the expression From is a
6492/// converted constant expression of type T, perform the conversion but
6493/// does not evaluate the expression
6495 QualType T, CCEKind CCE,
6496 NamedDecl *Dest,
6497 APValue &PreNarrowingValue) {
6498 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6500 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6501 "converted constant expression outside C++11 or TTP matching");
6502
6503 if (checkPlaceholderForOverload(S, From))
6504 return ExprError();
6505
6506 if (From->containsErrors()) {
6507 if (S.Context.hasSameType(From->getType(), T))
6508 return From;
6509
6510 // The expression already has errors, so the correct cast kind can't be
6511 // determined. Use RecoveryExpr to keep the expected type T and mark the
6512 // result as invalid, preventing further cascading errors.
6513 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6514 T);
6515 }
6516
6517 // C++1z [expr.const]p3:
6518 // A converted constant expression of type T is an expression,
6519 // implicitly converted to type T, where the converted
6520 // expression is a constant expression and the implicit conversion
6521 // sequence contains only [... list of conversions ...].
6523 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6525 : TryCopyInitialization(S, From, T,
6526 /*SuppressUserConversions=*/false,
6527 /*InOverloadResolution=*/false,
6528 /*AllowObjCWritebackConversion=*/false,
6529 /*AllowExplicit=*/false);
6530 StandardConversionSequence *SCS = nullptr;
6531 switch (ICS.getKind()) {
6533 SCS = &ICS.Standard;
6534 break;
6536 if (T->isRecordType())
6537 SCS = &ICS.UserDefined.Before;
6538 else
6539 SCS = &ICS.UserDefined.After;
6540 break;
6544 return S.Diag(From->getBeginLoc(),
6545 diag::err_typecheck_converted_constant_expression)
6546 << From->getType() << From->getSourceRange() << T;
6547 return ExprError();
6548
6551 llvm_unreachable("bad conversion in converted constant expression");
6552 }
6553
6554 // Check that we would only use permitted conversions.
6555 if (!CheckConvertedConstantConversions(S, *SCS)) {
6556 return S.Diag(From->getBeginLoc(),
6557 diag::err_typecheck_converted_constant_expression_disallowed)
6558 << From->getType() << From->getSourceRange() << T;
6559 }
6560 // [...] and where the reference binding (if any) binds directly.
6561 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6562 return S.Diag(From->getBeginLoc(),
6563 diag::err_typecheck_converted_constant_expression_indirect)
6564 << From->getType() << From->getSourceRange() << T;
6565 }
6566 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6567 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6568 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6569 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6570 // case explicitly.
6571 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6572 return S.Diag(From->getBeginLoc(),
6573 diag::err_reference_bind_to_bitfield_in_cce)
6574 << From->getSourceRange();
6575 }
6576
6577 // Usually we can simply apply the ImplicitConversionSequence we formed
6578 // earlier, but that's not guaranteed to work when initializing an object of
6579 // class type.
6581 bool IsTemplateArgument =
6583 if (T->isRecordType()) {
6584 assert(IsTemplateArgument &&
6585 "unexpected class type converted constant expr");
6589 SourceLocation(), From);
6590 } else {
6591 Result =
6593 }
6594 if (Result.isInvalid())
6595 return Result;
6596
6597 // C++2a [intro.execution]p5:
6598 // A full-expression is [...] a constant-expression [...]
6599 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6600 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6601 IsTemplateArgument);
6602 if (Result.isInvalid())
6603 return Result;
6604
6605 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6606
6607 // Check for a narrowing implicit conversion.
6608 bool ReturnPreNarrowingValue = false;
6609 QualType PreNarrowingType;
6610 switch (SCS->getNarrowingKind(
6611 S.Context, Result.get(), PreNarrowingValue, PreNarrowingType,
6612 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6614 // Implicit conversion to a narrower type, and the value is not a constant
6615 // expression. We'll diagnose this in a moment.
6616 case NK_Not_Narrowing:
6617 break;
6618
6620 if (CCE == CCEKind::ArrayBound &&
6621 PreNarrowingType->isIntegralOrEnumerationType() &&
6622 PreNarrowingValue.isInt()) {
6623 // Don't diagnose array bound narrowing here; we produce more precise
6624 // errors by allowing the un-narrowed value through.
6625 ReturnPreNarrowingValue = true;
6626 break;
6627 }
6628 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6629 << CCE << /*Constant*/ 1
6630 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6631 // If this is an SFINAE Context, treat the result as invalid so it stops
6632 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6633 // FIXME: Should do this whenever the above diagnostic is an error, but
6634 // without further changes this would degrade some other diagnostics.
6635 if (S.isSFINAEContext())
6636 return ExprError();
6637 break;
6638
6640 // Implicit conversion to a narrower type, but the expression is
6641 // value-dependent so we can't tell whether it's actually narrowing.
6642 // For matching the parameters of a TTP, the conversion is ill-formed
6643 // if it may narrow.
6644 if (CCE != CCEKind::TempArgStrict)
6645 break;
6646 [[fallthrough]];
6647 case NK_Type_Narrowing:
6648 // FIXME: It would be better to diagnose that the expression is not a
6649 // constant expression.
6650 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6651 << CCE << /*Constant*/ 0 << From->getType() << T;
6652 if (S.isSFINAEContext())
6653 return ExprError();
6654 break;
6655 }
6656 if (!ReturnPreNarrowingValue)
6657 PreNarrowingValue = {};
6658
6659 return Result;
6660}
6661
6662/// CheckConvertedConstantExpression - Check that the expression From is a
6663/// converted constant expression of type T, perform the conversion and produce
6664/// the converted expression, per C++11 [expr.const]p3.
6667 CCEKind CCE, bool RequireInt,
6668 NamedDecl *Dest) {
6669
6670 APValue PreNarrowingValue;
6672 PreNarrowingValue);
6673 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6674 Value = APValue();
6675 return Result;
6676 }
6677 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6678 RequireInt, PreNarrowingValue);
6679}
6680
6682 CCEKind CCE,
6683 NamedDecl *Dest) {
6684 APValue PreNarrowingValue;
6685 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6686 PreNarrowingValue);
6687}
6688
6690 APValue &Value, CCEKind CCE,
6691 NamedDecl *Dest) {
6692 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6693 Dest);
6694}
6695
6697 llvm::APSInt &Value,
6698 CCEKind CCE) {
6699 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6700
6701 APValue V;
6702 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6703 /*Dest=*/nullptr);
6704 if (!R.isInvalid() && !R.get()->isValueDependent())
6705 Value = V.getInt();
6706 return R;
6707}
6708
6711 CCEKind CCE, bool RequireInt,
6712 const APValue &PreNarrowingValue) {
6713
6714 ExprResult Result = E;
6715 // Check the expression is a constant expression.
6718 Expr::EvalResult Eval;
6719 Eval.Diag = &Notes;
6720 Eval.ExtendedDiag = &MSWarning;
6721
6722 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6723
6724 ConstantExprKind Kind;
6725 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6726 Kind = ConstantExprKind::ClassTemplateArgument;
6727 else if (CCE == CCEKind::TemplateArg)
6728 Kind = ConstantExprKind::NonClassTemplateArgument;
6729 else
6730 Kind = ConstantExprKind::Normal;
6731
6732 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6733 (RequireInt && !Eval.Val.isInt())) {
6734 // The expression can't be folded, so we can't keep it at this position in
6735 // the AST.
6736 Result = ExprError();
6737 } else {
6738 Value = Eval.Val;
6739 // For -fms-compatibility mode we relax some requirements
6740 // for constant folding in non-SFINAE contexts
6741 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6742 if (Notes.empty() && !CantFold) {
6743 for (auto &Info : MSWarning)
6744 Diag(Info.first, Info.second);
6745 // It's a constant expression.
6746 Expr *E = Result.get();
6747 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6748 // We expect a ConstantExpr to have a value associated with it
6749 // by this point.
6750 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6751 "ConstantExpr has no value associated with it");
6752 (void)CE;
6753 } else {
6755 }
6756 if (!PreNarrowingValue.isAbsent())
6757 Value = std::move(PreNarrowingValue);
6758 return E;
6759 }
6760 }
6761
6762 // It's not a constant expression. Produce an appropriate diagnostic.
6763 if (Notes.size() == 1 &&
6764 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6765 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6766 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6767 diag::note_constexpr_invalid_template_arg) {
6768 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6769 for (unsigned I = 0; I < Notes.size(); ++I)
6770 Diag(Notes[I].first, Notes[I].second);
6771 } else {
6772 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6773 << CCE << E->getSourceRange();
6774 for (unsigned I = 0; I < Notes.size(); ++I)
6775 Diag(Notes[I].first, Notes[I].second);
6776 }
6777 return ExprError();
6778}
6779
6780/// dropPointerConversions - If the given standard conversion sequence
6781/// involves any pointer conversions, remove them. This may change
6782/// the result type of the conversion sequence.
6784 if (SCS.Second == ICK_Pointer_Conversion) {
6785 SCS.Second = ICK_Identity;
6786 SCS.Dimension = ICK_Identity;
6787 SCS.Third = ICK_Identity;
6788 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6789 }
6790}
6791
6792/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6793/// convert the expression From to an Objective-C pointer type.
6794static ImplicitConversionSequence
6796 // Do an implicit conversion to 'id'.
6799 = TryImplicitConversion(S, From, Ty,
6800 // FIXME: Are these flags correct?
6801 /*SuppressUserConversions=*/false,
6802 AllowedExplicit::Conversions,
6803 /*InOverloadResolution=*/false,
6804 /*CStyle=*/false,
6805 /*AllowObjCWritebackConversion=*/false,
6806 /*AllowObjCConversionOnExplicit=*/true);
6807
6808 // Strip off any final conversions to 'id'.
6809 switch (ICS.getKind()) {
6814 break;
6815
6818 break;
6819
6822 break;
6823 }
6824
6825 return ICS;
6826}
6827
6829 if (checkPlaceholderForOverload(*this, From))
6830 return ExprError();
6831
6832 QualType Ty = Context.getObjCIdType();
6835 if (!ICS.isBad())
6836 return PerformImplicitConversion(From, Ty, ICS,
6838 return ExprResult();
6839}
6840
6841static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6842 const Expr *Base = nullptr;
6843 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6844 "expected a member expression");
6845
6846 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6847 M && !M->isImplicitAccess())
6848 Base = M->getBase();
6849 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6850 M && !M->isImplicitAccess())
6851 Base = M->getBase();
6852
6853 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6854
6855 if (T->isPointerType())
6856 T = T->getPointeeType();
6857
6858 return T;
6859}
6860
6862 const FunctionDecl *Fun) {
6863 QualType ObjType = Obj->getType();
6864 if (ObjType->isPointerType()) {
6865 ObjType = ObjType->getPointeeType();
6866 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6868 /*CanOverflow=*/false, FPOptionsOverride());
6869 }
6870 return Obj;
6871}
6872
6880
6882 Expr *Object, MultiExprArg &Args,
6883 SmallVectorImpl<Expr *> &NewArgs) {
6884 assert(Method->isExplicitObjectMemberFunction() &&
6885 "Method is not an explicit member function");
6886 assert(NewArgs.empty() && "NewArgs should be empty");
6887
6888 NewArgs.reserve(Args.size() + 1);
6889 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6890 NewArgs.push_back(This);
6891 NewArgs.append(Args.begin(), Args.end());
6892 Args = NewArgs;
6894 Method, Object->getBeginLoc());
6895}
6896
6897/// Determine whether the provided type is an integral type, or an enumeration
6898/// type of a permitted flavor.
6900 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6901 : T->isIntegralOrUnscopedEnumerationType();
6902}
6903
6904static ExprResult
6907 QualType T, UnresolvedSetImpl &ViableConversions) {
6908
6909 if (Converter.Suppress)
6910 return ExprError();
6911
6912 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6913 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6914 CXXConversionDecl *Conv =
6915 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6917 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6918 }
6919 return From;
6920}
6921
6922static bool
6925 QualType T, bool HadMultipleCandidates,
6926 UnresolvedSetImpl &ExplicitConversions) {
6927 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6928 DeclAccessPair Found = ExplicitConversions[0];
6929 CXXConversionDecl *Conversion =
6930 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6931
6932 // The user probably meant to invoke the given explicit
6933 // conversion; use it.
6934 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6935 std::string TypeStr;
6936 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6937
6938 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6940 "static_cast<" + TypeStr + ">(")
6942 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6943 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6944
6945 // If we aren't in a SFINAE context, build a call to the
6946 // explicit conversion function.
6947 if (SemaRef.isSFINAEContext())
6948 return true;
6949
6950 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6951 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6952 HadMultipleCandidates);
6953 if (Result.isInvalid())
6954 return true;
6955
6956 // Replace the conversion with a RecoveryExpr, so we don't try to
6957 // instantiate it later, but can further diagnose here.
6958 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6959 From, Result.get()->getType());
6960 if (Result.isInvalid())
6961 return true;
6962 From = Result.get();
6963 }
6964 return false;
6965}
6966
6967static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6969 QualType T, bool HadMultipleCandidates,
6971 CXXConversionDecl *Conversion =
6972 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6973 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6974
6975 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6976 if (!Converter.SuppressConversion) {
6977 if (SemaRef.isSFINAEContext())
6978 return true;
6979
6980 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6981 << From->getSourceRange();
6982 }
6983
6984 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6985 HadMultipleCandidates);
6986 if (Result.isInvalid())
6987 return true;
6988 // Record usage of conversion in an implicit cast.
6989 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6990 CK_UserDefinedConversion, Result.get(),
6991 nullptr, Result.get()->getValueKind(),
6992 SemaRef.CurFPFeatureOverrides());
6993 return false;
6994}
6995
6997 Sema &SemaRef, SourceLocation Loc, Expr *From,
6999 if (!Converter.match(From->getType()) && !Converter.Suppress)
7000 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
7001 << From->getSourceRange();
7002
7003 return SemaRef.DefaultLvalueConversion(From);
7004}
7005
7006static void
7008 UnresolvedSetImpl &ViableConversions,
7009 OverloadCandidateSet &CandidateSet) {
7010 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7011 NamedDecl *D = FoundDecl.getDecl();
7012 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7013 if (isa<UsingShadowDecl>(D))
7014 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7015
7016 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7018 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7019 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7020 continue;
7021 }
7023 SemaRef.AddConversionCandidate(
7024 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7025 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7026 }
7027}
7028
7029/// Attempt to convert the given expression to a type which is accepted
7030/// by the given converter.
7031///
7032/// This routine will attempt to convert an expression of class type to a
7033/// type accepted by the specified converter. In C++11 and before, the class
7034/// must have a single non-explicit conversion function converting to a matching
7035/// type. In C++1y, there can be multiple such conversion functions, but only
7036/// one target type.
7037///
7038/// \param Loc The source location of the construct that requires the
7039/// conversion.
7040///
7041/// \param From The expression we're converting from.
7042///
7043/// \param Converter Used to control and diagnose the conversion process.
7044///
7045/// \returns The expression, converted to an integral or enumeration type if
7046/// successful.
7048 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7049 // We can't perform any more checking for type-dependent expressions.
7050 if (From->isTypeDependent())
7051 return From;
7052
7053 // Process placeholders immediately.
7054 if (From->hasPlaceholderType()) {
7055 ExprResult result = CheckPlaceholderExpr(From);
7056 if (result.isInvalid())
7057 return result;
7058 From = result.get();
7059 }
7060
7061 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7062 ExprResult Converted = DefaultLvalueConversion(From);
7063 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7064 From = Converted.isUsable() ? Converted.get() : nullptr;
7065 // If the expression already has a matching type, we're golden.
7066 if (Converter.match(T))
7067 return Converted;
7068
7069 // FIXME: Check for missing '()' if T is a function type?
7070
7071 // We can only perform contextual implicit conversions on objects of class
7072 // type.
7073 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7074 if (!RecordTy || !getLangOpts().CPlusPlus) {
7075 if (!Converter.Suppress)
7076 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7077 return From;
7078 }
7079
7080 // We must have a complete class type.
7081 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7082 ContextualImplicitConverter &Converter;
7083 Expr *From;
7084
7085 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7086 : Converter(Converter), From(From) {}
7087
7088 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7089 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7090 }
7091 } IncompleteDiagnoser(Converter, From);
7092
7093 if (Converter.Suppress ? !isCompleteType(Loc, T)
7094 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7095 return From;
7096
7097 // Look for a conversion to an integral or enumeration type.
7099 ViableConversions; // These are *potentially* viable in C++1y.
7100 UnresolvedSet<4> ExplicitConversions;
7101 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7102 ->getDefinitionOrSelf()
7103 ->getVisibleConversionFunctions();
7104
7105 bool HadMultipleCandidates =
7106 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7107
7108 // To check that there is only one target type, in C++1y:
7109 QualType ToType;
7110 bool HasUniqueTargetType = true;
7111
7112 // Collect explicit or viable (potentially in C++1y) conversions.
7113 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7114 NamedDecl *D = (*I)->getUnderlyingDecl();
7115 CXXConversionDecl *Conversion;
7116 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7117 if (ConvTemplate) {
7119 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7120 else
7121 continue; // C++11 does not consider conversion operator templates(?).
7122 } else
7123 Conversion = cast<CXXConversionDecl>(D);
7124
7125 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7126 "Conversion operator templates are considered potentially "
7127 "viable in C++1y");
7128
7129 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7130 if (Converter.match(CurToType) || ConvTemplate) {
7131
7132 if (Conversion->isExplicit()) {
7133 // FIXME: For C++1y, do we need this restriction?
7134 // cf. diagnoseNoViableConversion()
7135 if (!ConvTemplate)
7136 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7137 } else {
7138 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7139 if (ToType.isNull())
7140 ToType = CurToType.getUnqualifiedType();
7141 else if (HasUniqueTargetType &&
7142 (CurToType.getUnqualifiedType() != ToType))
7143 HasUniqueTargetType = false;
7144 }
7145 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7146 }
7147 }
7148 }
7149
7150 if (getLangOpts().CPlusPlus14) {
7151 // C++1y [conv]p6:
7152 // ... An expression e of class type E appearing in such a context
7153 // is said to be contextually implicitly converted to a specified
7154 // type T and is well-formed if and only if e can be implicitly
7155 // converted to a type T that is determined as follows: E is searched
7156 // for conversion functions whose return type is cv T or reference to
7157 // cv T such that T is allowed by the context. There shall be
7158 // exactly one such T.
7159
7160 // If no unique T is found:
7161 if (ToType.isNull()) {
7162 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7163 HadMultipleCandidates,
7164 ExplicitConversions))
7165 return ExprError();
7166 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7167 }
7168
7169 // If more than one unique Ts are found:
7170 if (!HasUniqueTargetType)
7171 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7172 ViableConversions);
7173
7174 // If one unique T is found:
7175 // First, build a candidate set from the previously recorded
7176 // potentially viable conversions.
7178 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7179 CandidateSet);
7180
7181 // Then, perform overload resolution over the candidate set.
7183 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7184 case OR_Success: {
7185 // Apply this conversion.
7187 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7188 if (recordConversion(*this, Loc, From, Converter, T,
7189 HadMultipleCandidates, Found))
7190 return ExprError();
7191 break;
7192 }
7193 case OR_Ambiguous:
7194 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7195 ViableConversions);
7197 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7198 HadMultipleCandidates,
7199 ExplicitConversions))
7200 return ExprError();
7201 [[fallthrough]];
7202 case OR_Deleted:
7203 // We'll complain below about a non-integral condition type.
7204 break;
7205 }
7206 } else {
7207 switch (ViableConversions.size()) {
7208 case 0: {
7209 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7210 HadMultipleCandidates,
7211 ExplicitConversions))
7212 return ExprError();
7213
7214 // We'll complain below about a non-integral condition type.
7215 break;
7216 }
7217 case 1: {
7218 // Apply this conversion.
7219 DeclAccessPair Found = ViableConversions[0];
7220 if (recordConversion(*this, Loc, From, Converter, T,
7221 HadMultipleCandidates, Found))
7222 return ExprError();
7223 break;
7224 }
7225 default:
7226 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7227 ViableConversions);
7228 }
7229 }
7230
7231 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7232}
7233
7234/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7235/// an acceptable non-member overloaded operator for a call whose
7236/// arguments have types T1 (and, if non-empty, T2). This routine
7237/// implements the check in C++ [over.match.oper]p3b2 concerning
7238/// enumeration types.
7240 FunctionDecl *Fn,
7241 ArrayRef<Expr *> Args) {
7242 QualType T1 = Args[0]->getType();
7243 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7244
7245 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7246 return true;
7247
7248 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7249 return true;
7250
7251 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7252 if (Proto->getNumParams() < 1)
7253 return false;
7254
7255 if (T1->isEnumeralType()) {
7256 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7257 if (Context.hasSameUnqualifiedType(T1, ArgType))
7258 return true;
7259 }
7260
7261 if (Proto->getNumParams() < 2)
7262 return false;
7263
7264 if (!T2.isNull() && T2->isEnumeralType()) {
7265 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7266 if (Context.hasSameUnqualifiedType(T2, ArgType))
7267 return true;
7268 }
7269
7270 return false;
7271}
7272
7275 return false;
7276
7277 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7278 return FD->isTargetMultiVersion();
7279
7280 if (!FD->isMultiVersion())
7281 return false;
7282
7283 // Among multiple target versions consider either the default,
7284 // or the first non-default in the absence of default version.
7285 unsigned SeenAt = 0;
7286 unsigned I = 0;
7287 bool HasDefault = false;
7289 FD, [&](const FunctionDecl *CurFD) {
7290 if (FD == CurFD)
7291 SeenAt = I;
7292 else if (CurFD->isTargetMultiVersionDefault())
7293 HasDefault = true;
7294 ++I;
7295 });
7296 return HasDefault || SeenAt != 0;
7297}
7298
7301 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7302 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7303 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7304 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7305 bool StrictPackMatch) {
7306 const FunctionProtoType *Proto
7307 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7308 assert(Proto && "Functions without a prototype cannot be overloaded");
7309 assert(!Function->getDescribedFunctionTemplate() &&
7310 "Use AddTemplateOverloadCandidate for function templates");
7311
7312 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7314 // If we get here, it's because we're calling a member function
7315 // that is named without a member access expression (e.g.,
7316 // "this->f") that was either written explicitly or created
7317 // implicitly. This can happen with a qualified call to a member
7318 // function, e.g., X::f(). We use an empty type for the implied
7319 // object argument (C++ [over.call.func]p3), and the acting context
7320 // is irrelevant.
7321 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7323 CandidateSet, SuppressUserConversions,
7324 PartialOverloading, EarlyConversions, PO,
7325 StrictPackMatch);
7326 return;
7327 }
7328 // We treat a constructor like a non-member function, since its object
7329 // argument doesn't participate in overload resolution.
7330 }
7331
7332 if (!CandidateSet.isNewCandidate(Function, PO))
7333 return;
7334
7335 // C++11 [class.copy]p11: [DR1402]
7336 // A defaulted move constructor that is defined as deleted is ignored by
7337 // overload resolution.
7338 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7339 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7340 Constructor->isMoveConstructor())
7341 return;
7342
7343 // Overload resolution is always an unevaluated context.
7346
7347 // C++ [over.match.oper]p3:
7348 // if no operand has a class type, only those non-member functions in the
7349 // lookup set that have a first parameter of type T1 or "reference to
7350 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7351 // is a right operand) a second parameter of type T2 or "reference to
7352 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7353 // candidate functions.
7354 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7356 return;
7357
7358 // Add this candidate
7359 OverloadCandidate &Candidate =
7360 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7361 Candidate.FoundDecl = FoundDecl;
7362 Candidate.Function = Function;
7363 Candidate.Viable = true;
7364 Candidate.RewriteKind =
7365 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7366 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7367 Candidate.ExplicitCallArguments = Args.size();
7368 Candidate.StrictPackMatch = StrictPackMatch;
7369
7370 // Explicit functions are not actually candidates at all if we're not
7371 // allowing them in this context, but keep them around so we can point
7372 // to them in diagnostics.
7373 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7374 Candidate.Viable = false;
7375 Candidate.FailureKind = ovl_fail_explicit;
7376 return;
7377 }
7378
7379 // Functions with internal linkage are only viable in the same module unit.
7380 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7381 /// FIXME: Currently, the semantics of linkage in clang is slightly
7382 /// different from the semantics in C++ spec. In C++ spec, only names
7383 /// have linkage. So that all entities of the same should share one
7384 /// linkage. But in clang, different entities of the same could have
7385 /// different linkage.
7386 const NamedDecl *ND = Function;
7387 bool IsImplicitlyInstantiated = false;
7388 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7389 ND = SpecInfo->getTemplate();
7390 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7392 }
7393
7394 /// Don't remove inline functions with internal linkage from the overload
7395 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7396 /// However:
7397 /// - Inline functions with internal linkage are a common pattern in
7398 /// headers to avoid ODR issues.
7399 /// - The global module is meant to be a transition mechanism for C and C++
7400 /// headers, and the current rules as written work against that goal.
7401 const bool IsInlineFunctionInGMF =
7402 Function->isFromGlobalModule() &&
7403 (IsImplicitlyInstantiated || Function->isInlined());
7404
7405 // Don't exclude internal-linkage entities from the current TU's global
7406 // module fragment.
7407 const Module *CurrentModule = getCurrentModule();
7408 const bool IsCurrentUnitGMFDecl =
7409 Function->isFromGlobalModule() && CurrentModule &&
7410 Function->getOwningModule()->getTopLevelModule() ==
7411 CurrentModule->getTopLevelModule();
7412
7413 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7414 !IsCurrentUnitGMFDecl) {
7415 Candidate.Viable = false;
7417 return;
7418 }
7419 }
7420
7422 Candidate.Viable = false;
7424 return;
7425 }
7426
7427 if (Constructor) {
7428 // C++ [class.copy]p3:
7429 // A member function template is never instantiated to perform the copy
7430 // of a class object to an object of its class type.
7431 CanQualType ClassType =
7432 Context.getCanonicalTagType(Constructor->getParent());
7433 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7434 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7435 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7436 ClassType))) {
7437 Candidate.Viable = false;
7439 return;
7440 }
7441
7442 // C++ [over.match.funcs]p8: (proposed DR resolution)
7443 // A constructor inherited from class type C that has a first parameter
7444 // of type "reference to P" (including such a constructor instantiated
7445 // from a template) is excluded from the set of candidate functions when
7446 // constructing an object of type cv D if the argument list has exactly
7447 // one argument and D is reference-related to P and P is reference-related
7448 // to C.
7449 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7450 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7451 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7452 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7453 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7454 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7455 SourceLocation Loc = Args.front()->getExprLoc();
7456 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7457 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7458 Candidate.Viable = false;
7460 return;
7461 }
7462 }
7463
7464 // Check that the constructor is capable of constructing an object in the
7465 // destination address space.
7467 Constructor->getMethodQualifiers().getAddressSpace(),
7468 CandidateSet.getDestAS(), getASTContext())) {
7469 Candidate.Viable = false;
7471 }
7472 }
7473
7474 unsigned NumParams = Proto->getNumParams();
7475
7476 // (C++ 13.3.2p2): A candidate function having fewer than m
7477 // parameters is viable only if it has an ellipsis in its parameter
7478 // list (8.3.5).
7479 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7480 !Proto->isVariadic() &&
7481 shouldEnforceArgLimit(PartialOverloading, Function)) {
7482 Candidate.Viable = false;
7484 return;
7485 }
7486
7487 // (C++ 13.3.2p2): A candidate function having more than m parameters
7488 // is viable only if the (m+1)st parameter has a default argument
7489 // (8.3.6). For the purposes of overload resolution, the
7490 // parameter list is truncated on the right, so that there are
7491 // exactly m parameters.
7492 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7493 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7494 !PartialOverloading) {
7495 // Not enough arguments.
7496 Candidate.Viable = false;
7498 return;
7499 }
7500
7501 // (CUDA B.1): Check for invalid calls between targets.
7502 if (getLangOpts().CUDA) {
7503 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7504 // Skip the check for callers that are implicit members, because in this
7505 // case we may not yet know what the member's target is; the target is
7506 // inferred for the member automatically, based on the bases and fields of
7507 // the class.
7508 if (!(Caller && Caller->isImplicit()) &&
7509 !CUDA().IsAllowedCall(Caller, Function)) {
7510 Candidate.Viable = false;
7511 Candidate.FailureKind = ovl_fail_bad_target;
7512 return;
7513 }
7514 }
7515
7516 if (Function->getTrailingRequiresClause()) {
7517 ConstraintSatisfaction Satisfaction;
7518 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7519 /*ForOverloadResolution*/ true) ||
7520 !Satisfaction.IsSatisfied) {
7521 Candidate.Viable = false;
7523 return;
7524 }
7525 }
7526
7527 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7528 // Determine the implicit conversion sequences for each of the
7529 // arguments.
7530 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7531 unsigned ConvIdx =
7532 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7533 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7534 // We already formed a conversion sequence for this parameter during
7535 // template argument deduction.
7536 } else if (ArgIdx < NumParams) {
7537 // (C++ 13.3.2p3): for F to be a viable function, there shall
7538 // exist for each argument an implicit conversion sequence
7539 // (13.3.3.1) that converts that argument to the corresponding
7540 // parameter of F.
7541 QualType ParamType = Proto->getParamType(ArgIdx);
7542 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7543 if (ParamABI == ParameterABI::HLSLOut ||
7544 ParamABI == ParameterABI::HLSLInOut) {
7545 ParamType = ParamType.getNonReferenceType();
7546 if (ParamABI == ParameterABI::HLSLInOut &&
7547 Args[ArgIdx]->getType().getAddressSpace() ==
7549 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7550 }
7551 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7552 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7553 /*InOverloadResolution=*/true,
7554 /*AllowObjCWritebackConversion=*/
7555 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7556 if (Candidate.Conversions[ConvIdx].isBad()) {
7557 Candidate.Viable = false;
7559 return;
7560 }
7561 } else {
7562 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7563 // argument for which there is no corresponding parameter is
7564 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7565 Candidate.Conversions[ConvIdx].setEllipsis();
7566 }
7567 }
7568
7569 if (EnableIfAttr *FailedAttr =
7570 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7571 Candidate.Viable = false;
7572 Candidate.FailureKind = ovl_fail_enable_if;
7573 Candidate.DeductionFailure.Data = FailedAttr;
7574 return;
7575 }
7576}
7577
7581 if (Methods.size() <= 1)
7582 return nullptr;
7583
7584 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7585 bool Match = true;
7586 ObjCMethodDecl *Method = Methods[b];
7587 unsigned NumNamedArgs = Sel.getNumArgs();
7588 // Method might have more arguments than selector indicates. This is due
7589 // to addition of c-style arguments in method.
7590 if (Method->param_size() > NumNamedArgs)
7591 NumNamedArgs = Method->param_size();
7592 if (Args.size() < NumNamedArgs)
7593 continue;
7594
7595 for (unsigned i = 0; i < NumNamedArgs; i++) {
7596 // We can't do any type-checking on a type-dependent argument.
7597 if (Args[i]->isTypeDependent()) {
7598 Match = false;
7599 break;
7600 }
7601
7602 ParmVarDecl *param = Method->parameters()[i];
7603 Expr *argExpr = Args[i];
7604 assert(argExpr && "SelectBestMethod(): missing expression");
7605
7606 // Strip the unbridged-cast placeholder expression off unless it's
7607 // a consumed argument.
7608 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7609 !param->hasAttr<CFConsumedAttr>())
7610 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7611
7612 // If the parameter is __unknown_anytype, move on to the next method.
7613 if (param->getType() == Context.UnknownAnyTy) {
7614 Match = false;
7615 break;
7616 }
7617
7618 ImplicitConversionSequence ConversionState
7619 = TryCopyInitialization(*this, argExpr, param->getType(),
7620 /*SuppressUserConversions*/false,
7621 /*InOverloadResolution=*/true,
7622 /*AllowObjCWritebackConversion=*/
7623 getLangOpts().ObjCAutoRefCount,
7624 /*AllowExplicit*/false);
7625 // This function looks for a reasonably-exact match, so we consider
7626 // incompatible pointer conversions to be a failure here.
7627 if (ConversionState.isBad() ||
7628 (ConversionState.isStandard() &&
7629 ConversionState.Standard.Second ==
7631 Match = false;
7632 break;
7633 }
7634 }
7635 // Promote additional arguments to variadic methods.
7636 if (Match && Method->isVariadic()) {
7637 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7638 if (Args[i]->isTypeDependent()) {
7639 Match = false;
7640 break;
7641 }
7643 Args[i], VariadicCallType::Method, nullptr);
7644 if (Arg.isInvalid()) {
7645 Match = false;
7646 break;
7647 }
7648 }
7649 } else {
7650 // Check for extra arguments to non-variadic methods.
7651 if (Args.size() != NumNamedArgs)
7652 Match = false;
7653 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7654 // Special case when selectors have no argument. In this case, select
7655 // one with the most general result type of 'id'.
7656 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7657 QualType ReturnT = Methods[b]->getReturnType();
7658 if (ReturnT->isObjCIdType())
7659 return Methods[b];
7660 }
7661 }
7662 }
7663
7664 if (Match)
7665 return Method;
7666 }
7667 return nullptr;
7668}
7669
7671 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7672 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7673 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7674 if (ThisArg) {
7675 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7676 assert(!isa<CXXConstructorDecl>(Method) &&
7677 "Shouldn't have `this` for ctors!");
7678 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7680 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7681 if (R.isInvalid())
7682 return false;
7683 ConvertedThis = R.get();
7684 } else {
7685 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7686 (void)MD;
7687 assert((MissingImplicitThis || MD->isStatic() ||
7689 "Expected `this` for non-ctor instance methods");
7690 }
7691 ConvertedThis = nullptr;
7692 }
7693
7694 // Ignore any variadic arguments. Converting them is pointless, since the
7695 // user can't refer to them in the function condition.
7696 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7697
7698 // Convert the arguments.
7699 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7700 ExprResult R;
7702 S.Context, Function->getParamDecl(I)),
7703 SourceLocation(), Args[I]);
7704
7705 if (R.isInvalid())
7706 return false;
7707
7708 ConvertedArgs.push_back(R.get());
7709 }
7710
7711 if (Trap.hasErrorOccurred())
7712 return false;
7713
7714 // Push default arguments if needed.
7715 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7716 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7717 ParmVarDecl *P = Function->getParamDecl(i);
7718 if (!P->hasDefaultArg())
7719 return false;
7720 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7721 if (R.isInvalid())
7722 return false;
7723 ConvertedArgs.push_back(R.get());
7724 }
7725
7726 if (Trap.hasErrorOccurred())
7727 return false;
7728 }
7729 return true;
7730}
7731
7733 SourceLocation CallLoc,
7734 ArrayRef<Expr *> Args,
7735 bool MissingImplicitThis) {
7736 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7737 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7738 return nullptr;
7739
7740 SFINAETrap Trap(*this);
7741 // Perform the access checking immediately so any access diagnostics are
7742 // caught by the SFINAE trap.
7743 llvm::scope_exit UndelayDiags(
7744 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7745 DelayedDiagnostics.popUndelayed(CurrentState);
7746 });
7747 SmallVector<Expr *, 16> ConvertedArgs;
7748 // FIXME: We should look into making enable_if late-parsed.
7749 Expr *DiscardedThis;
7751 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7752 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7753 return *EnableIfAttrs.begin();
7754
7755 for (auto *EIA : EnableIfAttrs) {
7757 // FIXME: This doesn't consider value-dependent cases, because doing so is
7758 // very difficult. Ideally, we should handle them more gracefully.
7759 if (EIA->getCond()->isValueDependent() ||
7760 !EIA->getCond()->EvaluateWithSubstitution(
7761 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7762 return EIA;
7763
7764 if (!Result.isInt() || !Result.getInt().getBoolValue())
7765 return EIA;
7766 }
7767 return nullptr;
7768}
7769
7770template <typename CheckFn>
7772 bool ArgDependent, SourceLocation Loc,
7773 CheckFn &&IsSuccessful) {
7775 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7776 if (ArgDependent == DIA->getArgDependent())
7777 Attrs.push_back(DIA);
7778 }
7779
7780 // Common case: No diagnose_if attributes, so we can quit early.
7781 if (Attrs.empty())
7782 return false;
7783
7784 auto WarningBegin = std::stable_partition(
7785 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7786 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7787 DIA->getWarningGroup().empty();
7788 });
7789
7790 // Note that diagnose_if attributes are late-parsed, so they appear in the
7791 // correct order (unlike enable_if attributes).
7792 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7793 IsSuccessful);
7794 if (ErrAttr != WarningBegin) {
7795 const DiagnoseIfAttr *DIA = *ErrAttr;
7796 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7797 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7798 << DIA->getParent() << DIA->getCond()->getSourceRange();
7799 return true;
7800 }
7801
7802 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7803 switch (Sev) {
7804 case DiagnoseIfAttr::DS_warning:
7806 case DiagnoseIfAttr::DS_error:
7807 return diag::Severity::Error;
7808 }
7809 llvm_unreachable("Fully covered switch above!");
7810 };
7811
7812 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7813 if (IsSuccessful(DIA)) {
7814 if (DIA->getWarningGroup().empty() &&
7815 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7816 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7817 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7818 << DIA->getParent() << DIA->getCond()->getSourceRange();
7819 } else {
7820 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7821 DIA->getWarningGroup());
7822 assert(DiagGroup);
7823 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7824 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7825 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7826 S.Diag(Loc, DiagID) << DIA->getMessage();
7827 }
7828 }
7829
7830 return false;
7831}
7832
7834 const Expr *ThisArg,
7836 SourceLocation Loc) {
7838 *this, Function, /*ArgDependent=*/true, Loc,
7839 [&](const DiagnoseIfAttr *DIA) {
7841 // It's sane to use the same Args for any redecl of this function, since
7842 // EvaluateWithSubstitution only cares about the position of each
7843 // argument in the arg list, not the ParmVarDecl* it maps to.
7844 if (!DIA->getCond()->EvaluateWithSubstitution(
7845 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7846 return false;
7847 return Result.isInt() && Result.getInt().getBoolValue();
7848 });
7849}
7850
7852 SourceLocation Loc) {
7854 *this, ND, /*ArgDependent=*/false, Loc,
7855 [&](const DiagnoseIfAttr *DIA) {
7856 bool Result;
7857 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7858 Result;
7859 });
7860}
7861
7863 ArrayRef<Expr *> Args,
7864 OverloadCandidateSet &CandidateSet,
7865 TemplateArgumentListInfo *ExplicitTemplateArgs,
7866 bool SuppressUserConversions,
7867 bool PartialOverloading,
7868 bool FirstArgumentIsBase) {
7869 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7870 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7871 ArrayRef<Expr *> FunctionArgs = Args;
7872
7873 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7874 FunctionDecl *FD =
7875 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7876
7877 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7878 QualType ObjectType;
7879 Expr::Classification ObjectClassification;
7880 if (Args.size() > 0) {
7881 if (Expr *E = Args[0]) {
7882 // Use the explicit base to restrict the lookup:
7883 ObjectType = E->getType();
7884 // Pointers in the object arguments are implicitly dereferenced, so we
7885 // always classify them as l-values.
7886 if (!ObjectType.isNull() && ObjectType->isPointerType())
7887 ObjectClassification = Expr::Classification::makeSimpleLValue();
7888 else
7889 ObjectClassification = E->Classify(Context);
7890 } // .. else there is an implicit base.
7891 FunctionArgs = Args.slice(1);
7892 }
7893 if (FunTmpl) {
7895 FunTmpl, F.getPair(),
7897 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7898 FunctionArgs, CandidateSet, SuppressUserConversions,
7899 PartialOverloading);
7900 } else {
7901 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7902 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7903 ObjectClassification, FunctionArgs, CandidateSet,
7904 SuppressUserConversions, PartialOverloading);
7905 }
7906 } else {
7907 // This branch handles both standalone functions and static methods.
7908
7909 // Slice the first argument (which is the base) when we access
7910 // static method as non-static.
7911 if (Args.size() > 0 &&
7912 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7913 !isa<CXXConstructorDecl>(FD)))) {
7914 assert(cast<CXXMethodDecl>(FD)->isStatic());
7915 FunctionArgs = Args.slice(1);
7916 }
7917 if (FunTmpl) {
7918 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7919 ExplicitTemplateArgs, FunctionArgs,
7920 CandidateSet, SuppressUserConversions,
7921 PartialOverloading);
7922 } else {
7923 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7924 SuppressUserConversions, PartialOverloading);
7925 }
7926 }
7927 }
7928}
7929
7931 Expr::Classification ObjectClassification,
7932 ArrayRef<Expr *> Args,
7933 OverloadCandidateSet &CandidateSet,
7934 bool SuppressUserConversions,
7936 NamedDecl *Decl = FoundDecl.getDecl();
7938
7940 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7941
7942 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7943 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7944 "Expected a member function template");
7945 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7946 /*ExplicitArgs*/ nullptr, ObjectType,
7947 ObjectClassification, Args, CandidateSet,
7948 SuppressUserConversions, false, PO);
7949 } else {
7950 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7951 ObjectType, ObjectClassification, Args, CandidateSet,
7952 SuppressUserConversions, false, {}, PO);
7953 }
7954}
7955
7958 CXXRecordDecl *ActingContext, QualType ObjectType,
7959 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7960 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7961 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7962 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7963 const FunctionProtoType *Proto
7964 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7965 assert(Proto && "Methods without a prototype cannot be overloaded");
7967 "Use AddOverloadCandidate for constructors");
7968
7969 if (!CandidateSet.isNewCandidate(Method, PO))
7970 return;
7971
7972 // C++11 [class.copy]p23: [DR1402]
7973 // A defaulted move assignment operator that is defined as deleted is
7974 // ignored by overload resolution.
7975 if (Method->isDefaulted() && Method->isDeleted() &&
7976 Method->isMoveAssignmentOperator())
7977 return;
7978
7979 // Overload resolution is always an unevaluated context.
7982
7983 bool IgnoreExplicitObject =
7984 (Method->isExplicitObjectMemberFunction() &&
7985 CandidateSet.getKind() ==
7987 bool ImplicitObjectMethodTreatedAsStatic =
7988 CandidateSet.getKind() ==
7990 Method->isImplicitObjectMemberFunction();
7991
7992 unsigned ExplicitOffset =
7993 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7994
7995 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7996 int(ImplicitObjectMethodTreatedAsStatic);
7997
7998 unsigned ExtraArgs =
8000 ? 0
8001 : 1;
8002
8003 // Add this candidate
8004 OverloadCandidate &Candidate =
8005 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
8006 Candidate.FoundDecl = FoundDecl;
8007 Candidate.Function = Method;
8008 Candidate.RewriteKind =
8009 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
8010 Candidate.TookAddressOfOverload =
8012 Candidate.ExplicitCallArguments = Args.size();
8013 Candidate.StrictPackMatch = StrictPackMatch;
8014
8015 // (C++ 13.3.2p2): A candidate function having fewer than m
8016 // parameters is viable only if it has an ellipsis in its parameter
8017 // list (8.3.5).
8018 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8019 !Proto->isVariadic() &&
8020 shouldEnforceArgLimit(PartialOverloading, Method)) {
8021 Candidate.Viable = false;
8023 return;
8024 }
8025
8026 // (C++ 13.3.2p2): A candidate function having more than m parameters
8027 // is viable only if the (m+1)st parameter has a default argument
8028 // (8.3.6). For the purposes of overload resolution, the
8029 // parameter list is truncated on the right, so that there are
8030 // exactly m parameters.
8031 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8032 ExplicitOffset +
8033 int(ImplicitObjectMethodTreatedAsStatic);
8034
8035 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8036 // Not enough arguments.
8037 Candidate.Viable = false;
8039 return;
8040 }
8041
8042 Candidate.Viable = true;
8043
8044 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8045 if (!IgnoreExplicitObject) {
8046 if (ObjectType.isNull())
8047 Candidate.IgnoreObjectArgument = true;
8048 else if (Method->isStatic()) {
8049 // [over.best.ics.general]p8
8050 // When the parameter is the implicit object parameter of a static member
8051 // function, the implicit conversion sequence is a standard conversion
8052 // sequence that is neither better nor worse than any other standard
8053 // conversion sequence.
8054 //
8055 // This is a rule that was introduced in C++23 to support static lambdas.
8056 // We apply it retroactively because we want to support static lambdas as
8057 // an extension and it doesn't hurt previous code.
8058 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8059 } else {
8060 // Determine the implicit conversion sequence for the object
8061 // parameter.
8062 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8063 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8064 Method, ActingContext, /*InOverloadResolution=*/true);
8065 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8066 Candidate.Viable = false;
8068 return;
8069 }
8070 }
8071 }
8072
8073 // (CUDA B.1): Check for invalid calls between targets.
8074 if (getLangOpts().CUDA)
8075 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8076 Method)) {
8077 Candidate.Viable = false;
8078 Candidate.FailureKind = ovl_fail_bad_target;
8079 return;
8080 }
8081
8082 if (Method->getTrailingRequiresClause()) {
8083 ConstraintSatisfaction Satisfaction;
8084 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8085 /*ForOverloadResolution*/ true) ||
8086 !Satisfaction.IsSatisfied) {
8087 Candidate.Viable = false;
8089 return;
8090 }
8091 }
8092
8093 // Determine the implicit conversion sequences for each of the
8094 // arguments.
8095 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8096 unsigned ConvIdx =
8097 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8098 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8099 // We already formed a conversion sequence for this parameter during
8100 // template argument deduction.
8101 } else if (ArgIdx < NumParams) {
8102 // (C++ 13.3.2p3): for F to be a viable function, there shall
8103 // exist for each argument an implicit conversion sequence
8104 // (13.3.3.1) that converts that argument to the corresponding
8105 // parameter of F.
8106 QualType ParamType;
8107 if (ImplicitObjectMethodTreatedAsStatic) {
8108 ParamType = ArgIdx == 0
8109 ? Method->getFunctionObjectParameterReferenceType()
8110 : Proto->getParamType(ArgIdx - 1);
8111 } else {
8112 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8113 }
8114 Candidate.Conversions[ConvIdx]
8115 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8116 SuppressUserConversions,
8117 /*InOverloadResolution=*/true,
8118 /*AllowObjCWritebackConversion=*/
8119 getLangOpts().ObjCAutoRefCount);
8120 if (Candidate.Conversions[ConvIdx].isBad()) {
8121 Candidate.Viable = false;
8123 return;
8124 }
8125 } else {
8126 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8127 // argument for which there is no corresponding parameter is
8128 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8129 Candidate.Conversions[ConvIdx].setEllipsis();
8130 }
8131 }
8132
8133 if (EnableIfAttr *FailedAttr =
8134 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8135 Candidate.Viable = false;
8136 Candidate.FailureKind = ovl_fail_enable_if;
8137 Candidate.DeductionFailure.Data = FailedAttr;
8138 return;
8139 }
8140
8142 Candidate.Viable = false;
8144 }
8145}
8146
8148 Sema &S, OverloadCandidateSet &CandidateSet,
8149 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8150 CXXRecordDecl *ActingContext,
8151 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8152 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8153 bool SuppressUserConversions, bool PartialOverloading,
8155
8156 // C++ [over.match.funcs]p7:
8157 // In each case where a candidate is a function template, candidate
8158 // function template specializations are generated using template argument
8159 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8160 // candidate functions in the usual way.113) A given name can refer to one
8161 // or more function templates and also to a set of overloaded non-template
8162 // functions. In such a case, the candidate functions generated from each
8163 // function template are combined with the set of non-template candidate
8164 // functions.
8165 TemplateDeductionInfo Info(CandidateSet.getLocation());
8166 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8167 FunctionDecl *Specialization = nullptr;
8168 ConversionSequenceList Conversions;
8170 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8171 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8172 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8173 CandidateSet.getKind() ==
8175 [&](ArrayRef<QualType> ParamTypes,
8176 bool OnlyInitializeNonUserDefinedConversions) {
8177 return S.CheckNonDependentConversions(
8178 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8179 Sema::CheckNonDependentConversionsFlag(
8180 SuppressUserConversions,
8181 OnlyInitializeNonUserDefinedConversions),
8182 ActingContext, ObjectType, ObjectClassification, PO);
8183 });
8185 OverloadCandidate &Candidate =
8186 CandidateSet.addCandidate(Conversions.size(), Conversions);
8187 Candidate.FoundDecl = FoundDecl;
8188 Candidate.Function = Method;
8189 Candidate.Viable = false;
8190 Candidate.RewriteKind =
8191 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8192 Candidate.IsSurrogate = false;
8193 Candidate.TookAddressOfOverload =
8194 CandidateSet.getKind() ==
8196
8197 Candidate.IgnoreObjectArgument =
8198 Method->isStatic() ||
8199 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8200 Candidate.ExplicitCallArguments = Args.size();
8203 else {
8205 Candidate.DeductionFailure =
8207 }
8208 return;
8209 }
8210
8211 // Add the function template specialization produced by template argument
8212 // deduction as a candidate.
8213 assert(Specialization && "Missing member function template specialization?");
8215 "Specialization is not a member function?");
8217 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8218 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8219 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8220}
8221
8223 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8224 CXXRecordDecl *ActingContext,
8225 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8226 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8227 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8228 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8229 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8230 return;
8231
8232 if (ExplicitTemplateArgs ||
8233 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8235 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8236 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8237 SuppressUserConversions, PartialOverloading, PO);
8238 return;
8239 }
8240
8242 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8243 Args, SuppressUserConversions, PartialOverloading, PO);
8244}
8245
8246/// Determine whether a given function template has a simple explicit specifier
8247/// or a non-value-dependent explicit-specification that evaluates to true.
8251
8256
8258 Sema &S, OverloadCandidateSet &CandidateSet,
8260 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8261 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8263 bool AggregateCandidateDeduction) {
8264
8265 // If the function template has a non-dependent explicit specification,
8266 // exclude it now if appropriate; we are not permitted to perform deduction
8267 // and substitution in this case.
8268 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8269 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8270 Candidate.FoundDecl = FoundDecl;
8271 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8272 Candidate.Viable = false;
8273 Candidate.FailureKind = ovl_fail_explicit;
8274 return;
8275 }
8276
8277 // C++ [over.match.funcs]p7:
8278 // In each case where a candidate is a function template, candidate
8279 // function template specializations are generated using template argument
8280 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8281 // candidate functions in the usual way.113) A given name can refer to one
8282 // or more function templates and also to a set of overloaded non-template
8283 // functions. In such a case, the candidate functions generated from each
8284 // function template are combined with the set of non-template candidate
8285 // functions.
8286 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8287 FunctionTemplate->getTemplateDepth());
8288 FunctionDecl *Specialization = nullptr;
8289 ConversionSequenceList Conversions;
8291 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8292 PartialOverloading, AggregateCandidateDeduction,
8293 /*PartialOrdering=*/false,
8294 /*ObjectType=*/QualType(),
8295 /*ObjectClassification=*/Expr::Classification(),
8296 CandidateSet.getKind() ==
8298 [&](ArrayRef<QualType> ParamTypes,
8299 bool OnlyInitializeNonUserDefinedConversions) {
8300 return S.CheckNonDependentConversions(
8301 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8302 Sema::CheckNonDependentConversionsFlag(
8303 SuppressUserConversions,
8304 OnlyInitializeNonUserDefinedConversions),
8305 nullptr, QualType(), {}, PO);
8306 });
8308 OverloadCandidate &Candidate =
8309 CandidateSet.addCandidate(Conversions.size(), Conversions);
8310 Candidate.FoundDecl = FoundDecl;
8311 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8312 Candidate.Viable = false;
8313 Candidate.RewriteKind =
8314 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8315 Candidate.IsSurrogate = false;
8316 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8317 // Ignore the object argument if there is one, since we don't have an object
8318 // type.
8319 Candidate.TookAddressOfOverload =
8320 CandidateSet.getKind() ==
8322
8323 Candidate.IgnoreObjectArgument =
8324 isa<CXXMethodDecl>(Candidate.Function) &&
8325 !cast<CXXMethodDecl>(Candidate.Function)
8326 ->isExplicitObjectMemberFunction() &&
8328
8329 Candidate.ExplicitCallArguments = Args.size();
8332 else {
8334 Candidate.DeductionFailure =
8336 }
8337 return;
8338 }
8339
8340 // Add the function template specialization produced by template argument
8341 // deduction as a candidate.
8342 assert(Specialization && "Missing function template specialization?");
8344 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8345 PartialOverloading, AllowExplicit,
8346 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8347 Info.AggregateDeductionCandidateHasMismatchedArity,
8348 Info.hasStrictPackMatch());
8349}
8350
8353 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8354 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8355 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8356 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8357 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8358 return;
8359
8360 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8361
8362 if (ExplicitTemplateArgs ||
8363 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8364 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8365 DependentExplicitSpecifier)) {
8366
8368 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8369 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8370 IsADLCandidate, PO, AggregateCandidateDeduction);
8371
8372 if (DependentExplicitSpecifier)
8374 return;
8375 }
8376
8377 CandidateSet.AddDeferredTemplateCandidate(
8378 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8379 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8380 AggregateCandidateDeduction);
8381}
8382
8385 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8387 CheckNonDependentConversionsFlag UserConversionFlag,
8388 CXXRecordDecl *ActingContext, QualType ObjectType,
8389 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8390 // FIXME: The cases in which we allow explicit conversions for constructor
8391 // arguments never consider calling a constructor template. It's not clear
8392 // that is correct.
8393 const bool AllowExplicit = false;
8394
8395 bool ForOverloadSetAddressResolution =
8397 auto *FD = FunctionTemplate->getTemplatedDecl();
8398 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8399 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8401 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8402
8403 if (Conversions.empty())
8404 Conversions =
8405 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8406
8407 // Overload resolution is always an unevaluated context.
8410
8411 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8412 // require that, but this check should never result in a hard error, and
8413 // overload resolution is permitted to sidestep instantiations.
8414 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8415 !ObjectType.isNull()) {
8416 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8417 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8418 !ParamTypes[0]->isDependentType()) {
8420 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8421 Method, ActingContext, /*InOverloadResolution=*/true,
8422 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8423 : QualType());
8424 if (Conversions[ConvIdx].isBad())
8425 return true;
8426 }
8427 }
8428
8429 // A speculative workaround for self-dependent constraint bugs that manifest
8430 // after CWG2369.
8431 // FIXME: Add references to the standard once P3606 is adopted.
8432 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8433 QualType ArgType) {
8434 ParamType = ParamType.getNonReferenceType();
8435 ArgType = ArgType.getNonReferenceType();
8436 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8437 if (PointerConv) {
8438 ParamType = ParamType->getPointeeType();
8439 ArgType = ArgType->getPointeeType();
8440 }
8441
8442 if (auto *RD = ParamType->getAsCXXRecordDecl();
8443 RD && RD->hasDefinition() &&
8444 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8445 auto Info = getConstructorInfo(ND);
8446 if (!Info)
8447 return false;
8448 CXXConstructorDecl *Ctor = Info.Constructor;
8449 /// isConvertingConstructor takes copy/move constructors into
8450 /// account!
8451 return !Ctor->isCopyOrMoveConstructor() &&
8453 /*AllowExplicit=*/true);
8454 }))
8455 return true;
8456 if (auto *RD = ArgType->getAsCXXRecordDecl();
8457 RD && RD->hasDefinition() &&
8458 !RD->getVisibleConversionFunctions().empty())
8459 return true;
8460
8461 return false;
8462 };
8463
8464 unsigned Offset =
8465 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8466 : 0;
8467
8468 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8469 I != N; ++I) {
8470 QualType ParamType = ParamTypes[I + Offset];
8471 if (!ParamType->isDependentType()) {
8472 unsigned ConvIdx;
8474 ConvIdx = Args.size() - 1 - I;
8475 assert(Args.size() + ThisConversions == 2 &&
8476 "number of args (including 'this') must be exactly 2 for "
8477 "reversed order");
8478 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8479 // would also be 0. 'this' got ConvIdx = 1 previously.
8480 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8481 } else {
8482 // For members, 'this' got ConvIdx = 0 previously.
8483 ConvIdx = ThisConversions + I;
8484 }
8485 if (Conversions[ConvIdx].isInitialized())
8486 continue;
8487 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8488 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8489 continue;
8491 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8492 /*InOverloadResolution=*/true,
8493 /*AllowObjCWritebackConversion=*/
8494 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8495 if (Conversions[ConvIdx].isBad())
8496 return true;
8497 }
8498 }
8499
8500 return false;
8501}
8502
8503/// Determine whether this is an allowable conversion from the result
8504/// of an explicit conversion operator to the expected type, per C++
8505/// [over.match.conv]p1 and [over.match.ref]p1.
8506///
8507/// \param ConvType The return type of the conversion function.
8508///
8509/// \param ToType The type we are converting to.
8510///
8511/// \param AllowObjCPointerConversion Allow a conversion from one
8512/// Objective-C pointer to another.
8513///
8514/// \returns true if the conversion is allowable, false otherwise.
8516 QualType ConvType, QualType ToType,
8517 bool AllowObjCPointerConversion) {
8518 QualType ToNonRefType = ToType.getNonReferenceType();
8519
8520 // Easy case: the types are the same.
8521 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8522 return true;
8523
8524 // Allow qualification conversions.
8525 bool ObjCLifetimeConversion;
8526 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8527 ObjCLifetimeConversion))
8528 return true;
8529
8530 // If we're not allowed to consider Objective-C pointer conversions,
8531 // we're done.
8532 if (!AllowObjCPointerConversion)
8533 return false;
8534
8535 // Is this an Objective-C pointer conversion?
8536 bool IncompatibleObjC = false;
8537 QualType ConvertedType;
8538 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8539 IncompatibleObjC);
8540}
8541
8543 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8544 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8545 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8546 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8547 assert(!Conversion->getDescribedFunctionTemplate() &&
8548 "Conversion function templates use AddTemplateConversionCandidate");
8549 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8550 if (!CandidateSet.isNewCandidate(Conversion))
8551 return;
8552
8553 // If the conversion function has an undeduced return type, trigger its
8554 // deduction now.
8555 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8556 if (DeduceReturnType(Conversion, From->getExprLoc()))
8557 return;
8558 ConvType = Conversion->getConversionType().getNonReferenceType();
8559 }
8560
8561 // If we don't allow any conversion of the result type, ignore conversion
8562 // functions that don't convert to exactly (possibly cv-qualified) T.
8563 if (!AllowResultConversion &&
8564 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8565 return;
8566
8567 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8568 // operator is only a candidate if its return type is the target type or
8569 // can be converted to the target type with a qualification conversion.
8570 //
8571 // FIXME: Include such functions in the candidate list and explain why we
8572 // can't select them.
8573 if (Conversion->isExplicit() &&
8574 !isAllowableExplicitConversion(*this, ConvType, ToType,
8575 AllowObjCConversionOnExplicit))
8576 return;
8577
8578 // Overload resolution is always an unevaluated context.
8581
8582 // Add this candidate
8583 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8584 Candidate.FoundDecl = FoundDecl;
8585 Candidate.Function = Conversion;
8587 Candidate.FinalConversion.setFromType(ConvType);
8588 Candidate.FinalConversion.setAllToTypes(ToType);
8589 Candidate.HasFinalConversion = true;
8590 Candidate.Viable = true;
8591 Candidate.ExplicitCallArguments = 1;
8592 Candidate.StrictPackMatch = StrictPackMatch;
8593
8594 // Explicit functions are not actually candidates at all if we're not
8595 // allowing them in this context, but keep them around so we can point
8596 // to them in diagnostics.
8597 if (!AllowExplicit && Conversion->isExplicit()) {
8598 Candidate.Viable = false;
8599 Candidate.FailureKind = ovl_fail_explicit;
8600 return;
8601 }
8602
8603 // C++ [over.match.funcs]p4:
8604 // For conversion functions, the function is considered to be a member of
8605 // the class of the implicit implied object argument for the purpose of
8606 // defining the type of the implicit object parameter.
8607 //
8608 // Determine the implicit conversion sequence for the implicit
8609 // object parameter.
8610 QualType ObjectType = From->getType();
8611 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8612 ObjectType = FromPtrType->getPointeeType();
8613 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8614 // C++23 [over.best.ics.general]
8615 // However, if the target is [...]
8616 // - the object parameter of a user-defined conversion function
8617 // [...] user-defined conversion sequences are not considered.
8619 *this, CandidateSet.getLocation(), From->getType(),
8620 From->Classify(Context), Conversion, ConversionContext,
8621 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8622 /*SuppressUserConversion*/ true);
8623
8624 if (Candidate.Conversions[0].isBad()) {
8625 Candidate.Viable = false;
8627 return;
8628 }
8629
8630 if (Conversion->getTrailingRequiresClause()) {
8631 ConstraintSatisfaction Satisfaction;
8632 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8633 !Satisfaction.IsSatisfied) {
8634 Candidate.Viable = false;
8636 return;
8637 }
8638 }
8639
8640 // We won't go through a user-defined type conversion function to convert a
8641 // derived to base as such conversions are given Conversion Rank. They only
8642 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8643 QualType FromCanon
8644 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8645 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8646 if (FromCanon == ToCanon ||
8647 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8648 Candidate.Viable = false;
8650 return;
8651 }
8652
8653 // To determine what the conversion from the result of calling the
8654 // conversion function to the type we're eventually trying to
8655 // convert to (ToType), we need to synthesize a call to the
8656 // conversion function and attempt copy initialization from it. This
8657 // makes sure that we get the right semantics with respect to
8658 // lvalues/rvalues and the type. Fortunately, we can allocate this
8659 // call on the stack and we don't need its arguments to be
8660 // well-formed.
8661 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8662 VK_LValue, From->getBeginLoc());
8664 Context.getPointerType(Conversion->getType()),
8665 CK_FunctionToPointerDecay, &ConversionRef,
8667
8668 QualType ConversionType = Conversion->getConversionType();
8669 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8670 Candidate.Viable = false;
8672 return;
8673 }
8674
8675 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8676
8677 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8678
8679 // Introduce a temporary expression with the right type and value category
8680 // that we can use for deduction purposes.
8681 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8682
8684 TryCopyInitialization(*this, &FakeCall, ToType,
8685 /*SuppressUserConversions=*/true,
8686 /*InOverloadResolution=*/false,
8687 /*AllowObjCWritebackConversion=*/false);
8688
8689 switch (ICS.getKind()) {
8691 Candidate.FinalConversion = ICS.Standard;
8692 Candidate.HasFinalConversion = true;
8693
8694 // C++ [over.ics.user]p3:
8695 // If the user-defined conversion is specified by a specialization of a
8696 // conversion function template, the second standard conversion sequence
8697 // shall have exact match rank.
8698 if (Conversion->getPrimaryTemplate() &&
8700 Candidate.Viable = false;
8702 return;
8703 }
8704
8705 // C++0x [dcl.init.ref]p5:
8706 // In the second case, if the reference is an rvalue reference and
8707 // the second standard conversion sequence of the user-defined
8708 // conversion sequence includes an lvalue-to-rvalue conversion, the
8709 // program is ill-formed.
8710 if (ToType->isRValueReferenceType() &&
8712 Candidate.Viable = false;
8714 return;
8715 }
8716 break;
8717
8719 Candidate.Viable = false;
8721 return;
8722
8723 default:
8724 llvm_unreachable(
8725 "Can only end up with a standard conversion sequence or failure");
8726 }
8727
8728 if (EnableIfAttr *FailedAttr =
8729 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8730 Candidate.Viable = false;
8731 Candidate.FailureKind = ovl_fail_enable_if;
8732 Candidate.DeductionFailure.Data = FailedAttr;
8733 return;
8734 }
8735
8736 if (isNonViableMultiVersionOverload(Conversion)) {
8737 Candidate.Viable = false;
8739 }
8740}
8741
8743 Sema &S, OverloadCandidateSet &CandidateSet,
8745 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8746 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8747 bool AllowResultConversion) {
8748
8749 // If the function template has a non-dependent explicit specification,
8750 // exclude it now if appropriate; we are not permitted to perform deduction
8751 // and substitution in this case.
8752 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8753 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8754 Candidate.FoundDecl = FoundDecl;
8755 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8756 Candidate.Viable = false;
8757 Candidate.FailureKind = ovl_fail_explicit;
8758 return;
8759 }
8760
8761 QualType ObjectType = From->getType();
8762 Expr::Classification ObjectClassification = From->Classify(S.Context);
8763
8764 TemplateDeductionInfo Info(CandidateSet.getLocation());
8767 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8768 Specialization, Info);
8770 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8771 Candidate.FoundDecl = FoundDecl;
8772 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8773 Candidate.Viable = false;
8775 Candidate.ExplicitCallArguments = 1;
8776 Candidate.DeductionFailure =
8778 return;
8779 }
8780
8781 // Add the conversion function template specialization produced by
8782 // template argument deduction as a candidate.
8783 assert(Specialization && "Missing function template specialization?");
8784 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8785 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8786 AllowExplicit, AllowResultConversion,
8787 Info.hasStrictPackMatch());
8788}
8789
8792 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8793 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8794 bool AllowExplicit, bool AllowResultConversion) {
8795 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8796 "Only conversion function templates permitted here");
8797
8798 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8799 return;
8800
8801 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8802 CandidateSet.getKind() ==
8806 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8807 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8808 AllowResultConversion);
8809
8811 return;
8812 }
8813
8815 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8816 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8817}
8818
8820 DeclAccessPair FoundDecl,
8821 CXXRecordDecl *ActingContext,
8822 const FunctionProtoType *Proto,
8823 Expr *Object,
8824 ArrayRef<Expr *> Args,
8825 OverloadCandidateSet& CandidateSet) {
8826 if (!CandidateSet.isNewCandidate(Conversion))
8827 return;
8828
8829 // Overload resolution is always an unevaluated context.
8832
8833 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8834 Candidate.FoundDecl = FoundDecl;
8835 Candidate.Function = nullptr;
8836 Candidate.Surrogate = Conversion;
8837 Candidate.IsSurrogate = true;
8838 Candidate.Viable = true;
8839 Candidate.ExplicitCallArguments = Args.size();
8840
8841 // Determine the implicit conversion sequence for the implicit
8842 // object parameter.
8843 ImplicitConversionSequence ObjectInit;
8844 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8845 ObjectInit = TryCopyInitialization(*this, Object,
8846 Conversion->getParamDecl(0)->getType(),
8847 /*SuppressUserConversions=*/false,
8848 /*InOverloadResolution=*/true, false);
8849 } else {
8851 *this, CandidateSet.getLocation(), Object->getType(),
8852 Object->Classify(Context), Conversion, ActingContext);
8853 }
8854
8855 if (ObjectInit.isBad()) {
8856 Candidate.Viable = false;
8858 Candidate.Conversions[0] = ObjectInit;
8859 return;
8860 }
8861
8862 // The first conversion is actually a user-defined conversion whose
8863 // first conversion is ObjectInit's standard conversion (which is
8864 // effectively a reference binding). Record it as such.
8865 Candidate.Conversions[0].setUserDefined();
8866 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8867 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8868 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8869 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8870 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8871 Candidate.Conversions[0].UserDefined.After
8872 = Candidate.Conversions[0].UserDefined.Before;
8873 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8874
8875 // Find the
8876 unsigned NumParams = Proto->getNumParams();
8877
8878 // (C++ 13.3.2p2): A candidate function having fewer than m
8879 // parameters is viable only if it has an ellipsis in its parameter
8880 // list (8.3.5).
8881 if (Args.size() > NumParams && !Proto->isVariadic()) {
8882 Candidate.Viable = false;
8884 return;
8885 }
8886
8887 // Function types don't have any default arguments, so just check if
8888 // we have enough arguments.
8889 if (Args.size() < NumParams) {
8890 // Not enough arguments.
8891 Candidate.Viable = false;
8893 return;
8894 }
8895
8896 // Determine the implicit conversion sequences for each of the
8897 // arguments.
8898 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8899 if (ArgIdx < NumParams) {
8900 // (C++ 13.3.2p3): for F to be a viable function, there shall
8901 // exist for each argument an implicit conversion sequence
8902 // (13.3.3.1) that converts that argument to the corresponding
8903 // parameter of F.
8904 QualType ParamType = Proto->getParamType(ArgIdx);
8905 Candidate.Conversions[ArgIdx + 1]
8906 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8907 /*SuppressUserConversions=*/false,
8908 /*InOverloadResolution=*/false,
8909 /*AllowObjCWritebackConversion=*/
8910 getLangOpts().ObjCAutoRefCount);
8911 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8912 Candidate.Viable = false;
8914 return;
8915 }
8916 } else {
8917 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8918 // argument for which there is no corresponding parameter is
8919 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8920 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8921 }
8922 }
8923
8924 if (Conversion->getTrailingRequiresClause()) {
8925 ConstraintSatisfaction Satisfaction;
8926 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8927 /*ForOverloadResolution*/ true) ||
8928 !Satisfaction.IsSatisfied) {
8929 Candidate.Viable = false;
8931 return;
8932 }
8933 }
8934
8935 if (EnableIfAttr *FailedAttr =
8936 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8937 Candidate.Viable = false;
8938 Candidate.FailureKind = ovl_fail_enable_if;
8939 Candidate.DeductionFailure.Data = FailedAttr;
8940 return;
8941 }
8942}
8943
8945 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8946 OverloadCandidateSet &CandidateSet,
8947 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8948 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8949 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8950 ArrayRef<Expr *> FunctionArgs = Args;
8951
8952 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8953 FunctionDecl *FD =
8954 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8955
8956 // Don't consider rewritten functions if we're not rewriting.
8957 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8958 continue;
8959
8960 assert(!isa<CXXMethodDecl>(FD) &&
8961 "unqualified operator lookup found a member function");
8962
8963 if (FunTmpl) {
8964 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8965 FunctionArgs, CandidateSet);
8966 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8967
8968 // As template candidates are not deduced immediately,
8969 // persist the array in the overload set.
8971 FunctionArgs[1], FunctionArgs[0]);
8972 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8973 Reversed, CandidateSet, false, false, true,
8974 ADLCallKind::NotADL,
8976 }
8977 } else {
8978 if (ExplicitTemplateArgs)
8979 continue;
8980 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8981 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8982 AddOverloadCandidate(FD, F.getPair(),
8983 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8984 false, false, true, false, ADLCallKind::NotADL, {},
8986 }
8987 }
8988}
8989
8991 SourceLocation OpLoc,
8992 ArrayRef<Expr *> Args,
8993 OverloadCandidateSet &CandidateSet,
8995 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8996
8997 // C++ [over.match.oper]p3:
8998 // For a unary operator @ with an operand of a type whose
8999 // cv-unqualified version is T1, and for a binary operator @ with
9000 // a left operand of a type whose cv-unqualified version is T1 and
9001 // a right operand of a type whose cv-unqualified version is T2,
9002 // three sets of candidate functions, designated member
9003 // candidates, non-member candidates and built-in candidates, are
9004 // constructed as follows:
9005 QualType T1 = Args[0]->getType();
9006
9007 // -- If T1 is a complete class type or a class currently being
9008 // defined, the set of member candidates is the result of the
9009 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9010 // the set of member candidates is empty.
9011 if (T1->isRecordType()) {
9012 bool IsComplete = isCompleteType(OpLoc, T1);
9013 auto *T1RD = T1->getAsCXXRecordDecl();
9014 // Complete the type if it can be completed.
9015 // If the type is neither complete nor being defined, bail out now.
9016 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9017 return;
9018
9019 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9020 LookupQualifiedName(Operators, T1RD);
9021 Operators.suppressAccessDiagnostics();
9022
9023 for (LookupResult::iterator Oper = Operators.begin(),
9024 OperEnd = Operators.end();
9025 Oper != OperEnd; ++Oper) {
9026 if (Oper->getAsFunction() &&
9028 !CandidateSet.getRewriteInfo().shouldAddReversed(
9029 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9030 continue;
9031 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9032 Args[0]->Classify(Context), Args.slice(1),
9033 CandidateSet, /*SuppressUserConversion=*/false, PO);
9034 }
9035 }
9036}
9037
9039 OverloadCandidateSet& CandidateSet,
9040 bool IsAssignmentOperator,
9041 unsigned NumContextualBoolArguments) {
9042 // Overload resolution is always an unevaluated context.
9045
9046 // Add this candidate
9047 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9048 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9049 Candidate.Function = nullptr;
9050 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9051
9052 // Determine the implicit conversion sequences for each of the
9053 // arguments.
9054 Candidate.Viable = true;
9055 Candidate.ExplicitCallArguments = Args.size();
9056 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9057 // C++ [over.match.oper]p4:
9058 // For the built-in assignment operators, conversions of the
9059 // left operand are restricted as follows:
9060 // -- no temporaries are introduced to hold the left operand, and
9061 // -- no user-defined conversions are applied to the left
9062 // operand to achieve a type match with the left-most
9063 // parameter of a built-in candidate.
9064 //
9065 // We block these conversions by turning off user-defined
9066 // conversions, since that is the only way that initialization of
9067 // a reference to a non-class type can occur from something that
9068 // is not of the same type.
9069 if (ArgIdx < NumContextualBoolArguments) {
9070 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9071 "Contextual conversion to bool requires bool type");
9072 Candidate.Conversions[ArgIdx]
9073 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9074 } else {
9075 Candidate.Conversions[ArgIdx]
9076 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9077 ArgIdx == 0 && IsAssignmentOperator,
9078 /*InOverloadResolution=*/false,
9079 /*AllowObjCWritebackConversion=*/
9080 getLangOpts().ObjCAutoRefCount);
9081 }
9082 if (Candidate.Conversions[ArgIdx].isBad()) {
9083 Candidate.Viable = false;
9085 break;
9086 }
9087 }
9088}
9089
9090namespace {
9091
9092/// BuiltinCandidateTypeSet - A set of types that will be used for the
9093/// candidate operator functions for built-in operators (C++
9094/// [over.built]). The types are separated into pointer types and
9095/// enumeration types.
9096class BuiltinCandidateTypeSet {
9097 /// TypeSet - A set of types.
9098 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9099
9100 /// PointerTypes - The set of pointer types that will be used in the
9101 /// built-in candidates.
9102 TypeSet PointerTypes;
9103
9104 /// MemberPointerTypes - The set of member pointer types that will be
9105 /// used in the built-in candidates.
9106 TypeSet MemberPointerTypes;
9107
9108 /// EnumerationTypes - The set of enumeration types that will be
9109 /// used in the built-in candidates.
9110 TypeSet EnumerationTypes;
9111
9112 /// The set of vector types that will be used in the built-in
9113 /// candidates.
9114 TypeSet VectorTypes;
9115
9116 /// The set of matrix types that will be used in the built-in
9117 /// candidates.
9118 TypeSet MatrixTypes;
9119
9120 /// The set of _BitInt types that will be used in the built-in candidates.
9121 TypeSet BitIntTypes;
9122
9123 /// A flag indicating non-record types are viable candidates
9124 bool HasNonRecordTypes;
9125
9126 /// A flag indicating whether either arithmetic or enumeration types
9127 /// were present in the candidate set.
9128 bool HasArithmeticOrEnumeralTypes;
9129
9130 /// A flag indicating whether the nullptr type was present in the
9131 /// candidate set.
9132 bool HasNullPtrType;
9133
9134 /// Sema - The semantic analysis instance where we are building the
9135 /// candidate type set.
9136 Sema &SemaRef;
9137
9138 /// Context - The AST context in which we will build the type sets.
9139 ASTContext &Context;
9140
9141 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9142 const Qualifiers &VisibleQuals);
9143 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9144
9145public:
9146 /// iterator - Iterates through the types that are part of the set.
9147 typedef TypeSet::iterator iterator;
9148
9149 BuiltinCandidateTypeSet(Sema &SemaRef)
9150 : HasNonRecordTypes(false),
9151 HasArithmeticOrEnumeralTypes(false),
9152 HasNullPtrType(false),
9153 SemaRef(SemaRef),
9154 Context(SemaRef.Context) { }
9155
9156 void AddTypesConvertedFrom(QualType Ty,
9157 SourceLocation Loc,
9158 bool AllowUserConversions,
9159 bool AllowExplicitConversions,
9160 const Qualifiers &VisibleTypeConversionsQuals);
9161
9162 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9163 llvm::iterator_range<iterator> member_pointer_types() {
9164 return MemberPointerTypes;
9165 }
9166 llvm::iterator_range<iterator> enumeration_types() {
9167 return EnumerationTypes;
9168 }
9169 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9170 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9171 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9172
9173 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9174 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9175 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9176 bool hasNullPtrType() const { return HasNullPtrType; }
9177};
9178
9179} // end anonymous namespace
9180
9181/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9182/// the set of pointer types along with any more-qualified variants of
9183/// that type. For example, if @p Ty is "int const *", this routine
9184/// will add "int const *", "int const volatile *", "int const
9185/// restrict *", and "int const volatile restrict *" to the set of
9186/// pointer types. Returns true if the add of @p Ty itself succeeded,
9187/// false otherwise.
9188///
9189/// FIXME: what to do about extended qualifiers?
9190bool
9191BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9192 const Qualifiers &VisibleQuals) {
9193
9194 // Insert this type.
9195 if (!PointerTypes.insert(Ty))
9196 return false;
9197
9198 QualType PointeeTy;
9199 const PointerType *PointerTy = Ty->getAs<PointerType>();
9200 bool buildObjCPtr = false;
9201 if (!PointerTy) {
9202 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9203 PointeeTy = PTy->getPointeeType();
9204 buildObjCPtr = true;
9205 } else {
9206 PointeeTy = PointerTy->getPointeeType();
9207 }
9208
9209 // Don't add qualified variants of arrays. For one, they're not allowed
9210 // (the qualifier would sink to the element type), and for another, the
9211 // only overload situation where it matters is subscript or pointer +- int,
9212 // and those shouldn't have qualifier variants anyway.
9213 if (PointeeTy->isArrayType())
9214 return true;
9215
9216 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9217 bool hasVolatile = VisibleQuals.hasVolatile();
9218 bool hasRestrict = VisibleQuals.hasRestrict();
9219
9220 // Iterate through all strict supersets of BaseCVR.
9221 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9222 if ((CVR | BaseCVR) != CVR) continue;
9223 // Skip over volatile if no volatile found anywhere in the types.
9224 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9225
9226 // Skip over restrict if no restrict found anywhere in the types, or if
9227 // the type cannot be restrict-qualified.
9228 if ((CVR & Qualifiers::Restrict) &&
9229 (!hasRestrict ||
9230 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9231 continue;
9232
9233 // Build qualified pointee type.
9234 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9235
9236 // Build qualified pointer type.
9237 QualType QPointerTy;
9238 if (!buildObjCPtr)
9239 QPointerTy = Context.getPointerType(QPointeeTy);
9240 else
9241 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9242
9243 // Insert qualified pointer type.
9244 PointerTypes.insert(QPointerTy);
9245 }
9246
9247 return true;
9248}
9249
9250/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9251/// to the set of pointer types along with any more-qualified variants of
9252/// that type. For example, if @p Ty is "int const *", this routine
9253/// will add "int const *", "int const volatile *", "int const
9254/// restrict *", and "int const volatile restrict *" to the set of
9255/// pointer types. Returns true if the add of @p Ty itself succeeded,
9256/// false otherwise.
9257///
9258/// FIXME: what to do about extended qualifiers?
9259bool
9260BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9261 QualType Ty) {
9262 // Insert this type.
9263 if (!MemberPointerTypes.insert(Ty))
9264 return false;
9265
9266 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9267 assert(PointerTy && "type was not a member pointer type!");
9268
9269 QualType PointeeTy = PointerTy->getPointeeType();
9270 // Don't add qualified variants of arrays. For one, they're not allowed
9271 // (the qualifier would sink to the element type), and for another, the
9272 // only overload situation where it matters is subscript or pointer +- int,
9273 // and those shouldn't have qualifier variants anyway.
9274 if (PointeeTy->isArrayType())
9275 return true;
9276 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9277
9278 // Iterate through all strict supersets of the pointee type's CVR
9279 // qualifiers.
9280 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9281 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9282 if ((CVR | BaseCVR) != CVR) continue;
9283
9284 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9285 MemberPointerTypes.insert(Context.getMemberPointerType(
9286 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9287 }
9288
9289 return true;
9290}
9291
9292/// AddTypesConvertedFrom - Add each of the types to which the type @p
9293/// Ty can be implicit converted to the given set of @p Types. We're
9294/// primarily interested in pointer types and enumeration types. We also
9295/// take member pointer types, for the conditional operator.
9296/// AllowUserConversions is true if we should look at the conversion
9297/// functions of a class type, and AllowExplicitConversions if we
9298/// should also include the explicit conversion functions of a class
9299/// type.
9300void
9301BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9302 SourceLocation Loc,
9303 bool AllowUserConversions,
9304 bool AllowExplicitConversions,
9305 const Qualifiers &VisibleQuals) {
9306 // Only deal with canonical types.
9307 Ty = Context.getCanonicalType(Ty);
9308
9309 // Look through reference types; they aren't part of the type of an
9310 // expression for the purposes of conversions.
9311 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9312 Ty = RefTy->getPointeeType();
9313
9314 // If we're dealing with an array type, decay to the pointer.
9315 if (Ty->isArrayType())
9316 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9317
9318 // Otherwise, we don't care about qualifiers on the type.
9319 Ty = Ty.getLocalUnqualifiedType();
9320
9321 // Flag if we ever add a non-record type.
9322 bool TyIsRec = Ty->isRecordType();
9323 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9324
9325 // Flag if we encounter an arithmetic type.
9326 HasArithmeticOrEnumeralTypes =
9327 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9328
9329 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9330 PointerTypes.insert(Ty);
9331 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9332 // Insert our type, and its more-qualified variants, into the set
9333 // of types.
9334 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9335 return;
9336 } else if (Ty->isMemberPointerType()) {
9337 // Member pointers are far easier, since the pointee can't be converted.
9338 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9339 return;
9340 } else if (Ty->isEnumeralType()) {
9341 HasArithmeticOrEnumeralTypes = true;
9342 EnumerationTypes.insert(Ty);
9343 } else if (Ty->isBitIntType()) {
9344 HasArithmeticOrEnumeralTypes = true;
9345 BitIntTypes.insert(Ty);
9346 } else if (Ty->isVectorType()) {
9347 // We treat vector types as arithmetic types in many contexts as an
9348 // extension.
9349 HasArithmeticOrEnumeralTypes = true;
9350 VectorTypes.insert(Ty);
9351 } else if (Ty->isMatrixType()) {
9352 // Similar to vector types, we treat vector types as arithmetic types in
9353 // many contexts as an extension.
9354 HasArithmeticOrEnumeralTypes = true;
9355 MatrixTypes.insert(Ty);
9356 } else if (Ty->isNullPtrType()) {
9357 HasNullPtrType = true;
9358 } else if (AllowUserConversions && TyIsRec) {
9359 // No conversion functions in incomplete types.
9360 if (!SemaRef.isCompleteType(Loc, Ty))
9361 return;
9362
9363 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9364 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9365 if (isa<UsingShadowDecl>(D))
9366 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9367
9368 // Skip conversion function templates; they don't tell us anything
9369 // about which builtin types we can convert to.
9371 continue;
9372
9373 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9374 if (AllowExplicitConversions || !Conv->isExplicit()) {
9375 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9376 VisibleQuals);
9377 }
9378 }
9379 }
9380}
9381/// Helper function for adjusting address spaces for the pointer or reference
9382/// operands of builtin operators depending on the argument.
9387
9388/// Helper function for AddBuiltinOperatorCandidates() that adds
9389/// the volatile- and non-volatile-qualified assignment operators for the
9390/// given type to the candidate set.
9392 QualType T,
9393 ArrayRef<Expr *> Args,
9394 OverloadCandidateSet &CandidateSet) {
9395 QualType ParamTypes[2];
9396
9397 // T& operator=(T&, T)
9398 ParamTypes[0] = S.Context.getLValueReferenceType(
9400 ParamTypes[1] = T;
9401 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9402 /*IsAssignmentOperator=*/true);
9403
9405 // volatile T& operator=(volatile T&, T)
9406 ParamTypes[0] = S.Context.getLValueReferenceType(
9408 Args[0]));
9409 ParamTypes[1] = T;
9410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9411 /*IsAssignmentOperator=*/true);
9412 }
9413}
9414
9415/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9416/// if any, found in visible type conversion functions found in ArgExpr's type.
9417static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9418 Qualifiers VRQuals;
9419 CXXRecordDecl *ClassDecl;
9420 if (const MemberPointerType *RHSMPType =
9421 ArgExpr->getType()->getAs<MemberPointerType>())
9422 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9423 else
9424 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9425 if (!ClassDecl) {
9426 // Just to be safe, assume the worst case.
9427 VRQuals.addVolatile();
9428 VRQuals.addRestrict();
9429 return VRQuals;
9430 }
9431 if (!ClassDecl->hasDefinition())
9432 return VRQuals;
9433
9434 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9435 if (isa<UsingShadowDecl>(D))
9436 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9437 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9438 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9439 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9440 CanTy = ResTypeRef->getPointeeType();
9441 // Need to go down the pointer/mempointer chain and add qualifiers
9442 // as see them.
9443 bool done = false;
9444 while (!done) {
9445 if (CanTy.isRestrictQualified())
9446 VRQuals.addRestrict();
9447 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9448 CanTy = ResTypePtr->getPointeeType();
9449 else if (const MemberPointerType *ResTypeMPtr =
9450 CanTy->getAs<MemberPointerType>())
9451 CanTy = ResTypeMPtr->getPointeeType();
9452 else
9453 done = true;
9454 if (CanTy.isVolatileQualified())
9455 VRQuals.addVolatile();
9456 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9457 return VRQuals;
9458 }
9459 }
9460 }
9461 return VRQuals;
9462}
9463
9464// Note: We're currently only handling qualifiers that are meaningful for the
9465// LHS of compound assignment overloading.
9467 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9468 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9469 // _Atomic
9470 if (Available.hasAtomic()) {
9471 Available.removeAtomic();
9472 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9473 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9474 return;
9475 }
9476
9477 // volatile
9478 if (Available.hasVolatile()) {
9479 Available.removeVolatile();
9480 assert(!Applied.hasVolatile());
9481 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9482 Callback);
9483 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9484 return;
9485 }
9486
9487 Callback(Applied);
9488}
9489
9491 QualifiersAndAtomic Quals,
9492 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9494 Callback);
9495}
9496
9498 QualifiersAndAtomic Quals,
9499 Sema &S) {
9500 if (Quals.hasAtomic())
9502 if (Quals.hasVolatile())
9505}
9506
9507namespace {
9508
9509/// Helper class to manage the addition of builtin operator overload
9510/// candidates. It provides shared state and utility methods used throughout
9511/// the process, as well as a helper method to add each group of builtin
9512/// operator overloads from the standard to a candidate set.
9513class BuiltinOperatorOverloadBuilder {
9514 // Common instance state available to all overload candidate addition methods.
9515 Sema &S;
9516 ArrayRef<Expr *> Args;
9517 QualifiersAndAtomic VisibleTypeConversionsQuals;
9518 bool HasArithmeticOrEnumeralCandidateType;
9519 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9520 OverloadCandidateSet &CandidateSet;
9521
9522 static constexpr int ArithmeticTypesCap = 26;
9523 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9524
9525 // Define some indices used to iterate over the arithmetic types in
9526 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9527 // types are that preserved by promotion (C++ [over.built]p2).
9528 unsigned FirstIntegralType,
9529 LastIntegralType;
9530 unsigned FirstPromotedIntegralType,
9531 LastPromotedIntegralType;
9532 unsigned FirstPromotedArithmeticType,
9533 LastPromotedArithmeticType;
9534 unsigned NumArithmeticTypes;
9535
9536 void InitArithmeticTypes() {
9537 // Start of promoted types.
9538 FirstPromotedArithmeticType = 0;
9539 ArithmeticTypes.push_back(S.Context.FloatTy);
9540 ArithmeticTypes.push_back(S.Context.DoubleTy);
9541 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9543 ArithmeticTypes.push_back(S.Context.Float128Ty);
9545 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9546
9547 // Start of integral types.
9548 FirstIntegralType = ArithmeticTypes.size();
9549 FirstPromotedIntegralType = ArithmeticTypes.size();
9550 ArithmeticTypes.push_back(S.Context.IntTy);
9551 ArithmeticTypes.push_back(S.Context.LongTy);
9552 ArithmeticTypes.push_back(S.Context.LongLongTy);
9556 ArithmeticTypes.push_back(S.Context.Int128Ty);
9557 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9558 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9559 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9563 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9564
9565 /// We add candidates for the unique, unqualified _BitInt types present in
9566 /// the candidate type set. The candidate set already handled ensuring the
9567 /// type is unqualified and canonical, but because we're adding from N
9568 /// different sets, we need to do some extra work to unique things. Insert
9569 /// the candidates into a unique set, then move from that set into the list
9570 /// of arithmetic types.
9571 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9572 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9573 for (QualType BitTy : Candidate.bitint_types())
9574 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9575 }
9576 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9577 LastPromotedIntegralType = ArithmeticTypes.size();
9578 LastPromotedArithmeticType = ArithmeticTypes.size();
9579 // End of promoted types.
9580
9581 ArithmeticTypes.push_back(S.Context.BoolTy);
9582 ArithmeticTypes.push_back(S.Context.CharTy);
9583 ArithmeticTypes.push_back(S.Context.WCharTy);
9584 if (S.Context.getLangOpts().Char8)
9585 ArithmeticTypes.push_back(S.Context.Char8Ty);
9586 ArithmeticTypes.push_back(S.Context.Char16Ty);
9587 ArithmeticTypes.push_back(S.Context.Char32Ty);
9588 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9589 ArithmeticTypes.push_back(S.Context.ShortTy);
9590 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9591 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9592 LastIntegralType = ArithmeticTypes.size();
9593 NumArithmeticTypes = ArithmeticTypes.size();
9594 // End of integral types.
9595 // FIXME: What about complex? What about half?
9596
9597 // We don't know for sure how many bit-precise candidates were involved, so
9598 // we subtract those from the total when testing whether we're under the
9599 // cap or not.
9600 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9601 ArithmeticTypesCap &&
9602 "Enough inline storage for all arithmetic types.");
9603 }
9604
9605 /// Helper method to factor out the common pattern of adding overloads
9606 /// for '++' and '--' builtin operators.
9607 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9608 bool HasVolatile,
9609 bool HasRestrict) {
9610 QualType ParamTypes[2] = {
9611 S.Context.getLValueReferenceType(CandidateTy),
9612 S.Context.IntTy
9613 };
9614
9615 // Non-volatile version.
9616 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9617
9618 // Use a heuristic to reduce number of builtin candidates in the set:
9619 // add volatile version only if there are conversions to a volatile type.
9620 if (HasVolatile) {
9621 ParamTypes[0] =
9623 S.Context.getVolatileType(CandidateTy));
9624 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9625 }
9626
9627 // Add restrict version only if there are conversions to a restrict type
9628 // and our candidate type is a non-restrict-qualified pointer.
9629 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9630 !CandidateTy.isRestrictQualified()) {
9631 ParamTypes[0]
9634 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9635
9636 if (HasVolatile) {
9637 ParamTypes[0]
9639 S.Context.getCVRQualifiedType(CandidateTy,
9642 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9643 }
9644 }
9645
9646 }
9647
9648 /// Helper to add an overload candidate for a binary builtin with types \p L
9649 /// and \p R.
9650 void AddCandidate(QualType L, QualType R) {
9651 QualType LandR[2] = {L, R};
9652 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9653 }
9654
9655public:
9656 BuiltinOperatorOverloadBuilder(
9657 Sema &S, ArrayRef<Expr *> Args,
9658 QualifiersAndAtomic VisibleTypeConversionsQuals,
9659 bool HasArithmeticOrEnumeralCandidateType,
9660 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9661 OverloadCandidateSet &CandidateSet)
9662 : S(S), Args(Args),
9663 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9664 HasArithmeticOrEnumeralCandidateType(
9665 HasArithmeticOrEnumeralCandidateType),
9666 CandidateTypes(CandidateTypes),
9667 CandidateSet(CandidateSet) {
9668
9669 InitArithmeticTypes();
9670 }
9671
9672 // Increment is deprecated for bool since C++17.
9673 //
9674 // C++ [over.built]p3:
9675 //
9676 // For every pair (T, VQ), where T is an arithmetic type other
9677 // than bool, and VQ is either volatile or empty, there exist
9678 // candidate operator functions of the form
9679 //
9680 // VQ T& operator++(VQ T&);
9681 // T operator++(VQ T&, int);
9682 //
9683 // C++ [over.built]p4:
9684 //
9685 // For every pair (T, VQ), where T is an arithmetic type other
9686 // than bool, and VQ is either volatile or empty, there exist
9687 // candidate operator functions of the form
9688 //
9689 // VQ T& operator--(VQ T&);
9690 // T operator--(VQ T&, int);
9691 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9692 if (!HasArithmeticOrEnumeralCandidateType)
9693 return;
9694
9695 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9696 const auto TypeOfT = ArithmeticTypes[Arith];
9697 if (TypeOfT == S.Context.BoolTy) {
9698 if (Op == OO_MinusMinus)
9699 continue;
9700 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9701 continue;
9702 }
9703 addPlusPlusMinusMinusStyleOverloads(
9704 TypeOfT,
9705 VisibleTypeConversionsQuals.hasVolatile(),
9706 VisibleTypeConversionsQuals.hasRestrict());
9707 }
9708 }
9709
9710 // C++ [over.built]p5:
9711 //
9712 // For every pair (T, VQ), where T is a cv-qualified or
9713 // cv-unqualified object type, and VQ is either volatile or
9714 // empty, there exist candidate operator functions of the form
9715 //
9716 // T*VQ& operator++(T*VQ&);
9717 // T*VQ& operator--(T*VQ&);
9718 // T* operator++(T*VQ&, int);
9719 // T* operator--(T*VQ&, int);
9720 void addPlusPlusMinusMinusPointerOverloads() {
9721 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9722 // Skip pointer types that aren't pointers to object types.
9723 if (!PtrTy->getPointeeType()->isObjectType())
9724 continue;
9725
9726 addPlusPlusMinusMinusStyleOverloads(
9727 PtrTy,
9728 (!PtrTy.isVolatileQualified() &&
9729 VisibleTypeConversionsQuals.hasVolatile()),
9730 (!PtrTy.isRestrictQualified() &&
9731 VisibleTypeConversionsQuals.hasRestrict()));
9732 }
9733 }
9734
9735 // C++ [over.built]p6:
9736 // For every cv-qualified or cv-unqualified object type T, there
9737 // exist candidate operator functions of the form
9738 //
9739 // T& operator*(T*);
9740 //
9741 // C++ [over.built]p7:
9742 // For every function type T that does not have cv-qualifiers or a
9743 // ref-qualifier, there exist candidate operator functions of the form
9744 // T& operator*(T*);
9745 void addUnaryStarPointerOverloads() {
9746 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9747 QualType PointeeTy = ParamTy->getPointeeType();
9748 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9749 continue;
9750
9751 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9752 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9753 continue;
9754
9755 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9756 }
9757 }
9758
9759 // C++ [over.built]p9:
9760 // For every promoted arithmetic type T, there exist candidate
9761 // operator functions of the form
9762 //
9763 // T operator+(T);
9764 // T operator-(T);
9765 void addUnaryPlusOrMinusArithmeticOverloads() {
9766 if (!HasArithmeticOrEnumeralCandidateType)
9767 return;
9768
9769 for (unsigned Arith = FirstPromotedArithmeticType;
9770 Arith < LastPromotedArithmeticType; ++Arith) {
9771 QualType ArithTy = ArithmeticTypes[Arith];
9772 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9773 }
9774
9775 // Extension: We also add these operators for vector types.
9776 for (QualType VecTy : CandidateTypes[0].vector_types())
9777 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9778 }
9779
9780 // C++ [over.built]p8:
9781 // For every type T, there exist candidate operator functions of
9782 // the form
9783 //
9784 // T* operator+(T*);
9785 void addUnaryPlusPointerOverloads() {
9786 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9787 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9788 }
9789
9790 // C++ [over.built]p10:
9791 // For every promoted integral type T, there exist candidate
9792 // operator functions of the form
9793 //
9794 // T operator~(T);
9795 void addUnaryTildePromotedIntegralOverloads() {
9796 if (!HasArithmeticOrEnumeralCandidateType)
9797 return;
9798
9799 for (unsigned Int = FirstPromotedIntegralType;
9800 Int < LastPromotedIntegralType; ++Int) {
9801 QualType IntTy = ArithmeticTypes[Int];
9802 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9803 }
9804
9805 // Extension: We also add this operator for vector types.
9806 for (QualType VecTy : CandidateTypes[0].vector_types())
9807 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9808 }
9809
9810 // C++ [over.match.oper]p16:
9811 // For every pointer to member type T or type std::nullptr_t, there
9812 // exist candidate operator functions of the form
9813 //
9814 // bool operator==(T,T);
9815 // bool operator!=(T,T);
9816 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9817 /// Set of (canonical) types that we've already handled.
9818 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9819
9820 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9821 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9822 // Don't add the same builtin candidate twice.
9823 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9824 continue;
9825
9826 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9827 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9828 }
9829
9830 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9832 if (AddedTypes.insert(NullPtrTy).second) {
9833 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9834 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9835 }
9836 }
9837 }
9838 }
9839
9840 // C++ [over.built]p15:
9841 //
9842 // For every T, where T is an enumeration type or a pointer type,
9843 // there exist candidate operator functions of the form
9844 //
9845 // bool operator<(T, T);
9846 // bool operator>(T, T);
9847 // bool operator<=(T, T);
9848 // bool operator>=(T, T);
9849 // bool operator==(T, T);
9850 // bool operator!=(T, T);
9851 // R operator<=>(T, T)
9852 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9853 // C++ [over.match.oper]p3:
9854 // [...]the built-in candidates include all of the candidate operator
9855 // functions defined in 13.6 that, compared to the given operator, [...]
9856 // do not have the same parameter-type-list as any non-template non-member
9857 // candidate.
9858 //
9859 // Note that in practice, this only affects enumeration types because there
9860 // aren't any built-in candidates of record type, and a user-defined operator
9861 // must have an operand of record or enumeration type. Also, the only other
9862 // overloaded operator with enumeration arguments, operator=,
9863 // cannot be overloaded for enumeration types, so this is the only place
9864 // where we must suppress candidates like this.
9865 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9866 UserDefinedBinaryOperators;
9867
9868 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9869 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9870 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9871 CEnd = CandidateSet.end();
9872 C != CEnd; ++C) {
9873 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9874 continue;
9875
9876 if (C->Function->isFunctionTemplateSpecialization())
9877 continue;
9878
9879 // We interpret "same parameter-type-list" as applying to the
9880 // "synthesized candidate, with the order of the two parameters
9881 // reversed", not to the original function.
9882 bool Reversed = C->isReversed();
9883 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9884 ->getType()
9885 .getUnqualifiedType();
9886 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9887 ->getType()
9888 .getUnqualifiedType();
9889
9890 // Skip if either parameter isn't of enumeral type.
9891 if (!FirstParamType->isEnumeralType() ||
9892 !SecondParamType->isEnumeralType())
9893 continue;
9894
9895 // Add this operator to the set of known user-defined operators.
9896 UserDefinedBinaryOperators.insert(
9897 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9898 S.Context.getCanonicalType(SecondParamType)));
9899 }
9900 }
9901 }
9902
9903 /// Set of (canonical) types that we've already handled.
9904 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9905
9906 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9907 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9908 // Don't add the same builtin candidate twice.
9909 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9910 continue;
9911 if (IsSpaceship && PtrTy->isFunctionPointerType())
9912 continue;
9913
9914 QualType ParamTypes[2] = {PtrTy, PtrTy};
9915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9916 }
9917 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9918 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9919
9920 // Don't add the same builtin candidate twice, or if a user defined
9921 // candidate exists.
9922 if (!AddedTypes.insert(CanonType).second ||
9923 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9924 CanonType)))
9925 continue;
9926 QualType ParamTypes[2] = {EnumTy, EnumTy};
9927 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9928 }
9929 }
9930 }
9931
9932 // C++ [over.built]p13:
9933 //
9934 // For every cv-qualified or cv-unqualified object type T
9935 // there exist candidate operator functions of the form
9936 //
9937 // T* operator+(T*, ptrdiff_t);
9938 // T& operator[](T*, ptrdiff_t); [BELOW]
9939 // T* operator-(T*, ptrdiff_t);
9940 // T* operator+(ptrdiff_t, T*);
9941 // T& operator[](ptrdiff_t, T*); [BELOW]
9942 //
9943 // C++ [over.built]p14:
9944 //
9945 // For every T, where T is a pointer to object type, there
9946 // exist candidate operator functions of the form
9947 //
9948 // ptrdiff_t operator-(T, T);
9949 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9950 /// Set of (canonical) types that we've already handled.
9951 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9952
9953 for (int Arg = 0; Arg < 2; ++Arg) {
9954 QualType AsymmetricParamTypes[2] = {
9957 };
9958 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9959 QualType PointeeTy = PtrTy->getPointeeType();
9960 if (!PointeeTy->isObjectType())
9961 continue;
9962
9963 AsymmetricParamTypes[Arg] = PtrTy;
9964 if (Arg == 0 || Op == OO_Plus) {
9965 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9966 // T* operator+(ptrdiff_t, T*);
9967 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9968 }
9969 if (Op == OO_Minus) {
9970 // ptrdiff_t operator-(T, T);
9971 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9972 continue;
9973
9974 QualType ParamTypes[2] = {PtrTy, PtrTy};
9975 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9976 }
9977 }
9978 }
9979 }
9980
9981 // C++ [over.built]p12:
9982 //
9983 // For every pair of promoted arithmetic types L and R, there
9984 // exist candidate operator functions of the form
9985 //
9986 // LR operator*(L, R);
9987 // LR operator/(L, R);
9988 // LR operator+(L, R);
9989 // LR operator-(L, R);
9990 // bool operator<(L, R);
9991 // bool operator>(L, R);
9992 // bool operator<=(L, R);
9993 // bool operator>=(L, R);
9994 // bool operator==(L, R);
9995 // bool operator!=(L, R);
9996 //
9997 // where LR is the result of the usual arithmetic conversions
9998 // between types L and R.
9999 //
10000 // C++ [over.built]p24:
10001 //
10002 // For every pair of promoted arithmetic types L and R, there exist
10003 // candidate operator functions of the form
10004 //
10005 // LR operator?(bool, L, R);
10006 //
10007 // where LR is the result of the usual arithmetic conversions
10008 // between types L and R.
10009 // Our candidates ignore the first parameter.
10010 void addGenericBinaryArithmeticOverloads() {
10011 if (!HasArithmeticOrEnumeralCandidateType)
10012 return;
10013
10014 for (unsigned Left = FirstPromotedArithmeticType;
10015 Left < LastPromotedArithmeticType; ++Left) {
10016 for (unsigned Right = FirstPromotedArithmeticType;
10017 Right < LastPromotedArithmeticType; ++Right) {
10018 QualType LandR[2] = { ArithmeticTypes[Left],
10019 ArithmeticTypes[Right] };
10020 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10021 }
10022 }
10023
10024 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10025 // conditional operator for vector types.
10026 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10027 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10028 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10029 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10030 }
10031 }
10032
10033 /// Add binary operator overloads for each candidate matrix type M1, M2:
10034 /// * (M1, M1) -> M1
10035 /// * (M1, M1.getElementType()) -> M1
10036 /// * (M2.getElementType(), M2) -> M2
10037 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10038 void addMatrixBinaryArithmeticOverloads() {
10039 if (!HasArithmeticOrEnumeralCandidateType)
10040 return;
10041
10042 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10043 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10044 AddCandidate(M1, M1);
10045 }
10046
10047 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10048 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10049 if (!CandidateTypes[0].containsMatrixType(M2))
10050 AddCandidate(M2, M2);
10051 }
10052 }
10053
10054 // C++2a [over.built]p14:
10055 //
10056 // For every integral type T there exists a candidate operator function
10057 // of the form
10058 //
10059 // std::strong_ordering operator<=>(T, T)
10060 //
10061 // C++2a [over.built]p15:
10062 //
10063 // For every pair of floating-point types L and R, there exists a candidate
10064 // operator function of the form
10065 //
10066 // std::partial_ordering operator<=>(L, R);
10067 //
10068 // FIXME: The current specification for integral types doesn't play nice with
10069 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10070 // comparisons. Under the current spec this can lead to ambiguity during
10071 // overload resolution. For example:
10072 //
10073 // enum A : int {a};
10074 // auto x = (a <=> (long)42);
10075 //
10076 // error: call is ambiguous for arguments 'A' and 'long'.
10077 // note: candidate operator<=>(int, int)
10078 // note: candidate operator<=>(long, long)
10079 //
10080 // To avoid this error, this function deviates from the specification and adds
10081 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10082 // arithmetic types (the same as the generic relational overloads).
10083 //
10084 // For now this function acts as a placeholder.
10085 void addThreeWayArithmeticOverloads() {
10086 addGenericBinaryArithmeticOverloads();
10087 }
10088
10089 // C++ [over.built]p17:
10090 //
10091 // For every pair of promoted integral types L and R, there
10092 // exist candidate operator functions of the form
10093 //
10094 // LR operator%(L, R);
10095 // LR operator&(L, R);
10096 // LR operator^(L, R);
10097 // LR operator|(L, R);
10098 // L operator<<(L, R);
10099 // L operator>>(L, R);
10100 //
10101 // where LR is the result of the usual arithmetic conversions
10102 // between types L and R.
10103 void addBinaryBitwiseArithmeticOverloads() {
10104 if (!HasArithmeticOrEnumeralCandidateType)
10105 return;
10106
10107 for (unsigned Left = FirstPromotedIntegralType;
10108 Left < LastPromotedIntegralType; ++Left) {
10109 for (unsigned Right = FirstPromotedIntegralType;
10110 Right < LastPromotedIntegralType; ++Right) {
10111 QualType LandR[2] = { ArithmeticTypes[Left],
10112 ArithmeticTypes[Right] };
10113 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10114 }
10115 }
10116 }
10117
10118 // C++ [over.built]p20:
10119 //
10120 // For every pair (T, VQ), where T is an enumeration or
10121 // pointer to member type and VQ is either volatile or
10122 // empty, there exist candidate operator functions of the form
10123 //
10124 // VQ T& operator=(VQ T&, T);
10125 void addAssignmentMemberPointerOrEnumeralOverloads() {
10126 /// Set of (canonical) types that we've already handled.
10127 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10128
10129 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10130 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10131 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10132 continue;
10133
10134 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10135 }
10136
10137 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10138 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10139 continue;
10140
10141 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10142 }
10143 }
10144 }
10145
10146 // C++ [over.built]p19:
10147 //
10148 // For every pair (T, VQ), where T is any type and VQ is either
10149 // volatile or empty, there exist candidate operator functions
10150 // of the form
10151 //
10152 // T*VQ& operator=(T*VQ&, T*);
10153 //
10154 // C++ [over.built]p21:
10155 //
10156 // For every pair (T, VQ), where T is a cv-qualified or
10157 // cv-unqualified object type and VQ is either volatile or
10158 // empty, there exist candidate operator functions of the form
10159 //
10160 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10161 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10162 void addAssignmentPointerOverloads(bool isEqualOp) {
10163 /// Set of (canonical) types that we've already handled.
10164 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10165
10166 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10167 // If this is operator=, keep track of the builtin candidates we added.
10168 if (isEqualOp)
10169 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10170 else if (!PtrTy->getPointeeType()->isObjectType())
10171 continue;
10172
10173 // non-volatile version
10174 QualType ParamTypes[2] = {
10176 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10177 };
10178 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10179 /*IsAssignmentOperator=*/ isEqualOp);
10180
10181 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10182 VisibleTypeConversionsQuals.hasVolatile();
10183 if (NeedVolatile) {
10184 // volatile version
10185 ParamTypes[0] =
10187 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10188 /*IsAssignmentOperator=*/isEqualOp);
10189 }
10190
10191 if (!PtrTy.isRestrictQualified() &&
10192 VisibleTypeConversionsQuals.hasRestrict()) {
10193 // restrict version
10194 ParamTypes[0] =
10196 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10197 /*IsAssignmentOperator=*/isEqualOp);
10198
10199 if (NeedVolatile) {
10200 // volatile restrict version
10201 ParamTypes[0] =
10204 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10205 /*IsAssignmentOperator=*/isEqualOp);
10206 }
10207 }
10208 }
10209
10210 if (isEqualOp) {
10211 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10212 // Make sure we don't add the same candidate twice.
10213 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10214 continue;
10215
10216 QualType ParamTypes[2] = {
10218 PtrTy,
10219 };
10220
10221 // non-volatile version
10222 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10223 /*IsAssignmentOperator=*/true);
10224
10225 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10226 VisibleTypeConversionsQuals.hasVolatile();
10227 if (NeedVolatile) {
10228 // volatile version
10229 ParamTypes[0] = S.Context.getLValueReferenceType(
10230 S.Context.getVolatileType(PtrTy));
10231 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10232 /*IsAssignmentOperator=*/true);
10233 }
10234
10235 if (!PtrTy.isRestrictQualified() &&
10236 VisibleTypeConversionsQuals.hasRestrict()) {
10237 // restrict version
10238 ParamTypes[0] = S.Context.getLValueReferenceType(
10239 S.Context.getRestrictType(PtrTy));
10240 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10241 /*IsAssignmentOperator=*/true);
10242
10243 if (NeedVolatile) {
10244 // volatile restrict version
10245 ParamTypes[0] =
10248 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10249 /*IsAssignmentOperator=*/true);
10250 }
10251 }
10252 }
10253 }
10254 }
10255
10256 // C++ [over.built]p18:
10257 //
10258 // For every triple (L, VQ, R), where L is an arithmetic type,
10259 // VQ is either volatile or empty, and R is a promoted
10260 // arithmetic type, there exist candidate operator functions of
10261 // the form
10262 //
10263 // VQ L& operator=(VQ L&, R);
10264 // VQ L& operator*=(VQ L&, R);
10265 // VQ L& operator/=(VQ L&, R);
10266 // VQ L& operator+=(VQ L&, R);
10267 // VQ L& operator-=(VQ L&, R);
10268 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10269 if (!HasArithmeticOrEnumeralCandidateType)
10270 return;
10271
10272 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10273 for (unsigned Right = FirstPromotedArithmeticType;
10274 Right < LastPromotedArithmeticType; ++Right) {
10275 QualType ParamTypes[2];
10276 ParamTypes[1] = ArithmeticTypes[Right];
10278 S, ArithmeticTypes[Left], Args[0]);
10279
10281 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10282 ParamTypes[0] =
10283 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10284 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10285 /*IsAssignmentOperator=*/isEqualOp);
10286 });
10287 }
10288 }
10289
10290 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10291 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10292 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10293 QualType ParamTypes[2];
10294 ParamTypes[1] = Vec2Ty;
10295 // Add this built-in operator as a candidate (VQ is empty).
10296 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10297 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10298 /*IsAssignmentOperator=*/isEqualOp);
10299
10300 // Add this built-in operator as a candidate (VQ is 'volatile').
10301 if (VisibleTypeConversionsQuals.hasVolatile()) {
10302 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10303 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10304 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10305 /*IsAssignmentOperator=*/isEqualOp);
10306 }
10307 }
10308 }
10309
10310 // C++ [over.built]p22:
10311 //
10312 // For every triple (L, VQ, R), where L is an integral type, VQ
10313 // is either volatile or empty, and R is a promoted integral
10314 // type, there exist candidate operator functions of the form
10315 //
10316 // VQ L& operator%=(VQ L&, R);
10317 // VQ L& operator<<=(VQ L&, R);
10318 // VQ L& operator>>=(VQ L&, R);
10319 // VQ L& operator&=(VQ L&, R);
10320 // VQ L& operator^=(VQ L&, R);
10321 // VQ L& operator|=(VQ L&, R);
10322 void addAssignmentIntegralOverloads() {
10323 if (!HasArithmeticOrEnumeralCandidateType)
10324 return;
10325
10326 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10327 for (unsigned Right = FirstPromotedIntegralType;
10328 Right < LastPromotedIntegralType; ++Right) {
10329 QualType ParamTypes[2];
10330 ParamTypes[1] = ArithmeticTypes[Right];
10332 S, ArithmeticTypes[Left], Args[0]);
10333
10335 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10336 ParamTypes[0] =
10337 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10339 });
10340 }
10341 }
10342 }
10343
10344 // C++ [over.operator]p23:
10345 //
10346 // There also exist candidate operator functions of the form
10347 //
10348 // bool operator!(bool);
10349 // bool operator&&(bool, bool);
10350 // bool operator||(bool, bool);
10351 void addExclaimOverload() {
10352 QualType ParamTy = S.Context.BoolTy;
10353 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10354 /*IsAssignmentOperator=*/false,
10355 /*NumContextualBoolArguments=*/1);
10356 }
10357 void addAmpAmpOrPipePipeOverload() {
10358 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10359 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10360 /*IsAssignmentOperator=*/false,
10361 /*NumContextualBoolArguments=*/2);
10362 }
10363
10364 // C++ [over.built]p13:
10365 //
10366 // For every cv-qualified or cv-unqualified object type T there
10367 // exist candidate operator functions of the form
10368 //
10369 // T* operator+(T*, ptrdiff_t); [ABOVE]
10370 // T& operator[](T*, ptrdiff_t);
10371 // T* operator-(T*, ptrdiff_t); [ABOVE]
10372 // T* operator+(ptrdiff_t, T*); [ABOVE]
10373 // T& operator[](ptrdiff_t, T*);
10374 void addSubscriptOverloads() {
10375 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10376 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10377 QualType PointeeType = PtrTy->getPointeeType();
10378 if (!PointeeType->isObjectType())
10379 continue;
10380
10381 // T& operator[](T*, ptrdiff_t)
10382 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10383 }
10384
10385 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10386 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10387 QualType PointeeType = PtrTy->getPointeeType();
10388 if (!PointeeType->isObjectType())
10389 continue;
10390
10391 // T& operator[](ptrdiff_t, T*)
10392 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10393 }
10394 }
10395
10396 // C++ [over.built]p11:
10397 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10398 // C1 is the same type as C2 or is a derived class of C2, T is an object
10399 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10400 // there exist candidate operator functions of the form
10401 //
10402 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10403 //
10404 // where CV12 is the union of CV1 and CV2.
10405 void addArrowStarOverloads() {
10406 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10407 QualType C1Ty = PtrTy;
10408 QualType C1;
10409 QualifierCollector Q1;
10410 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10411 if (!isa<RecordType>(C1))
10412 continue;
10413 // heuristic to reduce number of builtin candidates in the set.
10414 // Add volatile/restrict version only if there are conversions to a
10415 // volatile/restrict type.
10416 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10417 continue;
10418 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10419 continue;
10420 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10421 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10422 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10423 *D2 = mptr->getMostRecentCXXRecordDecl();
10424 if (!declaresSameEntity(D1, D2) &&
10425 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10426 break;
10427 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10428 // build CV12 T&
10429 QualType T = mptr->getPointeeType();
10430 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10431 T.isVolatileQualified())
10432 continue;
10433 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10434 T.isRestrictQualified())
10435 continue;
10436 T = Q1.apply(S.Context, T);
10437 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10438 }
10439 }
10440 }
10441
10442 // Note that we don't consider the first argument, since it has been
10443 // contextually converted to bool long ago. The candidates below are
10444 // therefore added as binary.
10445 //
10446 // C++ [over.built]p25:
10447 // For every type T, where T is a pointer, pointer-to-member, or scoped
10448 // enumeration type, there exist candidate operator functions of the form
10449 //
10450 // T operator?(bool, T, T);
10451 //
10452 void addConditionalOperatorOverloads() {
10453 /// Set of (canonical) types that we've already handled.
10454 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10455
10456 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10457 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10458 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10459 continue;
10460
10461 QualType ParamTypes[2] = {PtrTy, PtrTy};
10462 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10463 }
10464
10465 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10466 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10467 continue;
10468
10469 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10470 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10471 }
10472
10473 if (S.getLangOpts().CPlusPlus11) {
10474 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10475 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10476 continue;
10477
10478 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10479 continue;
10480
10481 QualType ParamTypes[2] = {EnumTy, EnumTy};
10482 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10483 }
10484 }
10485 }
10486 }
10487};
10488
10489} // end anonymous namespace
10490
10492 SourceLocation OpLoc,
10493 ArrayRef<Expr *> Args,
10494 OverloadCandidateSet &CandidateSet) {
10495 // Find all of the types that the arguments can convert to, but only
10496 // if the operator we're looking at has built-in operator candidates
10497 // that make use of these types. Also record whether we encounter non-record
10498 // candidate types or either arithmetic or enumeral candidate types.
10499 QualifiersAndAtomic VisibleTypeConversionsQuals;
10500 VisibleTypeConversionsQuals.addConst();
10501 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10502 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10503 if (Args[ArgIdx]->getType()->isAtomicType())
10504 VisibleTypeConversionsQuals.addAtomic();
10505 }
10506
10507 bool HasNonRecordCandidateType = false;
10508 bool HasArithmeticOrEnumeralCandidateType = false;
10510 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10511 CandidateTypes.emplace_back(*this);
10512 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10513 OpLoc,
10514 true,
10515 (Op == OO_Exclaim ||
10516 Op == OO_AmpAmp ||
10517 Op == OO_PipePipe),
10518 VisibleTypeConversionsQuals);
10519 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10520 CandidateTypes[ArgIdx].hasNonRecordTypes();
10521 HasArithmeticOrEnumeralCandidateType =
10522 HasArithmeticOrEnumeralCandidateType ||
10523 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10524 }
10525
10526 // Exit early when no non-record types have been added to the candidate set
10527 // for any of the arguments to the operator.
10528 //
10529 // We can't exit early for !, ||, or &&, since there we have always have
10530 // 'bool' overloads.
10531 if (!HasNonRecordCandidateType &&
10532 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10533 return;
10534
10535 // Setup an object to manage the common state for building overloads.
10536 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10537 VisibleTypeConversionsQuals,
10538 HasArithmeticOrEnumeralCandidateType,
10539 CandidateTypes, CandidateSet);
10540
10541 // Dispatch over the operation to add in only those overloads which apply.
10542 switch (Op) {
10543 case OO_None:
10545 llvm_unreachable("Expected an overloaded operator");
10546
10547 case OO_New:
10548 case OO_Delete:
10549 case OO_Array_New:
10550 case OO_Array_Delete:
10551 case OO_Call:
10552 llvm_unreachable(
10553 "Special operators don't use AddBuiltinOperatorCandidates");
10554
10555 case OO_Comma:
10556 case OO_Arrow:
10557 case OO_Coawait:
10558 // C++ [over.match.oper]p3:
10559 // -- For the operator ',', the unary operator '&', the
10560 // operator '->', or the operator 'co_await', the
10561 // built-in candidates set is empty.
10562 break;
10563
10564 case OO_Plus: // '+' is either unary or binary
10565 if (Args.size() == 1)
10566 OpBuilder.addUnaryPlusPointerOverloads();
10567 [[fallthrough]];
10568
10569 case OO_Minus: // '-' is either unary or binary
10570 if (Args.size() == 1) {
10571 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10572 } else {
10573 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10574 OpBuilder.addGenericBinaryArithmeticOverloads();
10575 OpBuilder.addMatrixBinaryArithmeticOverloads();
10576 }
10577 break;
10578
10579 case OO_Star: // '*' is either unary or binary
10580 if (Args.size() == 1)
10581 OpBuilder.addUnaryStarPointerOverloads();
10582 else {
10583 OpBuilder.addGenericBinaryArithmeticOverloads();
10584 OpBuilder.addMatrixBinaryArithmeticOverloads();
10585 }
10586 break;
10587
10588 case OO_Slash:
10589 OpBuilder.addGenericBinaryArithmeticOverloads();
10590 break;
10591
10592 case OO_PlusPlus:
10593 case OO_MinusMinus:
10594 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10595 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10596 break;
10597
10598 case OO_EqualEqual:
10599 case OO_ExclaimEqual:
10600 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10601 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10602 OpBuilder.addGenericBinaryArithmeticOverloads();
10603 break;
10604
10605 case OO_Less:
10606 case OO_Greater:
10607 case OO_LessEqual:
10608 case OO_GreaterEqual:
10609 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10610 OpBuilder.addGenericBinaryArithmeticOverloads();
10611 break;
10612
10613 case OO_Spaceship:
10614 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10615 OpBuilder.addThreeWayArithmeticOverloads();
10616 break;
10617
10618 case OO_Percent:
10619 case OO_Caret:
10620 case OO_Pipe:
10621 case OO_LessLess:
10622 case OO_GreaterGreater:
10623 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10624 break;
10625
10626 case OO_Amp: // '&' is either unary or binary
10627 if (Args.size() == 1)
10628 // C++ [over.match.oper]p3:
10629 // -- For the operator ',', the unary operator '&', or the
10630 // operator '->', the built-in candidates set is empty.
10631 break;
10632
10633 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10634 break;
10635
10636 case OO_Tilde:
10637 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10638 break;
10639
10640 case OO_Equal:
10641 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10642 [[fallthrough]];
10643
10644 case OO_PlusEqual:
10645 case OO_MinusEqual:
10646 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10647 [[fallthrough]];
10648
10649 case OO_StarEqual:
10650 case OO_SlashEqual:
10651 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10652 break;
10653
10654 case OO_PercentEqual:
10655 case OO_LessLessEqual:
10656 case OO_GreaterGreaterEqual:
10657 case OO_AmpEqual:
10658 case OO_CaretEqual:
10659 case OO_PipeEqual:
10660 OpBuilder.addAssignmentIntegralOverloads();
10661 break;
10662
10663 case OO_Exclaim:
10664 OpBuilder.addExclaimOverload();
10665 break;
10666
10667 case OO_AmpAmp:
10668 case OO_PipePipe:
10669 OpBuilder.addAmpAmpOrPipePipeOverload();
10670 break;
10671
10672 case OO_Subscript:
10673 if (Args.size() == 2)
10674 OpBuilder.addSubscriptOverloads();
10675 break;
10676
10677 case OO_ArrowStar:
10678 OpBuilder.addArrowStarOverloads();
10679 break;
10680
10681 case OO_Conditional:
10682 OpBuilder.addConditionalOperatorOverloads();
10683 OpBuilder.addGenericBinaryArithmeticOverloads();
10684 break;
10685 }
10686}
10687
10688void
10690 SourceLocation Loc,
10691 ArrayRef<Expr *> Args,
10692 TemplateArgumentListInfo *ExplicitTemplateArgs,
10693 OverloadCandidateSet& CandidateSet,
10694 bool PartialOverloading) {
10695 ADLResult Fns;
10696
10697 // FIXME: This approach for uniquing ADL results (and removing
10698 // redundant candidates from the set) relies on pointer-equality,
10699 // which means we need to key off the canonical decl. However,
10700 // always going back to the canonical decl might not get us the
10701 // right set of default arguments. What default arguments are
10702 // we supposed to consider on ADL candidates, anyway?
10703
10704 // FIXME: Pass in the explicit template arguments?
10705 ArgumentDependentLookup(Name, Loc, Args, Fns);
10706
10707 ArrayRef<Expr *> ReversedArgs;
10708
10709 // Erase all of the candidates we already knew about.
10710 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10711 CandEnd = CandidateSet.end();
10712 Cand != CandEnd; ++Cand)
10713 if (Cand->Function) {
10714 FunctionDecl *Fn = Cand->Function;
10715 Fns.erase(Fn);
10716 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10717 Fns.erase(FunTmpl);
10718 }
10719
10720 // For each of the ADL candidates we found, add it to the overload
10721 // set.
10722 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10724
10725 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10726 if (ExplicitTemplateArgs)
10727 continue;
10728
10730 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10731 PartialOverloading, /*AllowExplicit=*/true,
10732 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10733 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10735 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10736 /*SuppressUserConversions=*/false, PartialOverloading,
10737 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10738 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10739 }
10740 } else {
10741 auto *FTD = cast<FunctionTemplateDecl>(*I);
10743 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10744 /*SuppressUserConversions=*/false, PartialOverloading,
10745 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10746 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10747 *this, Args, FTD->getTemplatedDecl())) {
10748
10749 // As template candidates are not deduced immediately,
10750 // persist the array in the overload set.
10751 if (ReversedArgs.empty())
10752 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10753
10755 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10756 /*SuppressUserConversions=*/false, PartialOverloading,
10757 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10759 }
10760 }
10761 }
10762}
10763
10764namespace {
10765enum class Comparison { Equal, Better, Worse };
10766}
10767
10768/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10769/// overload resolution.
10770///
10771/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10772/// Cand1's first N enable_if attributes have precisely the same conditions as
10773/// Cand2's first N enable_if attributes (where N = the number of enable_if
10774/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10775///
10776/// Note that you can have a pair of candidates such that Cand1's enable_if
10777/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10778/// worse than Cand1's.
10779static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10780 const FunctionDecl *Cand2) {
10781 // Common case: One (or both) decls don't have enable_if attrs.
10782 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10783 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10784 if (!Cand1Attr || !Cand2Attr) {
10785 if (Cand1Attr == Cand2Attr)
10786 return Comparison::Equal;
10787 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10788 }
10789
10790 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10791 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10792
10793 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10794 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10795 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10796 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10797
10798 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10799 // has fewer enable_if attributes than Cand2, and vice versa.
10800 if (!Cand1A)
10801 return Comparison::Worse;
10802 if (!Cand2A)
10803 return Comparison::Better;
10804
10805 Cand1ID.clear();
10806 Cand2ID.clear();
10807
10808 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10809 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10810 if (Cand1ID != Cand2ID)
10811 return Comparison::Worse;
10812 }
10813
10814 return Comparison::Equal;
10815}
10816
10817static Comparison
10819 const OverloadCandidate &Cand2) {
10820 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10821 !Cand2.Function->isMultiVersion())
10822 return Comparison::Equal;
10823
10824 // If both are invalid, they are equal. If one of them is invalid, the other
10825 // is better.
10826 if (Cand1.Function->isInvalidDecl()) {
10827 if (Cand2.Function->isInvalidDecl())
10828 return Comparison::Equal;
10829 return Comparison::Worse;
10830 }
10831 if (Cand2.Function->isInvalidDecl())
10832 return Comparison::Better;
10833
10834 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10835 // cpu_dispatch, else arbitrarily based on the identifiers.
10836 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10837 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10838 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10839 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10840
10841 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10842 return Comparison::Equal;
10843
10844 if (Cand1CPUDisp && !Cand2CPUDisp)
10845 return Comparison::Better;
10846 if (Cand2CPUDisp && !Cand1CPUDisp)
10847 return Comparison::Worse;
10848
10849 if (Cand1CPUSpec && Cand2CPUSpec) {
10850 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10851 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10852 ? Comparison::Better
10853 : Comparison::Worse;
10854
10855 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10856 FirstDiff = std::mismatch(
10857 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10858 Cand2CPUSpec->cpus_begin(),
10859 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10860 return LHS->getName() == RHS->getName();
10861 });
10862
10863 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10864 "Two different cpu-specific versions should not have the same "
10865 "identifier list, otherwise they'd be the same decl!");
10866 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10867 ? Comparison::Better
10868 : Comparison::Worse;
10869 }
10870 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10871}
10872
10873/// Compute the type of the implicit object parameter for the given function,
10874/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10875/// null QualType if there is a 'matches anything' implicit object parameter.
10876static std::optional<QualType>
10879 return std::nullopt;
10880
10881 auto *M = cast<CXXMethodDecl>(F);
10882 // Static member functions' object parameters match all types.
10883 if (M->isStatic())
10884 return QualType();
10885 return M->getFunctionObjectParameterReferenceType();
10886}
10887
10888// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10889// represent the same entity.
10890static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10891 const FunctionDecl *F2) {
10892 if (declaresSameEntity(F1, F2))
10893 return true;
10894 auto PT1 = F1->getPrimaryTemplate();
10895 auto PT2 = F2->getPrimaryTemplate();
10896 if (PT1 && PT2) {
10897 if (declaresSameEntity(PT1, PT2) ||
10898 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10899 PT2->getInstantiatedFromMemberTemplate()))
10900 return true;
10901 }
10902 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10903 // different functions with same params). Consider removing this (as no test
10904 // fail w/o it).
10905 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10906 if (First) {
10907 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10908 return *T;
10909 }
10910 assert(I < F->getNumParams());
10911 return F->getParamDecl(I++)->getType();
10912 };
10913
10914 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10915 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10916
10917 if (F1NumParams != F2NumParams)
10918 return false;
10919
10920 unsigned I1 = 0, I2 = 0;
10921 for (unsigned I = 0; I != F1NumParams; ++I) {
10922 QualType T1 = NextParam(F1, I1, I == 0);
10923 QualType T2 = NextParam(F2, I2, I == 0);
10924 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10925 if (!Context.hasSameUnqualifiedType(T1, T2))
10926 return false;
10927 }
10928 return true;
10929}
10930
10931/// We're allowed to use constraints partial ordering only if the candidates
10932/// have the same parameter types:
10933/// [over.match.best.general]p2.6
10934/// F1 and F2 are non-template functions with the same
10935/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10937 FunctionDecl *Fn2,
10938 bool IsFn1Reversed,
10939 bool IsFn2Reversed) {
10940 assert(Fn1 && Fn2);
10941 if (Fn1->isVariadic() != Fn2->isVariadic())
10942 return false;
10943
10944 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10945 IsFn1Reversed ^ IsFn2Reversed))
10946 return false;
10947
10948 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10949 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10950 if (Mem1 && Mem2) {
10951 // if they are member functions, both are direct members of the same class,
10952 // and
10953 if (Mem1->getParent() != Mem2->getParent())
10954 return false;
10955 // if both are non-static member functions, they have the same types for
10956 // their object parameters
10957 if (Mem1->isInstance() && Mem2->isInstance() &&
10959 Mem1->getFunctionObjectParameterReferenceType(),
10960 Mem1->getFunctionObjectParameterReferenceType()))
10961 return false;
10962 }
10963 return true;
10964}
10965
10966static FunctionDecl *
10968 bool IsFn1Reversed, bool IsFn2Reversed) {
10969 if (!Fn1 || !Fn2)
10970 return nullptr;
10971
10972 // C++ [temp.constr.order]:
10973 // A non-template function F1 is more partial-ordering-constrained than a
10974 // non-template function F2 if:
10975 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10976 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10977
10978 if (Cand1IsSpecialization || Cand2IsSpecialization)
10979 return nullptr;
10980
10981 // - they have the same non-object-parameter-type-lists, and [...]
10982 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10983 IsFn2Reversed))
10984 return nullptr;
10985
10986 // - the declaration of F1 is more constrained than the declaration of F2.
10987 return S.getMoreConstrainedFunction(Fn1, Fn2);
10988}
10989
10990/// isBetterOverloadCandidate - Determines whether the first overload
10991/// candidate is a better candidate than the second (C++ 13.3.3p1).
10993 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10995 bool PartialOverloading) {
10996 // Define viable functions to be better candidates than non-viable
10997 // functions.
10998 if (!Cand2.Viable)
10999 return Cand1.Viable;
11000 else if (!Cand1.Viable)
11001 return false;
11002
11003 // [CUDA] A function with 'never' preference is marked not viable, therefore
11004 // is never shown up here. The worst preference shown up here is 'wrong side',
11005 // e.g. an H function called by a HD function in device compilation. This is
11006 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11007 // function which is called only by an H function. A deferred diagnostic will
11008 // be triggered if it is emitted. However a wrong-sided function is still
11009 // a viable candidate here.
11010 //
11011 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11012 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11013 // can be emitted, Cand1 is not better than Cand2. This rule should have
11014 // precedence over other rules.
11015 //
11016 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11017 // other rules should be used to determine which is better. This is because
11018 // host/device based overloading resolution is mostly for determining
11019 // viability of a function. If two functions are both viable, other factors
11020 // should take precedence in preference, e.g. the standard-defined preferences
11021 // like argument conversion ranks or enable_if partial-ordering. The
11022 // preference for pass-object-size parameters is probably most similar to a
11023 // type-based-overloading decision and so should take priority.
11024 //
11025 // If other rules cannot determine which is better, CUDA preference will be
11026 // used again to determine which is better.
11027 //
11028 // TODO: Currently IdentifyPreference does not return correct values
11029 // for functions called in global variable initializers due to missing
11030 // correct context about device/host. Therefore we can only enforce this
11031 // rule when there is a caller. We should enforce this rule for functions
11032 // in global variable initializers once proper context is added.
11033 //
11034 // TODO: We can only enable the hostness based overloading resolution when
11035 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11036 // overloading resolution diagnostics.
11037 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11038 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11039 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11040 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11041 bool IsCand1ImplicitHD =
11043 bool IsCand2ImplicitHD =
11045 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11046 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11047 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11048 // The implicit HD function may be a function in a system header which
11049 // is forced by pragma. In device compilation, if we prefer HD candidates
11050 // over wrong-sided candidates, overloading resolution may change, which
11051 // may result in non-deferrable diagnostics. As a workaround, we let
11052 // implicit HD candidates take equal preference as wrong-sided candidates.
11053 // This will preserve the overloading resolution.
11054 // TODO: We still need special handling of implicit HD functions since
11055 // they may incur other diagnostics to be deferred. We should make all
11056 // host/device related diagnostics deferrable and remove special handling
11057 // of implicit HD functions.
11058 auto EmitThreshold =
11059 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11060 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11063 auto Cand1Emittable = P1 > EmitThreshold;
11064 auto Cand2Emittable = P2 > EmitThreshold;
11065 if (Cand1Emittable && !Cand2Emittable)
11066 return true;
11067 if (!Cand1Emittable && Cand2Emittable)
11068 return false;
11069 }
11070 }
11071
11072 // C++ [over.match.best]p1: (Changed in C++23)
11073 //
11074 // -- if F is a static member function, ICS1(F) is defined such
11075 // that ICS1(F) is neither better nor worse than ICS1(G) for
11076 // any function G, and, symmetrically, ICS1(G) is neither
11077 // better nor worse than ICS1(F).
11078 unsigned StartArg = 0;
11079 if (!Cand1.TookAddressOfOverload &&
11081 StartArg = 1;
11082
11083 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11084 // We don't allow incompatible pointer conversions in C++.
11085 if (!S.getLangOpts().CPlusPlus)
11086 return ICS.isStandard() &&
11087 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11088
11089 // The only ill-formed conversion we allow in C++ is the string literal to
11090 // char* conversion, which is only considered ill-formed after C++11.
11091 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11093 };
11094
11095 // Define functions that don't require ill-formed conversions for a given
11096 // argument to be better candidates than functions that do.
11097 unsigned NumArgs = Cand1.Conversions.size();
11098 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11099 bool HasBetterConversion = false;
11100 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11101 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11102 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11103 if (Cand1Bad != Cand2Bad) {
11104 if (Cand1Bad)
11105 return false;
11106 HasBetterConversion = true;
11107 }
11108 }
11109
11110 if (HasBetterConversion)
11111 return true;
11112
11113 // C++ [over.match.best]p1:
11114 // A viable function F1 is defined to be a better function than another
11115 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11116 // conversion sequence than ICSi(F2), and then...
11117 bool HasWorseConversion = false;
11118 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11120 Cand1.Conversions[ArgIdx],
11121 Cand2.Conversions[ArgIdx])) {
11123 // Cand1 has a better conversion sequence.
11124 HasBetterConversion = true;
11125 break;
11126
11128 if (Cand1.Function && Cand2.Function &&
11129 Cand1.isReversed() != Cand2.isReversed() &&
11130 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11131 // Work around large-scale breakage caused by considering reversed
11132 // forms of operator== in C++20:
11133 //
11134 // When comparing a function against a reversed function, if we have a
11135 // better conversion for one argument and a worse conversion for the
11136 // other, the implicit conversion sequences are treated as being equally
11137 // good.
11138 //
11139 // This prevents a comparison function from being considered ambiguous
11140 // with a reversed form that is written in the same way.
11141 //
11142 // We diagnose this as an extension from CreateOverloadedBinOp.
11143 HasWorseConversion = true;
11144 break;
11145 }
11146
11147 // Cand1 can't be better than Cand2.
11148 return false;
11149
11151 // Do nothing.
11152 break;
11153 }
11154 }
11155
11156 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11157 // ICSj(F2), or, if not that,
11158 if (HasBetterConversion && !HasWorseConversion)
11159 return true;
11160
11161 // -- the context is an initialization by user-defined conversion
11162 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11163 // from the return type of F1 to the destination type (i.e.,
11164 // the type of the entity being initialized) is a better
11165 // conversion sequence than the standard conversion sequence
11166 // from the return type of F2 to the destination type.
11168 Cand1.Function && Cand2.Function &&
11171
11172 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11173 // First check whether we prefer one of the conversion functions over the
11174 // other. This only distinguishes the results in non-standard, extension
11175 // cases such as the conversion from a lambda closure type to a function
11176 // pointer or block.
11181 Cand1.FinalConversion,
11182 Cand2.FinalConversion);
11183
11186
11187 // FIXME: Compare kind of reference binding if conversion functions
11188 // convert to a reference type used in direct reference binding, per
11189 // C++14 [over.match.best]p1 section 2 bullet 3.
11190 }
11191
11192 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11193 // as combined with the resolution to CWG issue 243.
11194 //
11195 // When the context is initialization by constructor ([over.match.ctor] or
11196 // either phase of [over.match.list]), a constructor is preferred over
11197 // a conversion function.
11198 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11199 Cand1.Function && Cand2.Function &&
11202 return isa<CXXConstructorDecl>(Cand1.Function);
11203
11204 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11205 return Cand2.StrictPackMatch;
11206
11207 // -- F1 is a non-template function and F2 is a function template
11208 // specialization, or, if not that,
11209 bool Cand1IsSpecialization = Cand1.Function &&
11211 bool Cand2IsSpecialization = Cand2.Function &&
11213 if (Cand1IsSpecialization != Cand2IsSpecialization)
11214 return Cand2IsSpecialization;
11215
11216 // -- F1 and F2 are function template specializations, and the function
11217 // template for F1 is more specialized than the template for F2
11218 // according to the partial ordering rules described in 14.5.5.2, or,
11219 // if not that,
11220 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11221 const auto *Obj1Context =
11222 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11223 const auto *Obj2Context =
11224 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11225 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11227 Cand2.Function->getPrimaryTemplate(), Loc,
11229 : TPOC_Call,
11231 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11232 : QualType{},
11233 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11234 : QualType{},
11235 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11236 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11237 }
11238 }
11239
11240 // -— F1 and F2 are non-template functions and F1 is more
11241 // partial-ordering-constrained than F2 [...],
11243 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11244 Cand2.isReversed());
11245 F && F == Cand1.Function)
11246 return true;
11247
11248 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11249 // class B of D, and for all arguments the corresponding parameters of
11250 // F1 and F2 have the same type.
11251 // FIXME: Implement the "all parameters have the same type" check.
11252 bool Cand1IsInherited =
11253 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11254 bool Cand2IsInherited =
11255 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11256 if (Cand1IsInherited != Cand2IsInherited)
11257 return Cand2IsInherited;
11258 else if (Cand1IsInherited) {
11259 assert(Cand2IsInherited);
11260 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11261 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11262 if (Cand1Class->isDerivedFrom(Cand2Class))
11263 return true;
11264 if (Cand2Class->isDerivedFrom(Cand1Class))
11265 return false;
11266 // Inherited from sibling base classes: still ambiguous.
11267 }
11268
11269 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11270 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11271 // with reversed order of parameters and F1 is not
11272 //
11273 // We rank reversed + different operator as worse than just reversed, but
11274 // that comparison can never happen, because we only consider reversing for
11275 // the maximally-rewritten operator (== or <=>).
11276 if (Cand1.RewriteKind != Cand2.RewriteKind)
11277 return Cand1.RewriteKind < Cand2.RewriteKind;
11278
11279 // Check C++17 tie-breakers for deduction guides.
11280 {
11281 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11282 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11283 if (Guide1 && Guide2) {
11284 // -- F1 is generated from a deduction-guide and F2 is not
11285 if (Guide1->isImplicit() != Guide2->isImplicit())
11286 return Guide2->isImplicit();
11287
11288 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11289 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11290 return true;
11291 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11292 return false;
11293
11294 // --F1 is generated from a non-template constructor and F2 is generated
11295 // from a constructor template
11296 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11297 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11298 if (Constructor1 && Constructor2) {
11299 bool isC1Templated = Constructor1->getTemplatedKind() !=
11301 bool isC2Templated = Constructor2->getTemplatedKind() !=
11303 if (isC1Templated != isC2Templated)
11304 return isC2Templated;
11305 }
11306 }
11307 }
11308
11309 // Check for enable_if value-based overload resolution.
11310 if (Cand1.Function && Cand2.Function) {
11312 if (Cmp != Comparison::Equal)
11313 return Cmp == Comparison::Better;
11314 }
11315
11316 bool HasPS1 = Cand1.Function != nullptr &&
11318 bool HasPS2 = Cand2.Function != nullptr &&
11320 if (HasPS1 != HasPS2 && HasPS1)
11321 return true;
11322
11323 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11324 if (MV == Comparison::Better)
11325 return true;
11326 if (MV == Comparison::Worse)
11327 return false;
11328
11329 // If other rules cannot determine which is better, CUDA preference is used
11330 // to determine which is better.
11331 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11332 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11333 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11334 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11335 }
11336
11337 // General member function overloading is handled above, so this only handles
11338 // constructors with address spaces.
11339 // This only handles address spaces since C++ has no other
11340 // qualifier that can be used with constructors.
11341 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11342 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11343 if (CD1 && CD2) {
11344 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11345 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11346 if (AS1 != AS2) {
11348 return true;
11350 return false;
11351 }
11352 }
11353
11354 return false;
11355}
11356
11357/// Determine whether two declarations are "equivalent" for the purposes of
11358/// name lookup and overload resolution. This applies when the same internal/no
11359/// linkage entity is defined by two modules (probably by textually including
11360/// the same header). In such a case, we don't consider the declarations to
11361/// declare the same entity, but we also don't want lookups with both
11362/// declarations visible to be ambiguous in some cases (this happens when using
11363/// a modularized libstdc++).
11365 const NamedDecl *B) {
11366 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11367 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11368 if (!VA || !VB)
11369 return false;
11370
11371 // The declarations must be declaring the same name as an internal linkage
11372 // entity in different modules.
11373 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11374 VB->getDeclContext()->getRedeclContext()) ||
11375 getOwningModule(VA) == getOwningModule(VB) ||
11376 VA->isExternallyVisible() || VB->isExternallyVisible())
11377 return false;
11378
11379 // Check that the declarations appear to be equivalent.
11380 //
11381 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11382 // For constants and functions, we should check the initializer or body is
11383 // the same. For non-constant variables, we shouldn't allow it at all.
11384 if (Context.hasSameType(VA->getType(), VB->getType()))
11385 return true;
11386
11387 // Enum constants within unnamed enumerations will have different types, but
11388 // may still be similar enough to be interchangeable for our purposes.
11389 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11390 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11391 // Only handle anonymous enums. If the enumerations were named and
11392 // equivalent, they would have been merged to the same type.
11393 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11394 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11395 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11396 !Context.hasSameType(EnumA->getIntegerType(),
11397 EnumB->getIntegerType()))
11398 return false;
11399 // Allow this only if the value is the same for both enumerators.
11400 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11401 }
11402 }
11403
11404 // Nothing else is sufficiently similar.
11405 return false;
11406}
11407
11410 assert(D && "Unknown declaration");
11411 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11412
11413 Module *M = getOwningModule(D);
11414 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11415 << !M << (M ? M->getFullModuleName() : "");
11416
11417 for (auto *E : Equiv) {
11418 Module *M = getOwningModule(E);
11419 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11420 << !M << (M ? M->getFullModuleName() : "");
11421 }
11422}
11423
11426 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11428 static_cast<CNSInfo *>(DeductionFailure.Data)
11429 ->Satisfaction.ContainsErrors;
11430}
11431
11434 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11435 bool PartialOverloading, bool AllowExplicit,
11437 bool AggregateCandidateDeduction) {
11438
11439 auto *C =
11440 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11441
11444 /*AllowObjCConversionOnExplicit=*/false,
11445 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11446 PartialOverloading, AggregateCandidateDeduction},
11448 FoundDecl,
11449 Args,
11450 IsADLCandidate,
11451 PO};
11452
11453 HasDeferredTemplateConstructors |=
11454 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11455}
11456
11458 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11459 CXXRecordDecl *ActingContext, QualType ObjectType,
11460 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11461 bool SuppressUserConversions, bool PartialOverloading,
11463
11464 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11465
11466 auto *C =
11467 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11468
11471 /*AllowObjCConversionOnExplicit=*/false,
11472 /*AllowResultConversion=*/false,
11473 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11474 /*AggregateCandidateDeduction=*/false},
11475 MethodTmpl,
11476 FoundDecl,
11477 Args,
11478 ActingContext,
11479 ObjectClassification,
11480 ObjectType,
11481 PO};
11482}
11483
11486 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11487 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11488 bool AllowResultConversion) {
11489
11490 auto *C =
11491 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11492
11495 AllowObjCConversionOnExplicit, AllowResultConversion,
11496 /*AllowExplicit=*/false,
11497 /*SuppressUserConversions=*/false,
11498 /*PartialOverloading*/ false,
11499 /*AggregateCandidateDeduction=*/false},
11501 FoundDecl,
11502 ActingContext,
11503 From,
11504 ToType};
11505}
11506
11507static void
11510
11512 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11513 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11514 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11515}
11516
11517static void
11521 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11522 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11523 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11524 C.AggregateCandidateDeduction);
11525}
11526
11527static void
11531 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11532 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11533 C.AllowResultConversion);
11534}
11535
11537 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11538 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11539 while (Cand) {
11540 switch (Cand->Kind) {
11543 S, *this,
11544 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11545 break;
11548 S, *this,
11549 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11550 break;
11553 S, *this,
11554 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11555 break;
11556 }
11557 Cand = Cand->Next;
11558 }
11559 FirstDeferredCandidate = nullptr;
11560 DeferredCandidatesCount = 0;
11561}
11562
11564OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11565 Best->Best = true;
11566 if (Best->Function && Best->Function->isDeleted())
11567 return OR_Deleted;
11568 return OR_Success;
11569}
11570
11571void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11573 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11574 // are accepted by both clang and NVCC. However, during a particular
11575 // compilation mode only one call variant is viable. We need to
11576 // exclude non-viable overload candidates from consideration based
11577 // only on their host/device attributes. Specifically, if one
11578 // candidate call is WrongSide and the other is SameSide, we ignore
11579 // the WrongSide candidate.
11580 // We only need to remove wrong-sided candidates here if
11581 // -fgpu-exclude-wrong-side-overloads is off. When
11582 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11583 // uniformly in isBetterOverloadCandidate.
11584 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11585 return;
11586 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11587
11588 bool ContainsSameSideCandidate =
11589 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11590 // Check viable function only.
11591 return Cand->Viable && Cand->Function &&
11592 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11594 });
11595
11596 if (!ContainsSameSideCandidate)
11597 return;
11598
11599 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11600 // Check viable function only to avoid unnecessary data copying/moving.
11601 return Cand->Viable && Cand->Function &&
11602 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11604 };
11605 llvm::erase_if(Candidates, IsWrongSideCandidate);
11606}
11607
11608/// Computes the best viable function (C++ 13.3.3)
11609/// within an overload candidate set.
11610///
11611/// \param Loc The location of the function name (or operator symbol) for
11612/// which overload resolution occurs.
11613///
11614/// \param Best If overload resolution was successful or found a deleted
11615/// function, \p Best points to the candidate function found.
11616///
11617/// \returns The result of overload resolution.
11619 SourceLocation Loc,
11620 iterator &Best) {
11621
11623 DeferredCandidatesCount == 0) &&
11624 "Unexpected deferred template candidates");
11625
11626 bool TwoPhaseResolution =
11627 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11628
11629 if (TwoPhaseResolution) {
11630 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11631 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11632 if (!(HasDeferredTemplateConstructors &&
11633 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11634 return Res;
11635 }
11636 }
11637
11639 return BestViableFunctionImpl(S, Loc, Best);
11640}
11641
11642OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11644
11646 Candidates.reserve(this->Candidates.size());
11647 std::transform(this->Candidates.begin(), this->Candidates.end(),
11648 std::back_inserter(Candidates),
11649 [](OverloadCandidate &Cand) { return &Cand; });
11650
11651 if (S.getLangOpts().CUDA)
11652 CudaExcludeWrongSideCandidates(S, Candidates);
11653
11654 Best = end();
11655 for (auto *Cand : Candidates) {
11656 Cand->Best = false;
11657 if (Cand->Viable) {
11658 if (Best == end() ||
11659 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11660 Best = Cand;
11661 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11662 // This candidate has constraint that we were unable to evaluate because
11663 // it referenced an expression that contained an error. Rather than fall
11664 // back onto a potentially unintended candidate (made worse by
11665 // subsuming constraints), treat this as 'no viable candidate'.
11666 Best = end();
11667 return OR_No_Viable_Function;
11668 }
11669 }
11670
11671 // If we didn't find any viable functions, abort.
11672 if (Best == end())
11673 return OR_No_Viable_Function;
11674
11675 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11676 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11677 PendingBest.push_back(&*Best);
11678 Best->Best = true;
11679
11680 // Make sure that this function is better than every other viable
11681 // function. If not, we have an ambiguity.
11682 while (!PendingBest.empty()) {
11683 auto *Curr = PendingBest.pop_back_val();
11684 for (auto *Cand : Candidates) {
11685 if (Cand->Viable && !Cand->Best &&
11686 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11687 PendingBest.push_back(Cand);
11688 Cand->Best = true;
11689
11691 Curr->Function))
11692 EquivalentCands.push_back(Cand->Function);
11693 else
11694 Best = end();
11695 }
11696 }
11697 }
11698
11699 if (Best == end())
11700 return OR_Ambiguous;
11701
11702 OverloadingResult R = ResultForBestCandidate(Best);
11703
11704 if (!EquivalentCands.empty())
11706 EquivalentCands);
11707 return R;
11708}
11709
11710namespace {
11711
11712enum OverloadCandidateKind {
11713 oc_function,
11714 oc_method,
11715 oc_reversed_binary_operator,
11716 oc_constructor,
11717 oc_implicit_default_constructor,
11718 oc_implicit_copy_constructor,
11719 oc_implicit_move_constructor,
11720 oc_implicit_copy_assignment,
11721 oc_implicit_move_assignment,
11722 oc_implicit_equality_comparison,
11723 oc_inherited_constructor
11724};
11725
11726enum OverloadCandidateSelect {
11727 ocs_non_template,
11728 ocs_template,
11729 ocs_described_template,
11730};
11731
11732static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11733ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11734 const FunctionDecl *Fn,
11736 std::string &Description) {
11737
11738 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11739 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11740 isTemplate = true;
11741 Description = S.getTemplateArgumentBindingsText(
11742 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11743 }
11744
11745 OverloadCandidateSelect Select = [&]() {
11746 if (!Description.empty())
11747 return ocs_described_template;
11748 return isTemplate ? ocs_template : ocs_non_template;
11749 }();
11750
11751 OverloadCandidateKind Kind = [&]() {
11752 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11753 return oc_implicit_equality_comparison;
11754
11755 if (CRK & CRK_Reversed)
11756 return oc_reversed_binary_operator;
11757
11758 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11759 if (!Ctor->isImplicit()) {
11761 return oc_inherited_constructor;
11762 else
11763 return oc_constructor;
11764 }
11765
11766 if (Ctor->isDefaultConstructor())
11767 return oc_implicit_default_constructor;
11768
11769 if (Ctor->isMoveConstructor())
11770 return oc_implicit_move_constructor;
11771
11772 assert(Ctor->isCopyConstructor() &&
11773 "unexpected sort of implicit constructor");
11774 return oc_implicit_copy_constructor;
11775 }
11776
11777 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11778 // This actually gets spelled 'candidate function' for now, but
11779 // it doesn't hurt to split it out.
11780 if (!Meth->isImplicit())
11781 return oc_method;
11782
11783 if (Meth->isMoveAssignmentOperator())
11784 return oc_implicit_move_assignment;
11785
11786 if (Meth->isCopyAssignmentOperator())
11787 return oc_implicit_copy_assignment;
11788
11789 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11790 return oc_method;
11791 }
11792
11793 return oc_function;
11794 }();
11795
11796 return std::make_pair(Kind, Select);
11797}
11798
11799void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11800 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11801 // set.
11802 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11803 S.Diag(FoundDecl->getLocation(),
11804 diag::note_ovl_candidate_inherited_constructor)
11805 << Shadow->getNominatedBaseClass();
11806}
11807
11808} // end anonymous namespace
11809
11811 const FunctionDecl *FD) {
11812 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11813 bool AlwaysTrue;
11814 if (EnableIf->getCond()->isValueDependent() ||
11815 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11816 return false;
11817 if (!AlwaysTrue)
11818 return false;
11819 }
11820 return true;
11821}
11822
11823/// Returns true if we can take the address of the function.
11824///
11825/// \param Complain - If true, we'll emit a diagnostic
11826/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11827/// we in overload resolution?
11828/// \param Loc - The location of the statement we're complaining about. Ignored
11829/// if we're not complaining, or if we're in overload resolution.
11831 bool Complain,
11832 bool InOverloadResolution,
11833 SourceLocation Loc) {
11834 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11835 if (Complain) {
11836 if (InOverloadResolution)
11837 S.Diag(FD->getBeginLoc(),
11838 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11839 else
11840 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11841 }
11842 return false;
11843 }
11844
11845 if (FD->getTrailingRequiresClause()) {
11846 ConstraintSatisfaction Satisfaction;
11847 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11848 return false;
11849 if (!Satisfaction.IsSatisfied) {
11850 if (Complain) {
11851 if (InOverloadResolution) {
11852 SmallString<128> TemplateArgString;
11853 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11854 TemplateArgString += " ";
11855 TemplateArgString += S.getTemplateArgumentBindingsText(
11856 FunTmpl->getTemplateParameters(),
11858 }
11859
11860 S.Diag(FD->getBeginLoc(),
11861 diag::note_ovl_candidate_unsatisfied_constraints)
11862 << TemplateArgString;
11863 } else
11864 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11865 << FD;
11866 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11867 }
11868 return false;
11869 }
11870 }
11871
11872 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11873 return P->hasAttr<PassObjectSizeAttr>();
11874 });
11875 if (I == FD->param_end())
11876 return true;
11877
11878 if (Complain) {
11879 // Add one to ParamNo because it's user-facing
11880 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11881 if (InOverloadResolution)
11882 S.Diag(FD->getLocation(),
11883 diag::note_ovl_candidate_has_pass_object_size_params)
11884 << ParamNo;
11885 else
11886 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11887 << FD << ParamNo;
11888 }
11889 return false;
11890}
11891
11893 const FunctionDecl *FD) {
11894 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11895 /*InOverloadResolution=*/true,
11896 /*Loc=*/SourceLocation());
11897}
11898
11900 bool Complain,
11901 SourceLocation Loc) {
11902 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11903 /*InOverloadResolution=*/false,
11904 Loc);
11905}
11906
11907// Don't print candidates other than the one that matches the calling
11908// convention of the call operator, since that is guaranteed to exist.
11910 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11911
11912 if (!ConvD)
11913 return false;
11914 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11915 if (!RD->isLambda())
11916 return false;
11917
11918 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11919 CallingConv CallOpCC =
11920 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11921 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11922 CallingConv ConvToCC =
11923 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11924
11925 return ConvToCC != CallOpCC;
11926}
11927
11928// Notes the location of an overload candidate.
11930 OverloadCandidateRewriteKind RewriteKind,
11931 QualType DestType, bool TakingAddress) {
11932 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11933 return;
11934 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11935 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11936 return;
11937 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11938 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11939 return;
11941 return;
11942
11943 std::string FnDesc;
11944 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11945 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11946 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11947 << (unsigned)KSPair.first << (unsigned)KSPair.second
11948 << Fn << FnDesc;
11949
11950 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11951 Diag(Fn->getLocation(), PD);
11952 MaybeEmitInheritedConstructorNote(*this, Found);
11953}
11954
11955static void
11957 // Perhaps the ambiguity was caused by two atomic constraints that are
11958 // 'identical' but not equivalent:
11959 //
11960 // void foo() requires (sizeof(T) > 4) { } // #1
11961 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11962 //
11963 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11964 // #2 to subsume #1, but these constraint are not considered equivalent
11965 // according to the subsumption rules because they are not the same
11966 // source-level construct. This behavior is quite confusing and we should try
11967 // to help the user figure out what happened.
11968
11969 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11970 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11971 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11972 if (!I->Function)
11973 continue;
11975 if (auto *Template = I->Function->getPrimaryTemplate())
11976 Template->getAssociatedConstraints(AC);
11977 else
11978 I->Function->getAssociatedConstraints(AC);
11979 if (AC.empty())
11980 continue;
11981 if (FirstCand == nullptr) {
11982 FirstCand = I->Function;
11983 FirstAC = AC;
11984 } else if (SecondCand == nullptr) {
11985 SecondCand = I->Function;
11986 SecondAC = AC;
11987 } else {
11988 // We have more than one pair of constrained functions - this check is
11989 // expensive and we'd rather not try to diagnose it.
11990 return;
11991 }
11992 }
11993 if (!SecondCand)
11994 return;
11995 // The diagnostic can only happen if there are associated constraints on
11996 // both sides (there needs to be some identical atomic constraint).
11997 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11998 SecondCand, SecondAC))
11999 // Just show the user one diagnostic, they'll probably figure it out
12000 // from here.
12001 return;
12002}
12003
12004// Notes the location of all overload candidates designated through
12005// OverloadedExpr
12006void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12007 bool TakingAddress) {
12008 assert(OverloadedExpr->getType() == Context.OverloadTy);
12009
12010 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
12011 OverloadExpr *OvlExpr = Ovl.Expression;
12012
12013 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12014 IEnd = OvlExpr->decls_end();
12015 I != IEnd; ++I) {
12016 if (FunctionTemplateDecl *FunTmpl =
12017 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12018 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12019 TakingAddress);
12020 } else if (FunctionDecl *Fun
12021 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12022 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12023 }
12024 }
12025}
12026
12027/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12028/// "lead" diagnostic; it will be given two arguments, the source and
12029/// target types of the conversion.
12031 Sema &S,
12032 SourceLocation CaretLoc,
12033 const PartialDiagnostic &PDiag) const {
12034 S.Diag(CaretLoc, PDiag)
12035 << Ambiguous.getFromType() << Ambiguous.getToType();
12036 unsigned CandsShown = 0;
12038 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12039 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12040 break;
12041 ++CandsShown;
12042 S.NoteOverloadCandidate(I->first, I->second);
12043 }
12044 S.Diags.overloadCandidatesShown(CandsShown);
12045 if (I != E)
12046 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12047}
12048
12050 unsigned I, bool TakingCandidateAddress) {
12051 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12052 assert(Conv.isBad());
12053 assert(Cand->Function && "for now, candidate must be a function");
12054 FunctionDecl *Fn = Cand->Function;
12055
12056 // There's a conversion slot for the object argument if this is a
12057 // non-constructor method. Note that 'I' corresponds the
12058 // conversion-slot index.
12059 bool isObjectArgument = false;
12060 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12062 if (I == 0)
12063 isObjectArgument = true;
12064 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12065 I--;
12066 }
12067
12068 std::string FnDesc;
12069 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12070 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12071 FnDesc);
12072
12073 Expr *FromExpr = Conv.Bad.FromExpr;
12074 QualType FromTy = Conv.Bad.getFromType();
12075 QualType ToTy = Conv.Bad.getToType();
12076 SourceRange ToParamRange;
12077
12078 // FIXME: In presence of parameter packs we can't determine parameter range
12079 // reliably, as we don't have access to instantiation.
12080 bool HasParamPack =
12081 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12082 return Parm->isParameterPack();
12083 });
12084 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12085 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12086
12087 if (FromTy == S.Context.OverloadTy) {
12088 assert(FromExpr && "overload set argument came from implicit argument?");
12089 Expr *E = FromExpr->IgnoreParens();
12090 if (isa<UnaryOperator>(E))
12091 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12092 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12093
12094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12095 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12096 << ToParamRange << ToTy << Name << I + 1;
12097 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12098 return;
12099 }
12100
12101 // Do some hand-waving analysis to see if the non-viability is due
12102 // to a qualifier mismatch.
12103 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12104 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12105 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12106 CToTy = RT->getPointeeType();
12107 else {
12108 // TODO: detect and diagnose the full richness of const mismatches.
12109 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12110 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12111 CFromTy = FromPT->getPointeeType();
12112 CToTy = ToPT->getPointeeType();
12113 }
12114 }
12115
12116 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12117 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12118 Qualifiers FromQs = CFromTy.getQualifiers();
12119 Qualifiers ToQs = CToTy.getQualifiers();
12120
12121 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12122 if (isObjectArgument)
12123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12124 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12125 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12126 else
12127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12128 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12129 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12130 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12131 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12132 return;
12133 }
12134
12135 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12136 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12137 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12138 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12139 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12140 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12141 return;
12142 }
12143
12144 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12146 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12147 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12148 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12149 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12150 return;
12151 }
12152
12153 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12154 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12155 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12156 << FromTy << !!FromQs.getPointerAuth()
12157 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12158 << ToQs.getPointerAuth().getAsString() << I + 1
12159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12160 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12161 return;
12162 }
12163
12164 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12165 assert(CVR && "expected qualifiers mismatch");
12166
12167 if (isObjectArgument) {
12168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12169 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12170 << FromTy << (CVR - 1);
12171 } else {
12172 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12173 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12174 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12175 }
12176 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12177 return;
12178 }
12179
12182 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12183 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12184 << (unsigned)isObjectArgument << I + 1
12186 << ToParamRange;
12187 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12188 return;
12189 }
12190
12191 // Special diagnostic for failure to convert an initializer list, since
12192 // telling the user that it has type void is not useful.
12193 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12195 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12196 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12199 ? 2
12200 : 0);
12201 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12202 return;
12203 }
12204
12205 // Diagnose references or pointers to incomplete types differently,
12206 // since it's far from impossible that the incompleteness triggered
12207 // the failure.
12208 QualType TempFromTy = FromTy.getNonReferenceType();
12209 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12210 TempFromTy = PTy->getPointeeType();
12211 if (TempFromTy->isIncompleteType()) {
12212 // Emit the generic diagnostic and, optionally, add the hints to it.
12213 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12214 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12215 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12216 << (unsigned)(Cand->Fix.Kind);
12217
12218 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12219 return;
12220 }
12221
12222 // Diagnose base -> derived pointer conversions.
12223 unsigned BaseToDerivedConversion = 0;
12224 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12225 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12226 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12227 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12228 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12229 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12230 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12231 FromPtrTy->getPointeeType()))
12232 BaseToDerivedConversion = 1;
12233 }
12234 } else if (const ObjCObjectPointerType *FromPtrTy
12235 = FromTy->getAs<ObjCObjectPointerType>()) {
12236 if (const ObjCObjectPointerType *ToPtrTy
12237 = ToTy->getAs<ObjCObjectPointerType>())
12238 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12239 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12240 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12241 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12242 FromIface->isSuperClassOf(ToIface))
12243 BaseToDerivedConversion = 2;
12244 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12245 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12246 S.getASTContext()) &&
12247 !FromTy->isIncompleteType() &&
12248 !ToRefTy->getPointeeType()->isIncompleteType() &&
12249 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12250 BaseToDerivedConversion = 3;
12251 }
12252 }
12253
12254 if (BaseToDerivedConversion) {
12255 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12256 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12257 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12258 << I + 1;
12259 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12260 return;
12261 }
12262
12263 if (isa<ObjCObjectPointerType>(CFromTy) &&
12264 isa<PointerType>(CToTy)) {
12265 Qualifiers FromQs = CFromTy.getQualifiers();
12266 Qualifiers ToQs = CToTy.getQualifiers();
12267 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12269 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12270 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12271 << I + 1;
12272 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12273 return;
12274 }
12275 }
12276
12277 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12278 return;
12279
12280 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12281 // although this is almost always an error and we advise against it.
12282 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12283 ToTy == S.Context.getLogicalOperationType()) {
12284 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12285 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12286 << Conv.Bad.FromExpr << ToTy;
12287 return;
12288 }
12289
12290 // Emit the generic diagnostic and, optionally, add the hints to it.
12291 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12292 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12293 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12294 << (unsigned)(Cand->Fix.Kind);
12295
12296 // Check that location of Fn is not in system header.
12297 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12298 // If we can fix the conversion, suggest the FixIts.
12299 for (const FixItHint &HI : Cand->Fix.Hints)
12300 FDiag << HI;
12301 }
12302
12303 S.Diag(Fn->getLocation(), FDiag);
12304
12305 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12306}
12307
12308/// Additional arity mismatch diagnosis specific to a function overload
12309/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12310/// over a candidate in any candidate set.
12312 unsigned NumArgs, bool IsAddressOf = false) {
12313 assert(Cand->Function && "Candidate is required to be a function.");
12314 FunctionDecl *Fn = Cand->Function;
12315 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12316 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12317
12318 // With invalid overloaded operators, it's possible that we think we
12319 // have an arity mismatch when in fact it looks like we have the
12320 // right number of arguments, because only overloaded operators have
12321 // the weird behavior of overloading member and non-member functions.
12322 // Just don't report anything.
12323 if (Fn->isInvalidDecl() &&
12324 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12325 return true;
12326
12327 if (NumArgs < MinParams) {
12328 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12330 Cand->DeductionFailure.getResult() ==
12332 } else {
12333 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12335 Cand->DeductionFailure.getResult() ==
12337 }
12338
12339 return false;
12340}
12341
12342/// General arity mismatch diagnosis over a candidate in a candidate set.
12344 unsigned NumFormalArgs,
12345 bool IsAddressOf = false) {
12346 assert(isa<FunctionDecl>(D) &&
12347 "The templated declaration should at least be a function"
12348 " when diagnosing bad template argument deduction due to too many"
12349 " or too few arguments");
12350
12352
12353 // TODO: treat calls to a missing default constructor as a special case
12354 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12355 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12356 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12357
12358 // at least / at most / exactly
12359 bool HasExplicitObjectParam =
12360 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12361
12362 unsigned ParamCount =
12363 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12364 unsigned mode, modeCount;
12365
12366 if (NumFormalArgs < MinParams) {
12367 if (MinParams != ParamCount || FnTy->isVariadic() ||
12368 FnTy->isTemplateVariadic())
12369 mode = 0; // "at least"
12370 else
12371 mode = 2; // "exactly"
12372 modeCount = MinParams;
12373 } else {
12374 if (MinParams != ParamCount)
12375 mode = 1; // "at most"
12376 else
12377 mode = 2; // "exactly"
12378 modeCount = ParamCount;
12379 }
12380
12381 std::string Description;
12382 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12383 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12384
12385 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12386 if (modeCount == 1 && !IsAddressOf &&
12387 FirstNonObjectParamIdx < Fn->getNumParams() &&
12388 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12389 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12390 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12391 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12392 << NumFormalArgs << HasExplicitObjectParam
12393 << Fn->getParametersSourceRange();
12394 else
12395 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12396 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12397 << Description << mode << modeCount << NumFormalArgs
12398 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12399
12400 MaybeEmitInheritedConstructorNote(S, Found);
12401}
12402
12403/// Arity mismatch diagnosis specific to a function overload candidate.
12405 unsigned NumFormalArgs) {
12406 assert(Cand->Function && "Candidate must be a function");
12407 FunctionDecl *Fn = Cand->Function;
12408 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12409 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12410 Cand->TookAddressOfOverload);
12411}
12412
12414 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12415 return TD;
12416 llvm_unreachable("Unsupported: Getting the described template declaration"
12417 " for bad deduction diagnosis");
12418}
12419
12420/// Diagnose a failed template-argument deduction.
12421static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12422 DeductionFailureInfo &DeductionFailure,
12423 unsigned NumArgs, bool TakingCandidateAddress,
12424 TemplateSpecCandidateSetKind CandidateSetKind =
12426 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12427 NamedDecl *ParamD;
12428 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12429 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12430 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12431 switch (DeductionFailure.getResult()) {
12433 llvm_unreachable(
12434 "TemplateDeductionResult::Success while diagnosing bad deduction");
12436 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12437 "while diagnosing bad deduction");
12440 return;
12441
12443 assert(ParamD && "no parameter found for incomplete deduction result");
12444 S.Diag(Templated->getLocation(),
12445 diag::note_ovl_candidate_incomplete_deduction)
12446 << ParamD->getDeclName();
12447 MaybeEmitInheritedConstructorNote(S, Found);
12448 return;
12449 }
12450
12452 assert(ParamD && "no parameter found for incomplete deduction result");
12453 S.Diag(Templated->getLocation(),
12454 diag::note_ovl_candidate_incomplete_deduction_pack)
12455 << ParamD->getDeclName()
12456 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12457 << *DeductionFailure.getFirstArg();
12458 MaybeEmitInheritedConstructorNote(S, Found);
12459 return;
12460 }
12461
12463 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12465
12466 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12467
12468 // Param will have been canonicalized, but it should just be a
12469 // qualified version of ParamD, so move the qualifiers to that.
12471 Qs.strip(Param);
12472 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12473 assert(S.Context.hasSameType(Param, NonCanonParam));
12474
12475 // Arg has also been canonicalized, but there's nothing we can do
12476 // about that. It also doesn't matter as much, because it won't
12477 // have any template parameters in it (because deduction isn't
12478 // done on dependent types).
12479 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12480
12481 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12482 << ParamD->getDeclName() << Arg << NonCanonParam;
12483 MaybeEmitInheritedConstructorNote(S, Found);
12484 return;
12485 }
12486
12488 assert(ParamD && "no parameter found for inconsistent deduction result");
12489 int which = 0;
12490 if (isa<TemplateTypeParmDecl>(ParamD))
12491 which = 0;
12492 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12493 // Deduction might have failed because we deduced arguments of two
12494 // different types for a non-type template parameter.
12495 // FIXME: Use a different TDK value for this.
12496 QualType T1 =
12497 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12498 QualType T2 =
12499 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12500 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12501 S.Diag(Templated->getLocation(),
12502 diag::note_ovl_candidate_inconsistent_deduction_types)
12503 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12504 << *DeductionFailure.getSecondArg() << T2;
12505 MaybeEmitInheritedConstructorNote(S, Found);
12506 return;
12507 }
12508
12509 which = 1;
12510 } else {
12511 which = 2;
12512 }
12513
12514 // Tweak the diagnostic if the problem is that we deduced packs of
12515 // different arities. We'll print the actual packs anyway in case that
12516 // includes additional useful information.
12517 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12518 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12519 DeductionFailure.getFirstArg()->pack_size() !=
12520 DeductionFailure.getSecondArg()->pack_size()) {
12521 which = 3;
12522 }
12523
12524 S.Diag(Templated->getLocation(),
12525 diag::note_ovl_candidate_inconsistent_deduction)
12526 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12527 << *DeductionFailure.getSecondArg();
12528 MaybeEmitInheritedConstructorNote(S, Found);
12529 return;
12530 }
12531
12533 assert(ParamD && "no parameter found for invalid explicit arguments");
12534
12535 auto Diag = S.Diag(Templated->getLocation(),
12536 diag::note_ovl_candidate_explicit_arg_mismatch);
12537 if (ParamD->getDeclName())
12538 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12539 else
12540 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12541 << (getDepthAndIndex(ParamD).second + 1);
12542 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12543 SmallString<128> DiagContent;
12544 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12545 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12546 } else {
12547 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12548 }
12549
12550 MaybeEmitInheritedConstructorNote(S, Found);
12551 return;
12552 }
12554 // Format the template argument list into the argument string.
12555 SmallString<128> TemplateArgString;
12556 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12557 TemplateArgString = " ";
12558 TemplateArgString += S.getTemplateArgumentBindingsText(
12559 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12560 if (TemplateArgString.size() == 1)
12561 TemplateArgString.clear();
12562 S.Diag(Templated->getLocation(),
12563 diag::note_ovl_candidate_unsatisfied_constraints)
12564 << TemplateArgString;
12565
12567 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12568 return;
12569 }
12572 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12573 return;
12574
12576 S.Diag(Templated->getLocation(),
12577 diag::note_ovl_candidate_instantiation_depth);
12578 MaybeEmitInheritedConstructorNote(S, Found);
12579 return;
12580
12582 // Format the template argument list into the argument string.
12583 SmallString<128> TemplateArgString;
12584 if (TemplateArgumentList *Args =
12585 DeductionFailure.getTemplateArgumentList()) {
12586 TemplateArgString = " ";
12587 TemplateArgString += S.getTemplateArgumentBindingsText(
12588 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12589 if (TemplateArgString.size() == 1)
12590 TemplateArgString.clear();
12591 }
12592
12593 // If this candidate was disabled by enable_if, say so.
12594 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12595 if (PDiag && PDiag->second.getDiagID() ==
12596 diag::err_typename_nested_not_found_enable_if) {
12597 // FIXME: Use the source range of the condition, and the fully-qualified
12598 // name of the enable_if template. These are both present in PDiag.
12599 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12600 << "'enable_if'" << TemplateArgString;
12601 return;
12602 }
12603
12604 // We found a specific requirement that disabled the enable_if.
12605 if (PDiag && PDiag->second.getDiagID() ==
12606 diag::err_typename_nested_not_found_requirement) {
12607 S.Diag(Templated->getLocation(),
12608 diag::note_ovl_candidate_disabled_by_requirement)
12609 << PDiag->second.getStringArg(0) << TemplateArgString;
12610 return;
12611 }
12612
12613 // Format the SFINAE diagnostic into the argument string.
12614 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12615 // formatted message in another diagnostic.
12616 SmallString<128> SFINAEArgString;
12617 SourceRange R;
12618 if (PDiag) {
12619 SFINAEArgString = ": ";
12620 R = SourceRange(PDiag->first, PDiag->first);
12621 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12622 }
12623
12624 S.Diag(Templated->getLocation(),
12625 diag::note_ovl_candidate_substitution_failure)
12626 << TemplateArgString << SFINAEArgString << R;
12627 MaybeEmitInheritedConstructorNote(S, Found);
12628 return;
12629 }
12630
12633 // Format the template argument list into the argument string.
12634 SmallString<128> TemplateArgString;
12635 if (TemplateArgumentList *Args =
12636 DeductionFailure.getTemplateArgumentList()) {
12637 TemplateArgString = " ";
12638 TemplateArgString += S.getTemplateArgumentBindingsText(
12639 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12640 if (TemplateArgString.size() == 1)
12641 TemplateArgString.clear();
12642 }
12643
12644 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12645 << (*DeductionFailure.getCallArgIndex() + 1)
12646 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12647 << TemplateArgString
12648 << (DeductionFailure.getResult() ==
12650 break;
12651 }
12652
12654 // FIXME: Provide a source location to indicate what we couldn't match.
12655 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12656 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12657 if (FirstTA.getKind() == TemplateArgument::Template &&
12658 SecondTA.getKind() == TemplateArgument::Template) {
12659 TemplateName FirstTN = FirstTA.getAsTemplate();
12660 TemplateName SecondTN = SecondTA.getAsTemplate();
12661 if (FirstTN.getKind() == TemplateName::Template &&
12662 SecondTN.getKind() == TemplateName::Template) {
12663 if (FirstTN.getAsTemplateDecl()->getName() ==
12664 SecondTN.getAsTemplateDecl()->getName()) {
12665 // FIXME: This fixes a bad diagnostic where both templates are named
12666 // the same. This particular case is a bit difficult since:
12667 // 1) It is passed as a string to the diagnostic printer.
12668 // 2) The diagnostic printer only attempts to find a better
12669 // name for types, not decls.
12670 // Ideally, this should folded into the diagnostic printer.
12671 S.Diag(Templated->getLocation(),
12672 CandidateSetKind ==
12674 ? diag::note_friend_template_non_deduced_mismatch_qualified
12675 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12676 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12677 return;
12678 }
12679 }
12680 }
12681
12682 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12684 return;
12685
12686 // FIXME: For generic lambda parameters, check if the function is a lambda
12687 // call operator, and if so, emit a prettier and more informative
12688 // diagnostic that mentions 'auto' and lambda in addition to
12689 // (or instead of?) the canonical template type parameters.
12690 S.Diag(Templated->getLocation(),
12692 ? diag::note_friend_template_non_deduced_mismatch
12693 : diag::note_ovl_candidate_non_deduced_mismatch)
12694 << FirstTA << SecondTA;
12695 return;
12696 }
12697 // TODO: diagnose these individually, then kill off
12698 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12700 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12701 MaybeEmitInheritedConstructorNote(S, Found);
12702 return;
12704 S.Diag(Templated->getLocation(),
12705 diag::note_cuda_ovl_candidate_target_mismatch);
12706 return;
12707 }
12708}
12709
12710/// Diagnose a failed template-argument deduction, for function calls.
12712 unsigned NumArgs,
12713 bool TakingCandidateAddress) {
12714 assert(Cand->Function && "Candidate must be a function");
12715 FunctionDecl *Fn = Cand->Function;
12719 if (CheckArityMismatch(S, Cand, NumArgs))
12720 return;
12721 }
12722 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12723 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12724}
12725
12726/// CUDA: diagnose an invalid call across targets.
12728 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12729 assert(Cand->Function && "Candidate must be a Function.");
12730 FunctionDecl *Callee = Cand->Function;
12731
12732 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12733 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12734
12735 std::string FnDesc;
12736 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12737 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12738 Cand->getRewriteKind(), FnDesc);
12739
12740 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12741 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12742 << FnDesc /* Ignored */
12743 << CalleeTarget << CallerTarget;
12744
12745 // This could be an implicit constructor for which we could not infer the
12746 // target due to a collsion. Diagnose that case.
12747 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12748 if (Meth != nullptr && Meth->isImplicit()) {
12749 CXXRecordDecl *ParentClass = Meth->getParent();
12751
12752 switch (FnKindPair.first) {
12753 default:
12754 return;
12755 case oc_implicit_default_constructor:
12757 break;
12758 case oc_implicit_copy_constructor:
12760 break;
12761 case oc_implicit_move_constructor:
12763 break;
12764 case oc_implicit_copy_assignment:
12766 break;
12767 case oc_implicit_move_assignment:
12769 break;
12770 };
12771
12772 bool ConstRHS = false;
12773 if (Meth->getNumParams()) {
12774 if (const ReferenceType *RT =
12775 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12776 ConstRHS = RT->getPointeeType().isConstQualified();
12777 }
12778 }
12779
12780 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12781 /* ConstRHS */ ConstRHS,
12782 /* Diagnose */ true);
12783 }
12784}
12785
12787 assert(Cand->Function && "Candidate must be a function");
12788 FunctionDecl *Callee = Cand->Function;
12789 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12790
12791 S.Diag(Callee->getLocation(),
12792 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12793 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12794}
12795
12797 assert(Cand->Function && "Candidate must be a function");
12798 FunctionDecl *Fn = Cand->Function;
12800 assert(ES.isExplicit() && "not an explicit candidate");
12801
12802 unsigned Kind;
12803 switch (Fn->getDeclKind()) {
12804 case Decl::Kind::CXXConstructor:
12805 Kind = 0;
12806 break;
12807 case Decl::Kind::CXXConversion:
12808 Kind = 1;
12809 break;
12810 case Decl::Kind::CXXDeductionGuide:
12811 Kind = Fn->isImplicit() ? 0 : 2;
12812 break;
12813 default:
12814 llvm_unreachable("invalid Decl");
12815 }
12816
12817 // Note the location of the first (in-class) declaration; a redeclaration
12818 // (particularly an out-of-class definition) will typically lack the
12819 // 'explicit' specifier.
12820 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12821 FunctionDecl *First = Fn->getFirstDecl();
12822 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12823 First = Pattern->getFirstDecl();
12824
12825 S.Diag(First->getLocation(),
12826 diag::note_ovl_candidate_explicit)
12827 << Kind << (ES.getExpr() ? 1 : 0)
12828 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12829}
12830
12832 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12833 if (!DG)
12834 return;
12835 TemplateDecl *OriginTemplate =
12837 // We want to always print synthesized deduction guides for type aliases.
12838 // They would retain the explicit bit of the corresponding constructor.
12839 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12840 return;
12841 std::string FunctionProto;
12842 llvm::raw_string_ostream OS(FunctionProto);
12843 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12844 if (!Template) {
12845 // This also could be an instantiation. Find out the primary template.
12846 FunctionDecl *Pattern =
12847 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12848 if (!Pattern) {
12849 // The implicit deduction guide is built on an explicit non-template
12850 // deduction guide. Currently, this might be the case only for type
12851 // aliases.
12852 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12853 // gets merged.
12854 assert(OriginTemplate->isTypeAlias() &&
12855 "Non-template implicit deduction guides are only possible for "
12856 "type aliases");
12857 DG->print(OS);
12858 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12859 << FunctionProto;
12860 return;
12861 }
12863 assert(Template && "Cannot find the associated function template of "
12864 "CXXDeductionGuideDecl?");
12865 }
12866 Template->print(OS);
12867 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12868 << FunctionProto;
12869}
12870
12871/// Generates a 'note' diagnostic for an overload candidate. We've
12872/// already generated a primary error at the call site.
12873///
12874/// It really does need to be a single diagnostic with its caret
12875/// pointed at the candidate declaration. Yes, this creates some
12876/// major challenges of technical writing. Yes, this makes pointing
12877/// out problems with specific arguments quite awkward. It's still
12878/// better than generating twenty screens of text for every failed
12879/// overload.
12880///
12881/// It would be great to be able to express per-candidate problems
12882/// more richly for those diagnostic clients that cared, but we'd
12883/// still have to be just as careful with the default diagnostics.
12884/// \param CtorDestAS Addr space of object being constructed (for ctor
12885/// candidates only).
12887 unsigned NumArgs,
12888 bool TakingCandidateAddress,
12889 LangAS CtorDestAS = LangAS::Default) {
12890 assert(Cand->Function && "Candidate must be a function");
12891 FunctionDecl *Fn = Cand->Function;
12893 return;
12894
12895 // There is no physical candidate declaration to point to for OpenCL builtins.
12896 // Except for failed conversions, the notes are identical for each candidate,
12897 // so do not generate such notes.
12898 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12900 return;
12901
12902 // Skip implicit member functions when trying to resolve
12903 // the address of a an overload set for a function pointer.
12904 if (Cand->TookAddressOfOverload &&
12905 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12906 return;
12907
12908 // Note deleted candidates, but only if they're viable.
12909 if (Cand->Viable) {
12910 if (Fn->isDeleted()) {
12911 std::string FnDesc;
12912 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12913 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12914 Cand->getRewriteKind(), FnDesc);
12915
12916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12917 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12918 << (Fn->isDeleted()
12919 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12920 : 0);
12921 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12922 return;
12923 }
12924
12925 // We don't really have anything else to say about viable candidates.
12926 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12927 return;
12928 }
12929
12930 // If this is a synthesized deduction guide we're deducing against, add a note
12931 // for it. These deduction guides are not explicitly spelled in the source
12932 // code, so simply printing a deduction failure note mentioning synthesized
12933 // template parameters or pointing to the header of the surrounding RecordDecl
12934 // would be confusing.
12935 //
12936 // We prefer adding such notes at the end of the deduction failure because
12937 // duplicate code snippets appearing in the diagnostic would likely become
12938 // noisy.
12939 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12940
12941 switch (Cand->FailureKind) {
12944 return DiagnoseArityMismatch(S, Cand, NumArgs);
12945
12947 return DiagnoseBadDeduction(S, Cand, NumArgs,
12948 TakingCandidateAddress);
12949
12951 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12952 << (Fn->getPrimaryTemplate() ? 1 : 0);
12953 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12954 return;
12955 }
12956
12958 Qualifiers QualsForPrinting;
12959 QualsForPrinting.setAddressSpace(CtorDestAS);
12960 S.Diag(Fn->getLocation(),
12961 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12962 << QualsForPrinting;
12963 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12964 return;
12965 }
12966
12970 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12971
12973 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12974 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12975 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12976 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12977
12978 // FIXME: this currently happens when we're called from SemaInit
12979 // when user-conversion overload fails. Figure out how to handle
12980 // those conditions and diagnose them well.
12981 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12982 }
12983
12985 return DiagnoseBadTarget(S, Cand);
12986
12987 case ovl_fail_enable_if:
12988 return DiagnoseFailedEnableIfAttr(S, Cand);
12989
12990 case ovl_fail_explicit:
12991 return DiagnoseFailedExplicitSpec(S, Cand);
12992
12994 // It's generally not interesting to note copy/move constructors here.
12995 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12996 return;
12997 S.Diag(Fn->getLocation(),
12998 diag::note_ovl_candidate_inherited_constructor_slice)
12999 << (Fn->getPrimaryTemplate() ? 1 : 0)
13000 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
13001 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13002 return;
13003
13005 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
13006 (void)Available;
13007 assert(!Available);
13008 break;
13009 }
13011 // Do nothing, these should simply be ignored.
13012 break;
13013
13015 std::string FnDesc;
13016 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13017 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13018 Cand->getRewriteKind(), FnDesc);
13019
13020 S.Diag(Fn->getLocation(),
13021 diag::note_ovl_candidate_constraints_not_satisfied)
13022 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13023 << FnDesc /* Ignored */;
13024 ConstraintSatisfaction Satisfaction;
13025 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13026 /*ForOverloadResolution=*/true))
13027 break;
13028 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13029 }
13030 }
13031}
13032
13035 return;
13036
13037 // Desugar the type of the surrogate down to a function type,
13038 // retaining as many typedefs as possible while still showing
13039 // the function type (and, therefore, its parameter types).
13040 QualType FnType = Cand->Surrogate->getConversionType();
13041 bool isLValueReference = false;
13042 bool isRValueReference = false;
13043 bool isPointer = false;
13044 if (const LValueReferenceType *FnTypeRef =
13045 FnType->getAs<LValueReferenceType>()) {
13046 FnType = FnTypeRef->getPointeeType();
13047 isLValueReference = true;
13048 } else if (const RValueReferenceType *FnTypeRef =
13049 FnType->getAs<RValueReferenceType>()) {
13050 FnType = FnTypeRef->getPointeeType();
13051 isRValueReference = true;
13052 }
13053 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13054 FnType = FnTypePtr->getPointeeType();
13055 isPointer = true;
13056 }
13057 // Desugar down to a function type.
13058 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13059 // Reconstruct the pointer/reference as appropriate.
13060 if (isPointer) FnType = S.Context.getPointerType(FnType);
13061 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13062 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13063
13064 if (!Cand->Viable &&
13066 S.Diag(Cand->Surrogate->getLocation(),
13067 diag::note_ovl_surrogate_constraints_not_satisfied)
13068 << Cand->Surrogate;
13069 ConstraintSatisfaction Satisfaction;
13070 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13071 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13072 } else {
13073 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13074 << FnType;
13075 }
13076}
13077
13078static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13079 SourceLocation OpLoc,
13080 OverloadCandidate *Cand) {
13081 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13082 std::string TypeStr("operator");
13083 TypeStr += Opc;
13084 TypeStr += "(";
13085 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13086 if (Cand->Conversions.size() == 1) {
13087 TypeStr += ")";
13088 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13089 } else {
13090 TypeStr += ", ";
13091 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13092 TypeStr += ")";
13093 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13094 }
13095}
13096
13098 OverloadCandidate *Cand) {
13099 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13100 if (ICS.isBad()) break; // all meaningless after first invalid
13101 if (!ICS.isAmbiguous()) continue;
13102
13104 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13105 }
13106}
13107
13109 if (Cand->Function)
13110 return Cand->Function->getLocation();
13111 if (Cand->IsSurrogate)
13112 return Cand->Surrogate->getLocation();
13113 return SourceLocation();
13114}
13115
13116static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13117 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13121 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13122
13126 return 1;
13127
13130 return 2;
13131
13139 return 3;
13140
13142 return 4;
13143
13145 return 5;
13146
13149 return 6;
13150 }
13151 llvm_unreachable("Unhandled deduction result");
13152}
13153
13154namespace {
13155
13156struct CompareOverloadCandidatesForDisplay {
13157 Sema &S;
13158 SourceLocation Loc;
13159 size_t NumArgs;
13161
13162 CompareOverloadCandidatesForDisplay(
13163 Sema &S, SourceLocation Loc, size_t NArgs,
13165 : S(S), NumArgs(NArgs), CSK(CSK) {}
13166
13167 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13168 // If there are too many or too few arguments, that's the high-order bit we
13169 // want to sort by, even if the immediate failure kind was something else.
13170 if (C->FailureKind == ovl_fail_too_many_arguments ||
13171 C->FailureKind == ovl_fail_too_few_arguments)
13172 return static_cast<OverloadFailureKind>(C->FailureKind);
13173
13174 if (C->Function) {
13175 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13177 if (NumArgs < C->Function->getMinRequiredArguments())
13179 }
13180
13181 return static_cast<OverloadFailureKind>(C->FailureKind);
13182 }
13183
13184 bool operator()(const OverloadCandidate *L,
13185 const OverloadCandidate *R) {
13186 // Fast-path this check.
13187 if (L == R) return false;
13188
13189 // Order first by viability.
13190 if (L->Viable) {
13191 if (!R->Viable) return true;
13192
13193 if (int Ord = CompareConversions(*L, *R))
13194 return Ord < 0;
13195 // Use other tie breakers.
13196 } else if (R->Viable)
13197 return false;
13198
13199 assert(L->Viable == R->Viable);
13200
13201 // Criteria by which we can sort non-viable candidates:
13202 if (!L->Viable) {
13203 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13204 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13205
13206 // 1. Arity mismatches come after other candidates.
13207 if (LFailureKind == ovl_fail_too_many_arguments ||
13208 LFailureKind == ovl_fail_too_few_arguments) {
13209 if (RFailureKind == ovl_fail_too_many_arguments ||
13210 RFailureKind == ovl_fail_too_few_arguments) {
13211 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13212 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13213 if (LDist == RDist) {
13214 if (LFailureKind == RFailureKind)
13215 // Sort non-surrogates before surrogates.
13216 return !L->IsSurrogate && R->IsSurrogate;
13217 // Sort candidates requiring fewer parameters than there were
13218 // arguments given after candidates requiring more parameters
13219 // than there were arguments given.
13220 return LFailureKind == ovl_fail_too_many_arguments;
13221 }
13222 return LDist < RDist;
13223 }
13224 return false;
13225 }
13226 if (RFailureKind == ovl_fail_too_many_arguments ||
13227 RFailureKind == ovl_fail_too_few_arguments)
13228 return true;
13229
13230 // 2. Bad conversions come first and are ordered by the number
13231 // of bad conversions and quality of good conversions.
13232 if (LFailureKind == ovl_fail_bad_conversion) {
13233 if (RFailureKind != ovl_fail_bad_conversion)
13234 return true;
13235
13236 // The conversion that can be fixed with a smaller number of changes,
13237 // comes first.
13238 unsigned numLFixes = L->Fix.NumConversionsFixed;
13239 unsigned numRFixes = R->Fix.NumConversionsFixed;
13240 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13241 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13242 if (numLFixes != numRFixes) {
13243 return numLFixes < numRFixes;
13244 }
13245
13246 // If there's any ordering between the defined conversions...
13247 if (int Ord = CompareConversions(*L, *R))
13248 return Ord < 0;
13249 } else if (RFailureKind == ovl_fail_bad_conversion)
13250 return false;
13251
13252 if (LFailureKind == ovl_fail_bad_deduction) {
13253 if (RFailureKind != ovl_fail_bad_deduction)
13254 return true;
13255
13256 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13257 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13258 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13259 if (LRank != RRank)
13260 return LRank < RRank;
13261 }
13262 } else if (RFailureKind == ovl_fail_bad_deduction)
13263 return false;
13264
13265 // TODO: others?
13266 }
13267
13268 // Sort everything else by location.
13269 SourceLocation LLoc = GetLocationForCandidate(L);
13270 SourceLocation RLoc = GetLocationForCandidate(R);
13271
13272 // Put candidates without locations (e.g. builtins) at the end.
13273 if (LLoc.isValid() && RLoc.isValid())
13274 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13275 if (LLoc.isValid() && !RLoc.isValid())
13276 return true;
13277 if (RLoc.isValid() && !LLoc.isValid())
13278 return false;
13279 assert(!LLoc.isValid() && !RLoc.isValid());
13280 // For builtins and other functions without locations, fallback to the order
13281 // in which they were added into the candidate set.
13282 return L < R;
13283 }
13284
13285private:
13286 struct ConversionSignals {
13287 unsigned KindRank = 0;
13289
13290 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13291 ConversionSignals Sig;
13292 Sig.KindRank = Seq.getKindRank();
13293 if (Seq.isStandard())
13294 Sig.Rank = Seq.Standard.getRank();
13295 else if (Seq.isUserDefined())
13296 Sig.Rank = Seq.UserDefined.After.getRank();
13297 // We intend StaticObjectArgumentConversion to compare the same as
13298 // StandardConversion with ICR_ExactMatch rank.
13299 return Sig;
13300 }
13301
13302 static ConversionSignals ForObjectArgument() {
13303 // We intend StaticObjectArgumentConversion to compare the same as
13304 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13305 return {};
13306 }
13307 };
13308
13309 // Returns -1 if conversions in L are considered better.
13310 // 0 if they are considered indistinguishable.
13311 // 1 if conversions in R are better.
13312 int CompareConversions(const OverloadCandidate &L,
13313 const OverloadCandidate &R) {
13314 // We cannot use `isBetterOverloadCandidate` because it is defined
13315 // according to the C++ standard and provides a partial order, but we need
13316 // a total order as this function is used in sort.
13317 assert(L.Conversions.size() == R.Conversions.size());
13318 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13319 auto LS = L.IgnoreObjectArgument && I == 0
13320 ? ConversionSignals::ForObjectArgument()
13321 : ConversionSignals::ForSequence(L.Conversions[I]);
13322 auto RS = R.IgnoreObjectArgument
13323 ? ConversionSignals::ForObjectArgument()
13324 : ConversionSignals::ForSequence(R.Conversions[I]);
13325 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13326 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13327 ? -1
13328 : 1;
13329 }
13330 // FIXME: find a way to compare templates for being more or less
13331 // specialized that provides a strict weak ordering.
13332 return 0;
13333 }
13334};
13335}
13336
13337/// CompleteNonViableCandidate - Normally, overload resolution only
13338/// computes up to the first bad conversion. Produces the FixIt set if
13339/// possible.
13340static void
13342 ArrayRef<Expr *> Args,
13344 assert(!Cand->Viable);
13345
13346 // Don't do anything on failures other than bad conversion.
13348 return;
13349
13350 // We only want the FixIts if all the arguments can be corrected.
13351 bool Unfixable = false;
13352 // Use a implicit copy initialization to check conversion fixes.
13354
13355 // Attempt to fix the bad conversion.
13356 unsigned ConvCount = Cand->Conversions.size();
13357 for (unsigned ConvIdx =
13358 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13359 : 0);
13360 /**/; ++ConvIdx) {
13361 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13362 if (Cand->Conversions[ConvIdx].isInitialized() &&
13363 Cand->Conversions[ConvIdx].isBad()) {
13364 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13365 break;
13366 }
13367 }
13368
13369 // FIXME: this should probably be preserved from the overload
13370 // operation somehow.
13371 bool SuppressUserConversions = false;
13372
13373 unsigned ConvIdx = 0;
13374 unsigned ArgIdx = 0;
13375 ArrayRef<QualType> ParamTypes;
13376 bool Reversed = Cand->isReversed();
13377
13378 if (Cand->IsSurrogate) {
13379 QualType ConvType
13381 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13382 ConvType = ConvPtrType->getPointeeType();
13383 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13384 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13385 ConvIdx = 1;
13386 } else if (Cand->Function) {
13387 ParamTypes =
13388 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13389 if (isa<CXXMethodDecl>(Cand->Function) &&
13392 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13393 ConvIdx = 1;
13395 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13397 OO_Subscript)
13398 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13399 ArgIdx = 1;
13400 }
13401 } else {
13402 // Builtin operator.
13403 assert(ConvCount <= 3);
13404 ParamTypes = Cand->BuiltinParamTypes;
13405 }
13406
13407 // Fill in the rest of the conversions.
13408 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13409 ConvIdx != ConvCount && ArgIdx < Args.size();
13410 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13411 if (Cand->Conversions[ConvIdx].isInitialized()) {
13412 // We've already checked this conversion.
13413 } else if (ParamIdx < ParamTypes.size()) {
13414 if (ParamTypes[ParamIdx]->isDependentType())
13415 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13416 Args[ArgIdx]->getType());
13417 else {
13418 Cand->Conversions[ConvIdx] =
13419 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13420 SuppressUserConversions,
13421 /*InOverloadResolution=*/true,
13422 /*AllowObjCWritebackConversion=*/
13423 S.getLangOpts().ObjCAutoRefCount);
13424 // Store the FixIt in the candidate if it exists.
13425 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13426 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13427 }
13428 } else
13429 Cand->Conversions[ConvIdx].setEllipsis();
13430 }
13431}
13432
13435 SourceLocation OpLoc,
13436 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13437
13439
13440 // Sort the candidates by viability and position. Sorting directly would
13441 // be prohibitive, so we make a set of pointers and sort those.
13443 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13444 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13445 Cand != LastCand; ++Cand) {
13446 if (!Filter(*Cand))
13447 continue;
13448 switch (OCD) {
13449 case OCD_AllCandidates:
13450 if (!Cand->Viable) {
13451 if (!Cand->Function && !Cand->IsSurrogate) {
13452 // This a non-viable builtin candidate. We do not, in general,
13453 // want to list every possible builtin candidate.
13454 continue;
13455 }
13456 CompleteNonViableCandidate(S, Cand, Args, Kind);
13457 }
13458 break;
13459
13461 if (!Cand->Viable)
13462 continue;
13463 break;
13464
13466 if (!Cand->Best)
13467 continue;
13468 break;
13469 }
13470
13471 Cands.push_back(Cand);
13472 }
13473
13474 llvm::stable_sort(
13475 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13476
13477 return Cands;
13478}
13479
13481 SourceLocation OpLoc) {
13482 bool DeferHint = false;
13483 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13484 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13485 // host device candidates.
13486 auto WrongSidedCands =
13487 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13488 return (Cand.Viable == false &&
13490 (Cand.Function &&
13491 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13492 Cand.Function->template hasAttr<CUDADeviceAttr>());
13493 });
13494 DeferHint = !WrongSidedCands.empty();
13495 }
13496 return DeferHint;
13497}
13498
13499/// When overload resolution fails, prints diagnostic messages containing the
13500/// candidates in the candidate set.
13503 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13504 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13505
13506 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13507
13508 {
13509 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13510 S.Diag(PD.first, PD.second);
13511 }
13512
13513 // In WebAssembly we don't want to emit further diagnostics if a table is
13514 // passed as an argument to a function.
13515 bool NoteCands = true;
13516 for (const Expr *Arg : Args) {
13517 if (Arg->getType()->isWebAssemblyTableType())
13518 NoteCands = false;
13519 }
13520
13521 if (NoteCands)
13522 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13523
13524 if (OCD == OCD_AmbiguousCandidates)
13526 {Candidates.begin(), Candidates.end()});
13527}
13528
13531 StringRef Opc, SourceLocation OpLoc) {
13532 bool ReportedAmbiguousConversions = false;
13533
13534 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13535 unsigned CandsShown = 0;
13536 auto I = Cands.begin(), E = Cands.end();
13537 for (; I != E; ++I) {
13538 OverloadCandidate *Cand = *I;
13539
13540 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13541 ShowOverloads == Ovl_Best) {
13542 break;
13543 }
13544 ++CandsShown;
13545
13546 if (Cand->Function)
13547 NoteFunctionCandidate(S, Cand, Args.size(),
13548 Kind == CSK_AddressOfOverloadSet, DestAS);
13549 else if (Cand->IsSurrogate)
13550 NoteSurrogateCandidate(S, Cand);
13551 else {
13552 assert(Cand->Viable &&
13553 "Non-viable built-in candidates are not added to Cands.");
13554 // Generally we only see ambiguities including viable builtin
13555 // operators if overload resolution got screwed up by an
13556 // ambiguous user-defined conversion.
13557 //
13558 // FIXME: It's quite possible for different conversions to see
13559 // different ambiguities, though.
13560 if (!ReportedAmbiguousConversions) {
13561 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13562 ReportedAmbiguousConversions = true;
13563 }
13564
13565 // If this is a viable builtin, print it.
13566 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13567 }
13568 }
13569
13570 // Inform S.Diags that we've shown an overload set with N elements. This may
13571 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13572 S.Diags.overloadCandidatesShown(CandsShown);
13573
13574 if (I != E) {
13575 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13576 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13577 }
13578}
13579
13581 const Sema &S) const {
13582 if (S.getLangOpts().CUDA) {
13583 auto *Caller = S.getCurFunctionDecl(true);
13584 // Overloading based on __host__ and __device__ attributes takes
13585 // higher priority, HD functions may favor template candidates even when a
13586 // non-template candidate would be a perfect match.
13587 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13588 Caller->hasAttr<CUDADeviceAttr>())
13589 return false;
13590 }
13591
13592 return
13593 // For user defined conversion we need to check against different
13594 // combination of CV qualifiers and look at any explicit specifier, so
13595 // always deduce template candidates.
13597 // When doing code completion, we want to see all the
13598 // viable candidates.
13599 && Kind != CSK_CodeCompletion;
13600}
13601
13602static SourceLocation
13604 return Cand->Specialization ? Cand->Specialization->getLocation()
13605 : SourceLocation();
13606}
13607
13608namespace {
13609struct CompareTemplateSpecCandidatesForDisplay {
13610 Sema &S;
13611 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13612
13613 bool operator()(const TemplateSpecCandidate *L,
13614 const TemplateSpecCandidate *R) {
13615 // Fast-path this check.
13616 if (L == R)
13617 return false;
13618
13619 // Assuming that both candidates are not matches...
13620
13621 // Sort by the ranking of deduction failures.
13622 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13624 RankDeductionFailure(R->DeductionFailure);
13625
13626 // Sort everything else by location.
13627 SourceLocation LLoc = GetLocationForCandidate(L);
13628 SourceLocation RLoc = GetLocationForCandidate(R);
13629
13630 // Put candidates without locations (e.g. builtins) at the end.
13631 if (LLoc.isInvalid())
13632 return false;
13633 if (RLoc.isInvalid())
13634 return true;
13635
13636 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13637 }
13638};
13639}
13640
13641/// Diagnose a template argument deduction failure.
13642/// We are treating these failures as overload failures due to bad
13643/// deductions.
13645 Sema &S, bool ForTakingAddress,
13646 TemplateSpecCandidateSetKind CandidateSetKind) {
13648 DeductionFailure, /*NumArgs=*/0, ForTakingAddress,
13649 CandidateSetKind);
13650}
13651
13652void TemplateSpecCandidateSet::destroyCandidates() {
13653 for (iterator i = begin(), e = end(); i != e; ++i) {
13654 i->DeductionFailure.Destroy();
13655 }
13656}
13657
13659 destroyCandidates();
13660 Candidates.clear();
13661}
13662
13663/// NoteCandidates - When no template specialization match is found, prints
13664/// diagnostic messages containing the non-matching specializations that form
13665/// the candidate set.
13666/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13667/// OCD == OCD_AllCandidates and Cand->Viable == false.
13669 // Sort the candidates by position (assuming no candidate is a match).
13670 // Sorting directly would be prohibitive, so we make a set of pointers
13671 // and sort those.
13673 Cands.reserve(size());
13674 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13675 if (Cand->Specialization)
13676 Cands.push_back(Cand);
13677 // Otherwise, this is a non-matching builtin candidate. We do not,
13678 // in general, want to list every possible builtin candidate.
13679 }
13680
13681 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13682
13683 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13684 // for generalization purposes (?).
13685 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13686
13688 unsigned CandsShown = 0;
13689 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13690 TemplateSpecCandidate *Cand = *I;
13691
13692 // Set an arbitrary limit on the number of candidates we'll spam
13693 // the user with. FIXME: This limit should depend on details of the
13694 // candidate list.
13695 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13696 break;
13697 ++CandsShown;
13698
13699 assert(Cand->Specialization &&
13700 "Non-matching built-in candidates are not added to Cands.");
13701 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13702 }
13703
13704 if (I != E)
13705 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13706}
13707
13708// [PossiblyAFunctionType] --> [Return]
13709// NonFunctionType --> NonFunctionType
13710// R (A) --> R(A)
13711// R (*)(A) --> R (A)
13712// R (&)(A) --> R (A)
13713// R (S::*)(A) --> R (A)
13715 QualType Ret = PossiblyAFunctionType;
13716 if (const PointerType *ToTypePtr =
13717 PossiblyAFunctionType->getAs<PointerType>())
13718 Ret = ToTypePtr->getPointeeType();
13719 else if (const ReferenceType *ToTypeRef =
13720 PossiblyAFunctionType->getAs<ReferenceType>())
13721 Ret = ToTypeRef->getPointeeType();
13722 else if (const MemberPointerType *MemTypePtr =
13723 PossiblyAFunctionType->getAs<MemberPointerType>())
13724 Ret = MemTypePtr->getPointeeType();
13725 Ret =
13726 Context.getCanonicalType(Ret).getUnqualifiedType();
13727 return Ret;
13728}
13729
13731 bool Complain = true) {
13732 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13733 S.DeduceReturnType(FD, Loc, Complain))
13734 return true;
13735
13736 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13737 if (S.getLangOpts().CPlusPlus17 &&
13738 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13739 !S.ResolveExceptionSpec(Loc, FPT))
13740 return true;
13741
13742 return false;
13743}
13744
13745namespace {
13746// A helper class to help with address of function resolution
13747// - allows us to avoid passing around all those ugly parameters
13748class AddressOfFunctionResolver {
13749 Sema& S;
13750 Expr* SourceExpr;
13751 const QualType& TargetType;
13752 QualType TargetFunctionType; // Extracted function type from target type
13753
13754 bool Complain;
13755 //DeclAccessPair& ResultFunctionAccessPair;
13756 ASTContext& Context;
13757
13758 bool TargetTypeIsNonStaticMemberFunction;
13759 bool FoundNonTemplateFunction;
13760 bool StaticMemberFunctionFromBoundPointer;
13761 bool HasComplained;
13762
13763 OverloadExpr::FindResult OvlExprInfo;
13764 OverloadExpr *OvlExpr;
13765 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13766 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13767 TemplateSpecCandidateSet FailedCandidates;
13768
13769public:
13770 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13771 const QualType &TargetType, bool Complain)
13772 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13773 Complain(Complain), Context(S.getASTContext()),
13774 TargetTypeIsNonStaticMemberFunction(
13775 !!TargetType->getAs<MemberPointerType>()),
13776 FoundNonTemplateFunction(false),
13777 StaticMemberFunctionFromBoundPointer(false),
13778 HasComplained(false),
13779 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13780 OvlExpr(OvlExprInfo.Expression),
13781 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13782 ExtractUnqualifiedFunctionTypeFromTargetType();
13783
13784 if (TargetFunctionType->isFunctionType()) {
13785 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13786 if (!UME->isImplicitAccess() &&
13788 StaticMemberFunctionFromBoundPointer = true;
13789 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13790 DeclAccessPair dap;
13791 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13792 OvlExpr, false, &dap)) {
13793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13794 if (!Method->isStatic()) {
13795 // If the target type is a non-function type and the function found
13796 // is a non-static member function, pretend as if that was the
13797 // target, it's the only possible type to end up with.
13798 TargetTypeIsNonStaticMemberFunction = true;
13799
13800 // And skip adding the function if its not in the proper form.
13801 // We'll diagnose this due to an empty set of functions.
13802 if (!OvlExprInfo.HasFormOfMemberPointer)
13803 return;
13804 }
13805
13806 Matches.push_back(std::make_pair(dap, Fn));
13807 }
13808 return;
13809 }
13810
13811 if (OvlExpr->hasExplicitTemplateArgs())
13812 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13813
13814 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13815 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13816 EliminateSuboptimalCudaMatches();
13817
13818 // C++ [over.over]p4:
13819 // If more than one function is selected, [...]
13820 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13821 if (FoundNonTemplateFunction) {
13822 EliminateAllTemplateMatches();
13823 EliminateLessPartialOrderingConstrainedMatches();
13824 } else
13825 EliminateAllExceptMostSpecializedTemplate();
13826 }
13827 }
13828 }
13829
13830 bool hasComplained() const { return HasComplained; }
13831
13832private:
13833 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13834 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13835 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13836 }
13837
13838 /// \return true if A is considered a better overload candidate for the
13839 /// desired type than B.
13840 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13841 // If A doesn't have exactly the correct type, we don't want to classify it
13842 // as "better" than anything else. This way, the user is required to
13843 // disambiguate for us if there are multiple candidates and no exact match.
13844 return candidateHasExactlyCorrectType(A) &&
13845 (!candidateHasExactlyCorrectType(B) ||
13846 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13847 }
13848
13849 /// \return true if we were able to eliminate all but one overload candidate,
13850 /// false otherwise.
13851 bool eliminiateSuboptimalOverloadCandidates() {
13852 // Same algorithm as overload resolution -- one pass to pick the "best",
13853 // another pass to be sure that nothing is better than the best.
13854 auto Best = Matches.begin();
13855 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13856 if (isBetterCandidate(I->second, Best->second))
13857 Best = I;
13858
13859 const FunctionDecl *BestFn = Best->second;
13860 auto IsBestOrInferiorToBest = [this, BestFn](
13861 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13862 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13863 };
13864
13865 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13866 // option, so we can potentially give the user a better error
13867 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13868 return false;
13869 Matches[0] = *Best;
13870 Matches.resize(1);
13871 return true;
13872 }
13873
13874 bool isTargetTypeAFunction() const {
13875 return TargetFunctionType->isFunctionType();
13876 }
13877
13878 // [ToType] [Return]
13879
13880 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13881 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13882 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13883 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13884 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13885 }
13886
13887 // return true if any matching specializations were found
13888 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13889 const DeclAccessPair& CurAccessFunPair) {
13890 if (CXXMethodDecl *Method
13891 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13892 // Skip non-static function templates when converting to pointer, and
13893 // static when converting to member pointer.
13894 bool CanConvertToFunctionPointer =
13895 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13896 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13897 return false;
13898 }
13899 else if (TargetTypeIsNonStaticMemberFunction)
13900 return false;
13901
13902 // C++ [over.over]p2:
13903 // If the name is a function template, template argument deduction is
13904 // done (14.8.2.2), and if the argument deduction succeeds, the
13905 // resulting template argument list is used to generate a single
13906 // function template specialization, which is added to the set of
13907 // overloaded functions considered.
13908 FunctionDecl *Specialization = nullptr;
13909 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13911 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13912 Specialization, Info, /*IsAddressOfFunction*/ true);
13913 Result != TemplateDeductionResult::Success) {
13914 // Make a note of the failed deduction for diagnostics.
13915 FailedCandidates.addCandidate()
13916 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13917 MakeDeductionFailureInfo(Context, Result, Info));
13918 return false;
13919 }
13920
13921 // Template argument deduction ensures that we have an exact match or
13922 // compatible pointer-to-function arguments that would be adjusted by ICS.
13923 // This function template specicalization works.
13925 Context.getCanonicalType(Specialization->getType()),
13926 Context.getCanonicalType(TargetFunctionType)));
13927
13929 return false;
13930
13931 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13932 return true;
13933 }
13934
13935 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13936 const DeclAccessPair& CurAccessFunPair) {
13937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13938 // Skip non-static functions when converting to pointer, and static
13939 // when converting to member pointer.
13940 bool CanConvertToFunctionPointer =
13941 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13942 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13943 return false;
13944 }
13945 else if (TargetTypeIsNonStaticMemberFunction)
13946 return false;
13947
13948 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13949 if (S.getLangOpts().CUDA) {
13950 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13951 if (!(Caller && Caller->isImplicit()) &&
13952 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13953 return false;
13954 }
13955 if (FunDecl->isMultiVersion()) {
13956 const auto *TA = FunDecl->getAttr<TargetAttr>();
13957 if (TA && !TA->isDefaultVersion())
13958 return false;
13959 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13960 if (TVA && !TVA->isDefaultVersion())
13961 return false;
13962 }
13963
13964 // If any candidate has a placeholder return type, trigger its deduction
13965 // now.
13966 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13967 Complain)) {
13968 HasComplained |= Complain;
13969 return false;
13970 }
13971
13972 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13973 return false;
13974
13975 // If we're in C, we need to support types that aren't exactly identical.
13976 if (!S.getLangOpts().CPlusPlus ||
13977 candidateHasExactlyCorrectType(FunDecl)) {
13978 Matches.push_back(std::make_pair(
13979 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13980 FoundNonTemplateFunction = true;
13981 return true;
13982 }
13983 }
13984
13985 return false;
13986 }
13987
13988 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13989 bool Ret = false;
13990
13991 // If the overload expression doesn't have the form of a pointer to
13992 // member, don't try to convert it to a pointer-to-member type.
13993 if (IsInvalidFormOfPointerToMemberFunction())
13994 return false;
13995
13996 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13997 E = OvlExpr->decls_end();
13998 I != E; ++I) {
13999 // Look through any using declarations to find the underlying function.
14000 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14001
14002 // C++ [over.over]p3:
14003 // Non-member functions and static member functions match
14004 // targets of type "pointer-to-function" or "reference-to-function."
14005 // Nonstatic member functions match targets of
14006 // type "pointer-to-member-function."
14007 // Note that according to DR 247, the containing class does not matter.
14008 if (FunctionTemplateDecl *FunctionTemplate
14009 = dyn_cast<FunctionTemplateDecl>(Fn)) {
14010 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
14011 Ret = true;
14012 }
14013 // If we have explicit template arguments supplied, skip non-templates.
14014 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14015 AddMatchingNonTemplateFunction(Fn, I.getPair()))
14016 Ret = true;
14017 }
14018 assert(Ret || Matches.empty());
14019 return Ret;
14020 }
14021
14022 void EliminateAllExceptMostSpecializedTemplate() {
14023 // [...] and any given function template specialization F1 is
14024 // eliminated if the set contains a second function template
14025 // specialization whose function template is more specialized
14026 // than the function template of F1 according to the partial
14027 // ordering rules of 14.5.5.2.
14028
14029 // The algorithm specified above is quadratic. We instead use a
14030 // two-pass algorithm (similar to the one used to identify the
14031 // best viable function in an overload set) that identifies the
14032 // best function template (if it exists).
14033
14034 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14035 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14036 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14037
14038 // TODO: It looks like FailedCandidates does not serve much purpose
14039 // here, since the no_viable diagnostic has index 0.
14040 UnresolvedSetIterator Result = S.getMostSpecialized(
14041 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14042 SourceExpr->getBeginLoc(), S.PDiag(),
14043 S.PDiag(diag::err_addr_ovl_ambiguous)
14044 << Matches[0].second->getDeclName(),
14045 S.PDiag(diag::note_ovl_candidate)
14046 << (unsigned)oc_function << (unsigned)ocs_described_template,
14047 Complain, TargetFunctionType);
14048
14049 if (Result != MatchesCopy.end()) {
14050 // Make it the first and only element
14051 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14052 Matches[0].second = cast<FunctionDecl>(*Result);
14053 Matches.resize(1);
14054 } else
14055 HasComplained |= Complain;
14056 }
14057
14058 void EliminateAllTemplateMatches() {
14059 // [...] any function template specializations in the set are
14060 // eliminated if the set also contains a non-template function, [...]
14061 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14062 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14063 ++I;
14064 else {
14065 Matches[I] = Matches[--N];
14066 Matches.resize(N);
14067 }
14068 }
14069 }
14070
14071 void EliminateLessPartialOrderingConstrainedMatches() {
14072 // C++ [over.over]p5:
14073 // [...] Any given non-template function F0 is eliminated if the set
14074 // contains a second non-template function that is more
14075 // partial-ordering-constrained than F0. [...]
14076 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14077 "Call EliminateAllTemplateMatches() first");
14078 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14079 Results.push_back(Matches[0]);
14080 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14081 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14082 FunctionDecl *F = getMorePartialOrderingConstrained(
14083 S, Matches[I].second, Results[0].second,
14084 /*IsFn1Reversed=*/false,
14085 /*IsFn2Reversed=*/false);
14086 if (!F) {
14087 Results.push_back(Matches[I]);
14088 continue;
14089 }
14090 if (F == Matches[I].second) {
14091 Results.clear();
14092 Results.push_back(Matches[I]);
14093 }
14094 }
14095 std::swap(Matches, Results);
14096 }
14097
14098 void EliminateSuboptimalCudaMatches() {
14099 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14100 Matches);
14101 }
14102
14103public:
14104 void ComplainNoMatchesFound() const {
14105 assert(Matches.empty());
14106 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14107 << OvlExpr->getName() << TargetFunctionType
14108 << OvlExpr->getSourceRange();
14109 if (FailedCandidates.empty())
14110 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14111 /*TakingAddress=*/true);
14112 else {
14113 // We have some deduction failure messages. Use them to diagnose
14114 // the function templates, and diagnose the non-template candidates
14115 // normally.
14116 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14117 IEnd = OvlExpr->decls_end();
14118 I != IEnd; ++I)
14119 if (FunctionDecl *Fun =
14120 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14122 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14123 /*TakingAddress=*/true);
14124 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14125 }
14126 }
14127
14128 bool IsInvalidFormOfPointerToMemberFunction() const {
14129 return TargetTypeIsNonStaticMemberFunction &&
14130 !OvlExprInfo.HasFormOfMemberPointer;
14131 }
14132
14133 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14134 // TODO: Should we condition this on whether any functions might
14135 // have matched, or is it more appropriate to do that in callers?
14136 // TODO: a fixit wouldn't hurt.
14137 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14138 << TargetType << OvlExpr->getSourceRange();
14139 }
14140
14141 bool IsStaticMemberFunctionFromBoundPointer() const {
14142 return StaticMemberFunctionFromBoundPointer;
14143 }
14144
14145 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14146 S.Diag(OvlExpr->getBeginLoc(),
14147 diag::err_invalid_form_pointer_member_function)
14148 << OvlExpr->getSourceRange();
14149 }
14150
14151 void ComplainOfInvalidConversion() const {
14152 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14153 << OvlExpr->getName() << TargetType;
14154 }
14155
14156 void ComplainMultipleMatchesFound() const {
14157 assert(Matches.size() > 1);
14158 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14159 << OvlExpr->getName() << OvlExpr->getSourceRange();
14160 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14161 /*TakingAddress=*/true);
14162 }
14163
14164 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14165
14166 int getNumMatches() const { return Matches.size(); }
14167
14168 FunctionDecl* getMatchingFunctionDecl() const {
14169 if (Matches.size() != 1) return nullptr;
14170 return Matches[0].second;
14171 }
14172
14173 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14174 if (Matches.size() != 1) return nullptr;
14175 return &Matches[0].first;
14176 }
14177};
14178}
14179
14180FunctionDecl *
14182 QualType TargetType,
14183 bool Complain,
14184 DeclAccessPair &FoundResult,
14185 bool *pHadMultipleCandidates) {
14186 assert(AddressOfExpr->getType() == Context.OverloadTy);
14187
14188 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14189 Complain);
14190 int NumMatches = Resolver.getNumMatches();
14191 FunctionDecl *Fn = nullptr;
14192 bool ShouldComplain = Complain && !Resolver.hasComplained();
14193 if (NumMatches == 0 && ShouldComplain) {
14194 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14195 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14196 else
14197 Resolver.ComplainNoMatchesFound();
14198 }
14199 else if (NumMatches > 1 && ShouldComplain)
14200 Resolver.ComplainMultipleMatchesFound();
14201 else if (NumMatches == 1) {
14202 Fn = Resolver.getMatchingFunctionDecl();
14203 assert(Fn);
14204 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14205 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14206 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14207 if (Complain) {
14208 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14209 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14210 else
14211 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14212 }
14213 }
14214
14215 if (pHadMultipleCandidates)
14216 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14217 return Fn;
14218}
14219
14223 OverloadExpr *Ovl = R.Expression;
14224 bool IsResultAmbiguous = false;
14225 FunctionDecl *Result = nullptr;
14226 DeclAccessPair DAP;
14227 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14228
14229 // Return positive for better, negative for worse, 0 for equal preference.
14230 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14231 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14232 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14233 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14234 };
14235
14236 // Don't use the AddressOfResolver because we're specifically looking for
14237 // cases where we have one overload candidate that lacks
14238 // enable_if/pass_object_size/...
14239 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14240 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14241 if (!FD)
14242 return nullptr;
14243
14245 continue;
14246
14247 // If we found a better result, update Result.
14248 auto FoundBetter = [&]() {
14249 IsResultAmbiguous = false;
14250 DAP = I.getPair();
14251 Result = FD;
14252 };
14253
14254 // We have more than one result - see if it is more
14255 // partial-ordering-constrained than the previous one.
14256 if (Result) {
14257 // Check CUDA preference first. If the candidates have differennt CUDA
14258 // preference, choose the one with higher CUDA preference. Otherwise,
14259 // choose the one with more constraints.
14260 if (getLangOpts().CUDA) {
14261 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14262 // FD has different preference than Result.
14263 if (PreferenceByCUDA != 0) {
14264 // FD is more preferable than Result.
14265 if (PreferenceByCUDA > 0)
14266 FoundBetter();
14267 continue;
14268 }
14269 }
14270 // FD has the same CUDA preference than Result. Continue to check
14271 // constraints.
14272
14273 // C++ [over.over]p5:
14274 // [...] Any given non-template function F0 is eliminated if the set
14275 // contains a second non-template function that is more
14276 // partial-ordering-constrained than F0 [...]
14277 FunctionDecl *MoreConstrained =
14279 /*IsFn1Reversed=*/false,
14280 /*IsFn2Reversed=*/false);
14281 if (MoreConstrained != FD) {
14282 if (!MoreConstrained) {
14283 IsResultAmbiguous = true;
14284 AmbiguousDecls.push_back(FD);
14285 }
14286 continue;
14287 }
14288 // FD is more constrained - replace Result with it.
14289 }
14290 FoundBetter();
14291 }
14292
14293 if (IsResultAmbiguous)
14294 return nullptr;
14295
14296 if (Result) {
14297 // We skipped over some ambiguous declarations which might be ambiguous with
14298 // the selected result.
14299 for (FunctionDecl *Skipped : AmbiguousDecls) {
14300 // If skipped candidate has different CUDA preference than the result,
14301 // there is no ambiguity. Otherwise check whether they have different
14302 // constraints.
14303 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14304 continue;
14305 if (!getMoreConstrainedFunction(Skipped, Result))
14306 return nullptr;
14307 }
14308 Pair = DAP;
14309 }
14310 return Result;
14311}
14312
14314 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14315 Expr *E = SrcExpr.get();
14316 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14317
14318 DeclAccessPair DAP;
14320 if (!Found || Found->isCPUDispatchMultiVersion() ||
14321 Found->isCPUSpecificMultiVersion())
14322 return false;
14323
14324 // Emitting multiple diagnostics for a function that is both inaccessible and
14325 // unavailable is consistent with our behavior elsewhere. So, always check
14326 // for both.
14330 if (Res.isInvalid())
14331 return false;
14332 Expr *Fixed = Res.get();
14333 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14334 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14335 else
14336 SrcExpr = Fixed;
14337 return true;
14338}
14339
14341 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14342 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14343 // C++ [over.over]p1:
14344 // [...] [Note: any redundant set of parentheses surrounding the
14345 // overloaded function name is ignored (5.1). ]
14346 // C++ [over.over]p1:
14347 // [...] The overloaded function name can be preceded by the &
14348 // operator.
14349
14350 // If we didn't actually find any template-ids, we're done.
14351 if (!ovl->hasExplicitTemplateArgs())
14352 return nullptr;
14353
14354 TemplateArgumentListInfo ExplicitTemplateArgs;
14355 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14356
14357 // Look through all of the overloaded functions, searching for one
14358 // whose type matches exactly.
14359 FunctionDecl *Matched = nullptr;
14360 for (UnresolvedSetIterator I = ovl->decls_begin(),
14361 E = ovl->decls_end(); I != E; ++I) {
14362 // C++0x [temp.arg.explicit]p3:
14363 // [...] In contexts where deduction is done and fails, or in contexts
14364 // where deduction is not done, if a template argument list is
14365 // specified and it, along with any default template arguments,
14366 // identifies a single function template specialization, then the
14367 // template-id is an lvalue for the function template specialization.
14369 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14370 if (!FunctionTemplate)
14371 continue;
14372
14373 // C++ [over.over]p2:
14374 // If the name is a function template, template argument deduction is
14375 // done (14.8.2.2), and if the argument deduction succeeds, the
14376 // resulting template argument list is used to generate a single
14377 // function template specialization, which is added to the set of
14378 // overloaded functions considered.
14379 FunctionDecl *Specialization = nullptr;
14380 TemplateDeductionInfo Info(ovl->getNameLoc());
14382 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14383 /*IsAddressOfFunction*/ true);
14385 // Make a note of the failed deduction for diagnostics.
14386 if (FailedTSC)
14387 FailedTSC->addCandidate().set(
14388 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14390 continue;
14391 }
14392
14393 assert(Specialization && "no specialization and no error?");
14394
14395 // C++ [temp.deduct.call]p6:
14396 // [...] If all successful deductions yield the same deduced A, that
14397 // deduced A is the result of deduction; otherwise, the parameter is
14398 // treated as a non-deduced context.
14399 if (Matched) {
14400 if (ForTypeDeduction &&
14402 Specialization->getType()))
14403 continue;
14404 // Multiple matches; we can't resolve to a single declaration.
14405 if (Complain) {
14406 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14407 << ovl->getName();
14409 }
14410 return nullptr;
14411 }
14412
14413 Matched = Specialization;
14414 if (FoundResult) *FoundResult = I.getPair();
14415 }
14416
14417 if (Matched &&
14418 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14419 return nullptr;
14420
14421 return Matched;
14422}
14423
14425 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14426 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14427 unsigned DiagIDForComplaining) {
14428 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14429
14431
14432 DeclAccessPair found;
14433 ExprResult SingleFunctionExpression;
14435 ovl.Expression, /*complain*/ false, &found)) {
14436 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14437 SrcExpr = ExprError();
14438 return true;
14439 }
14440
14441 // It is only correct to resolve to an instance method if we're
14442 // resolving a form that's permitted to be a pointer to member.
14443 // Otherwise we'll end up making a bound member expression, which
14444 // is illegal in all the contexts we resolve like this.
14445 if (!ovl.HasFormOfMemberPointer &&
14446 isa<CXXMethodDecl>(fn) &&
14447 cast<CXXMethodDecl>(fn)->isInstance()) {
14448 if (!complain) return false;
14449
14450 Diag(ovl.Expression->getExprLoc(),
14451 diag::err_bound_member_function)
14452 << 0 << ovl.Expression->getSourceRange();
14453
14454 // TODO: I believe we only end up here if there's a mix of
14455 // static and non-static candidates (otherwise the expression
14456 // would have 'bound member' type, not 'overload' type).
14457 // Ideally we would note which candidate was chosen and why
14458 // the static candidates were rejected.
14459 SrcExpr = ExprError();
14460 return true;
14461 }
14462
14463 // Fix the expression to refer to 'fn'.
14464 SingleFunctionExpression =
14465 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14466
14467 // If desired, do function-to-pointer decay.
14468 if (doFunctionPointerConversion) {
14469 SingleFunctionExpression =
14470 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14471 if (SingleFunctionExpression.isInvalid()) {
14472 SrcExpr = ExprError();
14473 return true;
14474 }
14475 }
14476 }
14477
14478 if (!SingleFunctionExpression.isUsable()) {
14479 if (complain) {
14480 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14481 << ovl.Expression->getName()
14482 << DestTypeForComplaining
14483 << OpRangeForComplaining
14485 NoteAllOverloadCandidates(SrcExpr.get());
14486
14487 SrcExpr = ExprError();
14488 return true;
14489 }
14490
14491 return false;
14492 }
14493
14494 SrcExpr = SingleFunctionExpression;
14495 return true;
14496}
14497
14498/// Add a single candidate to the overload set.
14500 DeclAccessPair FoundDecl,
14501 TemplateArgumentListInfo *ExplicitTemplateArgs,
14502 ArrayRef<Expr *> Args,
14503 OverloadCandidateSet &CandidateSet,
14504 bool PartialOverloading,
14505 bool KnownValid) {
14506 NamedDecl *Callee = FoundDecl.getDecl();
14507 if (isa<UsingShadowDecl>(Callee))
14508 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14509
14510 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14511 if (ExplicitTemplateArgs) {
14512 assert(!KnownValid && "Explicit template arguments?");
14513 return;
14514 }
14515 // Prevent ill-formed function decls to be added as overload candidates.
14516 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14517 return;
14518
14519 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14520 /*SuppressUserConversions=*/false,
14521 PartialOverloading);
14522 return;
14523 }
14524
14525 if (FunctionTemplateDecl *FuncTemplate
14526 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14527 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14528 ExplicitTemplateArgs, Args, CandidateSet,
14529 /*SuppressUserConversions=*/false,
14530 PartialOverloading);
14531 return;
14532 }
14533
14534 assert(!KnownValid && "unhandled case in overloaded call candidate");
14535}
14536
14538 ArrayRef<Expr *> Args,
14539 OverloadCandidateSet &CandidateSet,
14540 bool PartialOverloading) {
14541
14542#ifndef NDEBUG
14543 // Verify that ArgumentDependentLookup is consistent with the rules
14544 // in C++0x [basic.lookup.argdep]p3:
14545 //
14546 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14547 // and let Y be the lookup set produced by argument dependent
14548 // lookup (defined as follows). If X contains
14549 //
14550 // -- a declaration of a class member, or
14551 //
14552 // -- a block-scope function declaration that is not a
14553 // using-declaration, or
14554 //
14555 // -- a declaration that is neither a function or a function
14556 // template
14557 //
14558 // then Y is empty.
14559
14560 if (ULE->requiresADL()) {
14562 E = ULE->decls_end(); I != E; ++I) {
14563 assert(!(*I)->getDeclContext()->isRecord());
14564 assert(isa<UsingShadowDecl>(*I) ||
14565 !(*I)->getDeclContext()->isFunctionOrMethod());
14566 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14567 }
14568 }
14569#endif
14570
14571 // It would be nice to avoid this copy.
14572 TemplateArgumentListInfo TABuffer;
14573 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14574 if (ULE->hasExplicitTemplateArgs()) {
14575 ULE->copyTemplateArgumentsInto(TABuffer);
14576 ExplicitTemplateArgs = &TABuffer;
14577 }
14578
14580 E = ULE->decls_end(); I != E; ++I)
14581 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14582 CandidateSet, PartialOverloading,
14583 /*KnownValid*/ true);
14584
14585 if (ULE->requiresADL())
14587 Args, ExplicitTemplateArgs,
14588 CandidateSet, PartialOverloading);
14589}
14590
14592 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14593 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14594 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14595 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14596 CandidateSet, false, /*KnownValid*/ false);
14597}
14598
14599/// Determine whether a declaration with the specified name could be moved into
14600/// a different namespace.
14602 switch (Name.getCXXOverloadedOperator()) {
14603 case OO_New: case OO_Array_New:
14604 case OO_Delete: case OO_Array_Delete:
14605 return false;
14606
14607 default:
14608 return true;
14609 }
14610}
14611
14612/// Attempt to recover from an ill-formed use of a non-dependent name in a
14613/// template, where the non-dependent name was declared after the template
14614/// was defined. This is common in code written for a compilers which do not
14615/// correctly implement two-stage name lookup.
14616///
14617/// Returns true if a viable candidate was found and a diagnostic was issued.
14619 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14621 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14622 CXXRecordDecl **FoundInClass = nullptr) {
14623 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14624 return false;
14625
14626 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14627 if (DC->isTransparentContext())
14628 continue;
14629
14630 SemaRef.LookupQualifiedName(R, DC);
14631
14632 if (!R.empty()) {
14633 R.suppressDiagnostics();
14634
14635 OverloadCandidateSet Candidates(FnLoc, CSK);
14636 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14637 Candidates);
14638
14641 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14642
14643 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14644 // We either found non-function declarations or a best viable function
14645 // at class scope. A class-scope lookup result disables ADL. Don't
14646 // look past this, but let the caller know that we found something that
14647 // either is, or might be, usable in this class.
14648 if (FoundInClass) {
14649 *FoundInClass = RD;
14650 if (OR == OR_Success) {
14651 R.clear();
14652 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14653 R.resolveKind();
14654 }
14655 }
14656 return false;
14657 }
14658
14659 if (OR != OR_Success) {
14660 // There wasn't a unique best function or function template.
14661 return false;
14662 }
14663
14664 // Find the namespaces where ADL would have looked, and suggest
14665 // declaring the function there instead.
14666 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14667 Sema::AssociatedClassSet AssociatedClasses;
14668 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14669 AssociatedNamespaces,
14670 AssociatedClasses);
14671 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14672 if (canBeDeclaredInNamespace(R.getLookupName())) {
14673 DeclContext *Std = SemaRef.getStdNamespace();
14674 for (Sema::AssociatedNamespaceSet::iterator
14675 it = AssociatedNamespaces.begin(),
14676 end = AssociatedNamespaces.end(); it != end; ++it) {
14677 // Never suggest declaring a function within namespace 'std'.
14678 if (Std && Std->Encloses(*it))
14679 continue;
14680
14681 // Never suggest declaring a function within a namespace with a
14682 // reserved name, like __gnu_cxx.
14683 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14684 if (NS &&
14685 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14686 continue;
14687
14688 SuggestedNamespaces.insert(*it);
14689 }
14690 }
14691
14692 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14693 << R.getLookupName();
14694 if (SuggestedNamespaces.empty()) {
14695 SemaRef.Diag(Best->Function->getLocation(),
14696 diag::note_not_found_by_two_phase_lookup)
14697 << R.getLookupName() << 0;
14698 } else if (SuggestedNamespaces.size() == 1) {
14699 SemaRef.Diag(Best->Function->getLocation(),
14700 diag::note_not_found_by_two_phase_lookup)
14701 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14702 } else {
14703 // FIXME: It would be useful to list the associated namespaces here,
14704 // but the diagnostics infrastructure doesn't provide a way to produce
14705 // a localized representation of a list of items.
14706 SemaRef.Diag(Best->Function->getLocation(),
14707 diag::note_not_found_by_two_phase_lookup)
14708 << R.getLookupName() << 2;
14709 }
14710
14711 // Try to recover by calling this function.
14712 return true;
14713 }
14714
14715 R.clear();
14716 }
14717
14718 return false;
14719}
14720
14721/// Attempt to recover from ill-formed use of a non-dependent operator in a
14722/// template, where the non-dependent operator was declared after the template
14723/// was defined.
14724///
14725/// Returns true if a viable candidate was found and a diagnostic was issued.
14726static bool
14728 SourceLocation OpLoc,
14729 ArrayRef<Expr *> Args) {
14730 DeclarationName OpName =
14732 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14733 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14735 /*ExplicitTemplateArgs=*/nullptr, Args);
14736}
14737
14738namespace {
14739class BuildRecoveryCallExprRAII {
14740 Sema &SemaRef;
14741 Sema::SatisfactionStackResetRAII SatStack;
14742
14743public:
14744 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14745 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14746 SemaRef.IsBuildingRecoveryCallExpr = true;
14747 }
14748
14749 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14750};
14751}
14752
14753/// Attempts to recover from a call where no functions were found.
14754///
14755/// This function will do one of three things:
14756/// * Diagnose, recover, and return a recovery expression.
14757/// * Diagnose, fail to recover, and return ExprError().
14758/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14759/// expected to diagnose as appropriate.
14760static ExprResult
14763 SourceLocation LParenLoc,
14765 SourceLocation RParenLoc,
14766 bool EmptyLookup, bool AllowTypoCorrection) {
14767 // Do not try to recover if it is already building a recovery call.
14768 // This stops infinite loops for template instantiations like
14769 //
14770 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14771 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14772 if (SemaRef.IsBuildingRecoveryCallExpr)
14773 return ExprResult();
14774 BuildRecoveryCallExprRAII RCE(SemaRef);
14775
14776 CXXScopeSpec SS;
14777 SS.Adopt(ULE->getQualifierLoc());
14778 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14779
14780 TemplateArgumentListInfo TABuffer;
14781 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14782 if (ULE->hasExplicitTemplateArgs()) {
14783 ULE->copyTemplateArgumentsInto(TABuffer);
14784 ExplicitTemplateArgs = &TABuffer;
14785 }
14786
14787 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14789 CXXRecordDecl *FoundInClass = nullptr;
14790 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14792 ExplicitTemplateArgs, Args, &FoundInClass)) {
14793 // OK, diagnosed a two-phase lookup issue.
14794 } else if (EmptyLookup) {
14795 // Try to recover from an empty lookup with typo correction.
14796 R.clear();
14797 NoTypoCorrectionCCC NoTypoValidator{};
14798 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14799 ExplicitTemplateArgs != nullptr,
14800 dyn_cast<MemberExpr>(Fn));
14801 CorrectionCandidateCallback &Validator =
14802 AllowTypoCorrection
14803 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14804 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14805 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14806 Args))
14807 return ExprError();
14808 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14809 // We found a usable declaration of the name in a dependent base of some
14810 // enclosing class.
14811 // FIXME: We should also explain why the candidates found by name lookup
14812 // were not viable.
14813 if (SemaRef.DiagnoseDependentMemberLookup(R))
14814 return ExprError();
14815 } else {
14816 // We had viable candidates and couldn't recover; let the caller diagnose
14817 // this.
14818 return ExprResult();
14819 }
14820
14821 // If we get here, we should have issued a diagnostic and formed a recovery
14822 // lookup result.
14823 assert(!R.empty() && "lookup results empty despite recovery");
14824
14825 // If recovery created an ambiguity, just bail out.
14826 if (R.isAmbiguous()) {
14827 R.suppressDiagnostics();
14828 return ExprError();
14829 }
14830
14831 // Build an implicit member call if appropriate. Just drop the
14832 // casts and such from the call, we don't really care.
14833 ExprResult NewFn = ExprError();
14834 if ((*R.begin())->isCXXClassMember())
14835 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14836 ExplicitTemplateArgs, S);
14837 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14838 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14839 ExplicitTemplateArgs);
14840 else
14841 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14842
14843 if (NewFn.isInvalid())
14844 return ExprError();
14845
14846 // This shouldn't cause an infinite loop because we're giving it
14847 // an expression with viable lookup results, which should never
14848 // end up here.
14849 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14850 MultiExprArg(Args.data(), Args.size()),
14851 RParenLoc);
14852}
14853
14856 MultiExprArg Args,
14857 SourceLocation RParenLoc,
14858 OverloadCandidateSet *CandidateSet,
14859 ExprResult *Result) {
14860#ifndef NDEBUG
14861 if (ULE->requiresADL()) {
14862 // To do ADL, we must have found an unqualified name.
14863 assert(!ULE->getQualifier() && "qualified name with ADL");
14864
14865 // We don't perform ADL for implicit declarations of builtins.
14866 // Verify that this was correctly set up.
14867 FunctionDecl *F;
14868 if (ULE->decls_begin() != ULE->decls_end() &&
14869 ULE->decls_begin() + 1 == ULE->decls_end() &&
14870 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14871 F->getBuiltinID() && F->isImplicit())
14872 llvm_unreachable("performing ADL for builtin");
14873
14874 // We don't perform ADL in C.
14875 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14876 }
14877#endif
14878
14879 UnbridgedCastsSet UnbridgedCasts;
14880 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14881 *Result = ExprError();
14882 return true;
14883 }
14884
14885 // Add the functions denoted by the callee to the set of candidate
14886 // functions, including those from argument-dependent lookup.
14887 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14888
14889 if (getLangOpts().MSVCCompat &&
14890 CurContext->isDependentContext() && !isSFINAEContext() &&
14892
14894 if (CandidateSet->empty() ||
14895 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14897 // In Microsoft mode, if we are inside a template class member function
14898 // then create a type dependent CallExpr. The goal is to postpone name
14899 // lookup to instantiation time to be able to search into type dependent
14900 // base classes.
14901 CallExpr *CE =
14902 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14903 RParenLoc, CurFPFeatureOverrides());
14905 *Result = CE;
14906 return true;
14907 }
14908 }
14909
14910 if (CandidateSet->empty())
14911 return false;
14912
14913 UnbridgedCasts.restore();
14914 return false;
14915}
14916
14917// Guess at what the return type for an unresolvable overload should be.
14920 std::optional<QualType> Result;
14921 // Adjust Type after seeing a candidate.
14922 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14923 if (!Candidate.Function)
14924 return;
14925 if (Candidate.Function->isInvalidDecl())
14926 return;
14927 QualType T = Candidate.Function->getReturnType();
14928 if (T.isNull())
14929 return;
14930 if (!Result)
14931 Result = T;
14932 else if (Result != T)
14933 Result = QualType();
14934 };
14935
14936 // Look for an unambiguous type from a progressively larger subset.
14937 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14938 //
14939 // First, consider only the best candidate.
14940 if (Best && *Best != CS.end())
14941 ConsiderCandidate(**Best);
14942 // Next, consider only viable candidates.
14943 if (!Result)
14944 for (const auto &C : CS)
14945 if (C.Viable)
14946 ConsiderCandidate(C);
14947 // Finally, consider all candidates.
14948 if (!Result)
14949 for (const auto &C : CS)
14950 ConsiderCandidate(C);
14951
14952 if (!Result)
14953 return QualType();
14954 auto Value = *Result;
14955 if (Value.isNull() || Value->isUndeducedType())
14956 return QualType();
14957 return Value;
14958}
14959
14960/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14961/// the completed call expression. If overload resolution fails, emits
14962/// diagnostics and returns ExprError()
14965 SourceLocation LParenLoc,
14966 MultiExprArg Args,
14967 SourceLocation RParenLoc,
14968 Expr *ExecConfig,
14969 OverloadCandidateSet *CandidateSet,
14971 OverloadingResult OverloadResult,
14972 bool AllowTypoCorrection) {
14973 switch (OverloadResult) {
14974 case OR_Success: {
14975 FunctionDecl *FDecl = (*Best)->Function;
14976 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14977 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14978 return ExprError();
14979 ExprResult Res =
14980 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14981 if (Res.isInvalid())
14982 return ExprError();
14983 return SemaRef.BuildResolvedCallExpr(
14984 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14985 /*IsExecConfig=*/false,
14986 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14987 }
14988
14989 case OR_No_Viable_Function: {
14990 if (*Best != CandidateSet->end() &&
14991 CandidateSet->getKind() ==
14993 if (CXXMethodDecl *M =
14994 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14996 CandidateSet->NoteCandidates(
14998 Fn->getBeginLoc(),
14999 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
15000 SemaRef, OCD_AmbiguousCandidates, Args);
15001 return ExprError();
15002 }
15003 }
15004
15005 // Try to recover by looking for viable functions which the user might
15006 // have meant to call.
15007 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
15008 Args, RParenLoc,
15009 CandidateSet->empty(),
15010 AllowTypoCorrection);
15011 if (Recovery.isInvalid() || Recovery.isUsable())
15012 return Recovery;
15013
15014 // If the user passes in a function that we can't take the address of, we
15015 // generally end up emitting really bad error messages. Here, we attempt to
15016 // emit better ones.
15017 for (const Expr *Arg : Args) {
15018 if (!Arg->getType()->isFunctionType())
15019 continue;
15020 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
15021 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15022 if (FD &&
15023 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15024 Arg->getExprLoc()))
15025 return ExprError();
15026 }
15027 }
15028
15029 CandidateSet->NoteCandidates(
15031 Fn->getBeginLoc(),
15032 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15033 << ULE->getName() << Fn->getSourceRange()),
15034 SemaRef, OCD_AllCandidates, Args);
15035 break;
15036 }
15037
15038 case OR_Ambiguous:
15039 CandidateSet->NoteCandidates(
15040 PartialDiagnosticAt(Fn->getBeginLoc(),
15041 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15042 << ULE->getName() << Fn->getSourceRange()),
15043 SemaRef, OCD_AmbiguousCandidates, Args);
15044 break;
15045
15046 case OR_Deleted: {
15047 FunctionDecl *FDecl = (*Best)->Function;
15048 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15049 Fn->getSourceRange(), ULE->getName(),
15050 *CandidateSet, FDecl, Args);
15051
15052 // We emitted an error for the unavailable/deleted function call but keep
15053 // the call in the AST.
15054 ExprResult Res =
15055 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15056 if (Res.isInvalid())
15057 return ExprError();
15058 return SemaRef.BuildResolvedCallExpr(
15059 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15060 /*IsExecConfig=*/false,
15061 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15062 }
15063 }
15064
15065 // Overload resolution failed, try to recover.
15066 SmallVector<Expr *, 8> SubExprs = {Fn};
15067 SubExprs.append(Args.begin(), Args.end());
15068 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15069 chooseRecoveryType(*CandidateSet, Best));
15070}
15071
15074 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15075 if (I->Viable &&
15076 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15077 I->Viable = false;
15078 I->FailureKind = ovl_fail_addr_not_available;
15079 }
15080 }
15081}
15082
15085 SourceLocation LParenLoc,
15086 MultiExprArg Args,
15087 SourceLocation RParenLoc,
15088 Expr *ExecConfig,
15089 bool AllowTypoCorrection,
15090 bool CalleesAddressIsTaken) {
15091
15095
15096 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15097 ExprResult result;
15098
15099 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15100 &result))
15101 return result;
15102
15103 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15104 // functions that aren't addressible are considered unviable.
15105 if (CalleesAddressIsTaken)
15106 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15107
15109 OverloadingResult OverloadResult =
15110 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15111
15112 // [C++23][over.call.func]
15113 // if overload resolution selects a non-static member function,
15114 // the call is ill-formed;
15116 Best != CandidateSet.end()) {
15117 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15118 M && M->isImplicitObjectMemberFunction()) {
15119 OverloadResult = OR_No_Viable_Function;
15120 }
15121 }
15122
15123 // Model the case with a call to a templated function whose definition
15124 // encloses the call and whose return type contains a placeholder type as if
15125 // the UnresolvedLookupExpr was type-dependent.
15126 if (OverloadResult == OR_Success) {
15127 const FunctionDecl *FDecl = Best->Function;
15128 if (LangOpts.CUDA)
15129 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15130 if (FDecl && FDecl->isTemplateInstantiation() &&
15131 FDecl->getReturnType()->isUndeducedType()) {
15132
15133 // Creating dependent CallExpr is not okay if the enclosing context itself
15134 // is not dependent. This situation notably arises if a non-dependent
15135 // member function calls the later-defined overloaded static function.
15136 //
15137 // For example, in
15138 // class A {
15139 // void c() { callee(1); }
15140 // static auto callee(auto x) { }
15141 // };
15142 //
15143 // Here callee(1) is unresolved at the call site, but is not inside a
15144 // dependent context. There will be no further attempt to resolve this
15145 // call if it is made dependent.
15146
15147 if (const auto *TP =
15148 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15149 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15150 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15151 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15152 }
15153 }
15154 }
15155
15156 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15157 ExecConfig, &CandidateSet, &Best,
15158 OverloadResult, AllowTypoCorrection);
15159}
15160
15164 const UnresolvedSetImpl &Fns,
15165 bool PerformADL) {
15167 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15168 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15169}
15170
15173 bool HadMultipleCandidates) {
15174 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15175 // the FoundDecl as it impedes TransformMemberExpr.
15176 // We go a bit further here: if there's no difference in UnderlyingDecl,
15177 // then using FoundDecl vs Method shouldn't make a difference either.
15178 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15179 FoundDecl = Method;
15180 // Convert the expression to match the conversion function's implicit object
15181 // parameter.
15182 ExprResult Exp;
15183 if (Method->isExplicitObjectMemberFunction())
15185 else
15187 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15188 if (Exp.isInvalid())
15189 return true;
15190
15191 if (Method->getParent()->isLambda() &&
15192 Method->getConversionType()->isBlockPointerType()) {
15193 // This is a lambda conversion to block pointer; check if the argument
15194 // was a LambdaExpr.
15195 Expr *SubE = E;
15196 auto *CE = dyn_cast<CastExpr>(SubE);
15197 if (CE && CE->getCastKind() == CK_NoOp)
15198 SubE = CE->getSubExpr();
15199 SubE = SubE->IgnoreParens();
15200 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15201 SubE = BE->getSubExpr();
15202 if (isa<LambdaExpr>(SubE)) {
15203 // For the conversion to block pointer on a lambda expression, we
15204 // construct a special BlockLiteral instead; this doesn't really make
15205 // a difference in ARC, but outside of ARC the resulting block literal
15206 // follows the normal lifetime rules for block literals instead of being
15207 // autoreleased.
15211 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15213
15214 // FIXME: This note should be produced by a CodeSynthesisContext.
15215 if (BlockExp.isInvalid())
15216 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15217 return BlockExp;
15218 }
15219 }
15220 CallExpr *CE;
15221 QualType ResultType = Method->getReturnType();
15223 ResultType = ResultType.getNonLValueExprType(Context);
15224 if (Method->isExplicitObjectMemberFunction()) {
15225 ExprResult FnExpr =
15226 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15227 HadMultipleCandidates, E->getBeginLoc());
15228 if (FnExpr.isInvalid())
15229 return ExprError();
15230 Expr *ObjectParam = Exp.get();
15231 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15232 ResultType, VK, Exp.get()->getEndLoc(),
15234 CE->setUsesMemberSyntax(true);
15235 } else {
15236 MemberExpr *ME =
15237 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15239 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15240 HadMultipleCandidates, DeclarationNameInfo(),
15241 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15242
15243 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15244 Exp.get()->getEndLoc(),
15246 }
15247
15248 if (CheckFunctionCall(Method, CE,
15249 Method->getType()->castAs<FunctionProtoType>()))
15250 return ExprError();
15251
15253}
15254
15257 const UnresolvedSetImpl &Fns,
15258 ArrayRef<Expr *> Args, bool PerformADL) {
15259 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15260
15261 SourceLocation OpLoc = CandidateSet.getLocation();
15262 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15263
15264 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15265 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15266 if (PerformADL)
15267 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15268 /*ExplicitTemplateArgs*/ nullptr,
15269 CandidateSet);
15270 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15271}
15272
15275 const UnresolvedSetImpl &Fns,
15276 Expr *Input, bool PerformADL) {
15278 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15280 // TODO: provide better source location info.
15281 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15282
15283 if (checkPlaceholderForOverload(*this, Input))
15284 return ExprError();
15285
15286 Expr *Args[2] = { Input, nullptr };
15287 unsigned NumArgs = 1;
15288
15289 // For post-increment and post-decrement, add the implicit '0' as
15290 // the second argument, so that we know this is a post-increment or
15291 // post-decrement.
15292 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15293 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15294 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15295 SourceLocation());
15296 NumArgs = 2;
15297 }
15298
15299 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15300
15301 if (Input->isTypeDependent()) {
15303 // [C++26][expr.unary.op][expr.pre.incr]
15304 // The * operator yields an lvalue of type
15305 // The pre/post increment operators yied an lvalue.
15306 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15307 VK = VK_LValue;
15308
15309 if (Fns.empty())
15310 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15311 OK_Ordinary, OpLoc, false,
15313
15314 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15316 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15317 if (Fn.isInvalid())
15318 return ExprError();
15319 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15320 Context.DependentTy, VK_PRValue, OpLoc,
15322 }
15323
15324 // Build an empty overload set.
15326 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15327
15328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15329
15330 // Perform overload resolution.
15332 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15333 case OR_Success: {
15334 // We found a built-in operator or an overloaded operator.
15335 FunctionDecl *FnDecl = Best->Function;
15336
15337 if (FnDecl) {
15338 Expr *Base = nullptr;
15339 // We matched an overloaded operator. Build a call to that
15340 // operator.
15341
15342 // Convert the arguments.
15343 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15344 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15345
15346 ExprResult InputInit;
15347 if (Method->isExplicitObjectMemberFunction())
15348 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15349 else
15351 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15352 if (InputInit.isInvalid())
15353 return ExprError();
15354 Base = Input = InputInit.get();
15355 } else {
15356 // Convert the arguments.
15357 ExprResult InputInit
15359 Context,
15360 FnDecl->getParamDecl(0)),
15362 Input);
15363 if (InputInit.isInvalid())
15364 return ExprError();
15365 Input = InputInit.get();
15366 }
15367
15368 // Build the actual expression node.
15369 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15370 Base, HadMultipleCandidates,
15371 OpLoc);
15372 if (FnExpr.isInvalid())
15373 return ExprError();
15374
15375 // Determine the result type.
15376 QualType ResultTy = FnDecl->getReturnType();
15378 ResultTy = ResultTy.getNonLValueExprType(Context);
15379
15380 Args[0] = Input;
15382 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15384 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15385
15386 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15387 return ExprError();
15388
15389 if (CheckFunctionCall(FnDecl, TheCall,
15390 FnDecl->getType()->castAs<FunctionProtoType>()))
15391 return ExprError();
15392 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15393 } else {
15394 // We matched a built-in operator. Convert the arguments, then
15395 // break out so that we will build the appropriate built-in
15396 // operator node.
15398 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15401 if (InputRes.isInvalid())
15402 return ExprError();
15403 Input = InputRes.get();
15404 break;
15405 }
15406 }
15407
15409 // This is an erroneous use of an operator which can be overloaded by
15410 // a non-member function. Check for non-member operators which were
15411 // defined too late to be candidates.
15412 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15413 // FIXME: Recover by calling the found function.
15414 return ExprError();
15415
15416 // No viable function; fall through to handling this as a
15417 // built-in operator, which will produce an error message for us.
15418 break;
15419
15420 case OR_Ambiguous:
15421 CandidateSet.NoteCandidates(
15422 PartialDiagnosticAt(OpLoc,
15423 PDiag(diag::err_ovl_ambiguous_oper_unary)
15425 << Input->getType() << Input->getSourceRange()),
15426 *this, OCD_AmbiguousCandidates, ArgsArray,
15427 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15428 return ExprError();
15429
15430 case OR_Deleted: {
15431 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15432 // object whose method was called. Later in NoteCandidates size of ArgsArray
15433 // is passed further and it eventually ends up compared to number of
15434 // function candidate parameters which never includes the object parameter,
15435 // so slice ArgsArray to make sure apples are compared to apples.
15436 StringLiteral *Msg = Best->Function->getDeletedMessage();
15437 CandidateSet.NoteCandidates(
15438 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15440 << (Msg != nullptr)
15441 << (Msg ? Msg->getString() : StringRef())
15442 << Input->getSourceRange()),
15443 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15444 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15445 return ExprError();
15446 }
15447 }
15448
15449 // Either we found no viable overloaded operator or we matched a
15450 // built-in operator. In either case, fall through to trying to
15451 // build a built-in operation.
15452 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15453}
15454
15457 const UnresolvedSetImpl &Fns,
15458 ArrayRef<Expr *> Args, bool PerformADL) {
15459 SourceLocation OpLoc = CandidateSet.getLocation();
15460
15461 OverloadedOperatorKind ExtraOp =
15464 : OO_None;
15465
15466 // Add the candidates from the given function set. This also adds the
15467 // rewritten candidates using these functions if necessary.
15468 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15469
15470 // As template candidates are not deduced immediately,
15471 // persist the array in the overload set.
15472 ArrayRef<Expr *> ReversedArgs;
15473 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15474 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15475 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15476
15477 // Add operator candidates that are member functions.
15478 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15479 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15480 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15482
15483 // In C++20, also add any rewritten member candidates.
15484 if (ExtraOp) {
15485 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15486 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15487 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15489 }
15490
15491 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15492 // performed for an assignment operator (nor for operator[] nor operator->,
15493 // which don't get here).
15494 if (Op != OO_Equal && PerformADL) {
15495 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15496 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15497 /*ExplicitTemplateArgs*/ nullptr,
15498 CandidateSet);
15499 if (ExtraOp) {
15500 DeclarationName ExtraOpName =
15501 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15502 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15503 /*ExplicitTemplateArgs*/ nullptr,
15504 CandidateSet);
15505 }
15506 }
15507
15508 // Add builtin operator candidates.
15509 //
15510 // FIXME: We don't add any rewritten candidates here. This is strictly
15511 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15512 // resulting in our selecting a rewritten builtin candidate. For example:
15513 //
15514 // enum class E { e };
15515 // bool operator!=(E, E) requires false;
15516 // bool k = E::e != E::e;
15517 //
15518 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15519 // it seems unreasonable to consider rewritten builtin candidates. A core
15520 // issue has been filed proposing to removed this requirement.
15521 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15522}
15523
15526 const UnresolvedSetImpl &Fns, Expr *LHS,
15527 Expr *RHS, bool PerformADL,
15528 bool AllowRewrittenCandidates,
15529 FunctionDecl *DefaultedFn) {
15530 Expr *Args[2] = { LHS, RHS };
15531 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15532
15533 if (!getLangOpts().CPlusPlus20)
15534 AllowRewrittenCandidates = false;
15535
15537
15538 // If either side is type-dependent, create an appropriate dependent
15539 // expression.
15540 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15541 if (Fns.empty()) {
15542 // If there are no functions to store, just build a dependent
15543 // BinaryOperator or CompoundAssignment.
15546 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15547 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15548 Context.DependentTy);
15550 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15552 }
15553
15554 // FIXME: save results of ADL from here?
15555 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15556 // TODO: provide better source location info in DNLoc component.
15557 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15558 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15560 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15561 if (Fn.isInvalid())
15562 return ExprError();
15563 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15564 Context.DependentTy, VK_PRValue, OpLoc,
15566 }
15567
15568 // If this is the .* operator, which is not overloadable, just
15569 // create a built-in binary operator.
15570 if (Opc == BO_PtrMemD) {
15571 auto CheckPlaceholder = [&](Expr *&Arg) {
15573 if (Res.isUsable())
15574 Arg = Res.get();
15575 return !Res.isUsable();
15576 };
15577
15578 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15579 // expression that contains placeholders (in either the LHS or RHS).
15580 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15581 return ExprError();
15582 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15583 }
15584
15585 // Always do placeholder-like conversions on the RHS.
15586 if (checkPlaceholderForOverload(*this, Args[1]))
15587 return ExprError();
15588
15589 // Do placeholder-like conversion on the LHS; note that we should
15590 // not get here with a PseudoObject LHS.
15591 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15592 if (checkPlaceholderForOverload(*this, Args[0]))
15593 return ExprError();
15594
15595 // If this is the assignment operator, we only perform overload resolution
15596 // if the left-hand side is a class or enumeration type. This is actually
15597 // a hack. The standard requires that we do overload resolution between the
15598 // various built-in candidates, but as DR507 points out, this can lead to
15599 // problems. So we do it this way, which pretty much follows what GCC does.
15600 // Note that we go the traditional code path for compound assignment forms.
15601 // In HLSL, user-defined structs/classes do not have constructors or
15602 // overloadable assignment operators, so we can take this shortcut too.
15603 const Type *LHSTy = Args[0]->getType().getTypePtr();
15604 if (Opc == BO_Assign &&
15605 (!LHSTy->isOverloadableType() ||
15606 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15608 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15609
15610 // Build the overload set.
15613 Op, OpLoc, AllowRewrittenCandidates));
15614 if (DefaultedFn)
15615 CandidateSet.exclude(DefaultedFn);
15616 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15617
15618 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15619
15620 // Perform overload resolution.
15622 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15623 case OR_Success: {
15624 // We found a built-in operator or an overloaded operator.
15625 FunctionDecl *FnDecl = Best->Function;
15626
15627 bool IsReversed = Best->isReversed();
15628 if (IsReversed)
15629 std::swap(Args[0], Args[1]);
15630
15631 if (FnDecl) {
15632
15633 if (FnDecl->isInvalidDecl())
15634 return ExprError();
15635
15636 Expr *Base = nullptr;
15637 // We matched an overloaded operator. Build a call to that
15638 // operator.
15639
15640 OverloadedOperatorKind ChosenOp =
15642
15643 // C++2a [over.match.oper]p9:
15644 // If a rewritten operator== candidate is selected by overload
15645 // resolution for an operator@, its return type shall be cv bool
15646 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15647 !FnDecl->getReturnType()->isBooleanType()) {
15648 bool IsExtension =
15650 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15651 : diag::err_ovl_rewrite_equalequal_not_bool)
15652 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15653 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15654 Diag(FnDecl->getLocation(), diag::note_declared_at);
15655 if (!IsExtension)
15656 return ExprError();
15657 }
15658
15659 if (AllowRewrittenCandidates && !IsReversed &&
15660 CandidateSet.getRewriteInfo().isReversible()) {
15661 // We could have reversed this operator, but didn't. Check if some
15662 // reversed form was a viable candidate, and if so, if it had a
15663 // better conversion for either parameter. If so, this call is
15664 // formally ambiguous, and allowing it is an extension.
15666 for (OverloadCandidate &Cand : CandidateSet) {
15667 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15668 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15669 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15671 *this, OpLoc, Cand.Conversions[ArgIdx],
15672 Best->Conversions[ArgIdx]) ==
15674 AmbiguousWith.push_back(Cand.Function);
15675 break;
15676 }
15677 }
15678 }
15679 }
15680
15681 if (!AmbiguousWith.empty()) {
15682 bool AmbiguousWithSelf =
15683 AmbiguousWith.size() == 1 &&
15684 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15685 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15687 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15688 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15689 if (AmbiguousWithSelf) {
15690 Diag(FnDecl->getLocation(),
15691 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15692 // Mark member== const or provide matching != to disallow reversed
15693 // args. Eg.
15694 // struct S { bool operator==(const S&); };
15695 // S()==S();
15696 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15697 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15698 !MD->isConst() &&
15699 !MD->hasCXXExplicitFunctionObjectParameter() &&
15700 Context.hasSameUnqualifiedType(
15701 MD->getFunctionObjectParameterType(),
15702 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15703 Context.hasSameUnqualifiedType(
15704 MD->getFunctionObjectParameterType(),
15705 Args[0]->getType()) &&
15706 Context.hasSameUnqualifiedType(
15707 MD->getFunctionObjectParameterType(),
15708 Args[1]->getType()))
15709 Diag(FnDecl->getLocation(),
15710 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15711 } else {
15712 Diag(FnDecl->getLocation(),
15713 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15714 for (auto *F : AmbiguousWith)
15715 Diag(F->getLocation(),
15716 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15717 }
15718 }
15719 }
15720
15721 // Check for nonnull = nullable.
15722 // This won't be caught in the arg's initialization: the parameter to
15723 // the assignment operator is not marked nonnull.
15724 if (Op == OO_Equal)
15726 Args[1]->getType(), OpLoc);
15727
15728 // Convert the arguments.
15729 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15730 // Best->Access is only meaningful for class members.
15731 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15732
15733 ExprResult Arg0, Arg1;
15734 unsigned ParamIdx = 0;
15735 if (Method->isExplicitObjectMemberFunction()) {
15736 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15737 ParamIdx = 1;
15738 } else {
15740 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15741 }
15744 Context, FnDecl->getParamDecl(ParamIdx)),
15745 SourceLocation(), Args[1]);
15746 if (Arg0.isInvalid() || Arg1.isInvalid())
15747 return ExprError();
15748
15749 Base = Args[0] = Arg0.getAs<Expr>();
15750 Args[1] = RHS = Arg1.getAs<Expr>();
15751 } else {
15752 // Convert the arguments.
15755 FnDecl->getParamDecl(0)),
15756 SourceLocation(), Args[0]);
15757 if (Arg0.isInvalid())
15758 return ExprError();
15759
15760 ExprResult Arg1 =
15763 FnDecl->getParamDecl(1)),
15764 SourceLocation(), Args[1]);
15765 if (Arg1.isInvalid())
15766 return ExprError();
15767 Args[0] = LHS = Arg0.getAs<Expr>();
15768 Args[1] = RHS = Arg1.getAs<Expr>();
15769 }
15770
15771 // Build the actual expression node.
15772 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15773 Best->FoundDecl, Base,
15774 HadMultipleCandidates, OpLoc);
15775 if (FnExpr.isInvalid())
15776 return ExprError();
15777
15778 // Determine the result type.
15779 QualType ResultTy = FnDecl->getReturnType();
15781 ResultTy = ResultTy.getNonLValueExprType(Context);
15782
15783 CallExpr *TheCall;
15784 ArrayRef<const Expr *> ArgsArray(Args, 2);
15785 const Expr *ImplicitThis = nullptr;
15786
15787 // We always create a CXXOperatorCallExpr, even for explicit object
15788 // members; CodeGen should take care not to emit the this pointer.
15790 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15792 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15793 IsReversed);
15794
15795 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15796 Method && Method->isImplicitObjectMemberFunction()) {
15797 // Cut off the implicit 'this'.
15798 ImplicitThis = ArgsArray[0];
15799 ArgsArray = ArgsArray.slice(1);
15800 }
15801
15802 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15803 FnDecl))
15804 return ExprError();
15805
15806 if (Op == OO_Equal) {
15807 // Check for a self move.
15808 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15809 // lifetime check.
15811 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15812 Args[1]);
15813 }
15814 if (ImplicitThis) {
15815 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15816 QualType ThisTypeFromDecl = Context.getPointerType(
15817 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15818
15819 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15820 ThisTypeFromDecl);
15821 }
15822
15823 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15824 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15826
15827 ExprResult R = MaybeBindToTemporary(TheCall);
15828 if (R.isInvalid())
15829 return ExprError();
15830
15831 R = CheckForImmediateInvocation(R, FnDecl);
15832 if (R.isInvalid())
15833 return ExprError();
15834
15835 // For a rewritten candidate, we've already reversed the arguments
15836 // if needed. Perform the rest of the rewrite now.
15837 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15838 (Op == OO_Spaceship && IsReversed)) {
15839 if (Op == OO_ExclaimEqual) {
15840 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15841 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15842 } else {
15843 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15844 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15845 Expr *ZeroLiteral =
15847
15850 Ctx.Entity = FnDecl;
15852
15854 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15855 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15856 /*AllowRewrittenCandidates=*/false);
15857
15859 }
15860 if (R.isInvalid())
15861 return ExprError();
15862 } else {
15863 assert(ChosenOp == Op && "unexpected operator name");
15864 }
15865
15866 // Make a note in the AST if we did any rewriting.
15867 if (Best->RewriteKind != CRK_None)
15868 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15869
15870 return R;
15871 } else {
15872 // We matched a built-in operator. Convert the arguments, then
15873 // break out so that we will build the appropriate built-in
15874 // operator node.
15876 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15879 if (ArgsRes0.isInvalid())
15880 return ExprError();
15881 Args[0] = ArgsRes0.get();
15882
15884 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15887 if (ArgsRes1.isInvalid())
15888 return ExprError();
15889 Args[1] = ArgsRes1.get();
15890 break;
15891 }
15892 }
15893
15894 case OR_No_Viable_Function: {
15895 // C++ [over.match.oper]p9:
15896 // If the operator is the operator , [...] and there are no
15897 // viable functions, then the operator is assumed to be the
15898 // built-in operator and interpreted according to clause 5.
15899 if (Opc == BO_Comma)
15900 break;
15901
15902 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15903 // compare result using '==' and '<'.
15904 if (DefaultedFn && Opc == BO_Cmp) {
15905 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15906 Args[1], DefaultedFn);
15907 if (E.isInvalid() || E.isUsable())
15908 return E;
15909 }
15910
15911 // For class as left operand for assignment or compound assignment
15912 // operator do not fall through to handling in built-in, but report that
15913 // no overloaded assignment operator found
15915 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15916 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15917 Args, OpLoc);
15918 DeferDiagsRAII DDR(*this,
15919 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15920 if (Args[0]->getType()->isRecordType() &&
15921 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15922 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15924 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15925 if (Args[0]->getType()->isIncompleteType()) {
15926 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15927 << Args[0]->getType()
15928 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15929 }
15930 } else {
15931 // This is an erroneous use of an operator which can be overloaded by
15932 // a non-member function. Check for non-member operators which were
15933 // defined too late to be candidates.
15934 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15935 // FIXME: Recover by calling the found function.
15936 return ExprError();
15937
15938 // No viable function; try to create a built-in operation, which will
15939 // produce an error. Then, show the non-viable candidates.
15940 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15941 }
15942 assert(Result.isInvalid() &&
15943 "C++ binary operator overloading is missing candidates!");
15944 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15945 return Result;
15946 }
15947
15948 case OR_Ambiguous:
15949 CandidateSet.NoteCandidates(
15950 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15952 << Args[0]->getType()
15953 << Args[1]->getType()
15954 << Args[0]->getSourceRange()
15955 << Args[1]->getSourceRange()),
15957 OpLoc);
15958 return ExprError();
15959
15960 case OR_Deleted: {
15961 if (isImplicitlyDeleted(Best->Function)) {
15962 FunctionDecl *DeletedFD = Best->Function;
15964 DeletedFD->getDefaultedFunctionKind();
15965 if (DFK.isSpecialMember()) {
15966 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15967 << Args[0]->getType() << DFK.asSpecialMember();
15968 } else {
15969 assert(DFK.isComparison());
15970 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15971 << Args[0]->getType() << DeletedFD;
15972 }
15973
15974 // The user probably meant to call this special member. Just
15975 // explain why it's deleted.
15976 NoteDeletedFunction(DeletedFD);
15977 return ExprError();
15978 }
15979
15980 StringLiteral *Msg = Best->Function->getDeletedMessage();
15981 CandidateSet.NoteCandidates(
15983 OpLoc,
15984 PDiag(diag::err_ovl_deleted_oper)
15985 << getOperatorSpelling(Best->Function->getDeclName()
15986 .getCXXOverloadedOperator())
15987 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15988 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15990 OpLoc);
15991 return ExprError();
15992 }
15993 }
15994
15995 // We matched a built-in operator; build it.
15996 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15997}
15998
16000 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16001 FunctionDecl *DefaultedFn) {
16002 const ComparisonCategoryInfo *Info =
16003 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
16004 // If we're not producing a known comparison category type, we can't
16005 // synthesize a three-way comparison. Let the caller diagnose this.
16006 if (!Info)
16007 return ExprResult((Expr*)nullptr);
16008
16009 // If we ever want to perform this synthesis more generally, we will need to
16010 // apply the temporary materialization conversion to the operands.
16011 assert(LHS->isGLValue() && RHS->isGLValue() &&
16012 "cannot use prvalue expressions more than once");
16013 Expr *OrigLHS = LHS;
16014 Expr *OrigRHS = RHS;
16015
16016 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16017 // each of them multiple times below.
16018 LHS = new (Context)
16019 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16020 LHS->getObjectKind(), LHS);
16021 RHS = new (Context)
16022 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16023 RHS->getObjectKind(), RHS);
16024
16025 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16026 DefaultedFn);
16027 if (Eq.isInvalid())
16028 return ExprError();
16029
16030 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16031 true, DefaultedFn);
16032 if (Less.isInvalid())
16033 return ExprError();
16034
16036 if (Info->isPartial()) {
16037 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16038 DefaultedFn);
16039 if (Greater.isInvalid())
16040 return ExprError();
16041 }
16042
16043 // Form the list of comparisons we're going to perform.
16044 struct Comparison {
16047 } Comparisons[4] =
16053 };
16054
16055 int I = Info->isPartial() ? 3 : 2;
16056
16057 // Combine the comparisons with suitable conditional expressions.
16059 for (; I >= 0; --I) {
16060 // Build a reference to the comparison category constant.
16061 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16062 // FIXME: Missing a constant for a comparison category. Diagnose this?
16063 if (!VI)
16064 return ExprResult((Expr*)nullptr);
16065 ExprResult ThisResult =
16067 if (ThisResult.isInvalid())
16068 return ExprError();
16069
16070 // Build a conditional unless this is the final case.
16071 if (Result.get()) {
16072 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16073 ThisResult.get(), Result.get());
16074 if (Result.isInvalid())
16075 return ExprError();
16076 } else {
16077 Result = ThisResult;
16078 }
16079 }
16080
16081 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16082 // bind the OpaqueValueExprs before they're (repeatedly) used.
16083 Expr *SyntacticForm = BinaryOperator::Create(
16084 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16085 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16087 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16088 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16089}
16090
16092 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16093 MultiExprArg Args, SourceLocation LParenLoc) {
16094
16095 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16096 unsigned NumParams = Proto->getNumParams();
16097 unsigned NumArgsSlots =
16098 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16099 // Build the full argument list for the method call (the implicit object
16100 // parameter is placed at the beginning of the list).
16101 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16102 bool IsError = false;
16103 // Initialize the implicit object parameter.
16104 // Check the argument types.
16105 for (unsigned i = 0; i != NumParams; i++) {
16106 Expr *Arg;
16107 if (i < Args.size()) {
16108 Arg = Args[i];
16109 ExprResult InputInit =
16111 S.Context, Method->getParamDecl(i)),
16112 SourceLocation(), Arg);
16113 IsError |= InputInit.isInvalid();
16114 Arg = InputInit.getAs<Expr>();
16115 } else {
16116 ExprResult DefArg =
16117 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16118 if (DefArg.isInvalid()) {
16119 IsError = true;
16120 break;
16121 }
16122 Arg = DefArg.getAs<Expr>();
16123 }
16124
16125 MethodArgs.push_back(Arg);
16126 }
16127 return IsError;
16128}
16129
16131 SourceLocation RLoc,
16132 Expr *Base,
16133 MultiExprArg ArgExpr) {
16135 Args.push_back(Base);
16136 for (auto *e : ArgExpr) {
16137 Args.push_back(e);
16138 }
16139 DeclarationName OpName =
16140 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16141
16142 SourceRange Range = ArgExpr.empty()
16143 ? SourceRange{}
16144 : SourceRange(ArgExpr.front()->getBeginLoc(),
16145 ArgExpr.back()->getEndLoc());
16146
16147 // If either side is type-dependent, create an appropriate dependent
16148 // expression.
16150
16151 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16152 // CHECKME: no 'operator' keyword?
16153 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16154 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16156 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16157 if (Fn.isInvalid())
16158 return ExprError();
16159 // Can't add any actual overloads yet
16160
16161 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16162 Context.DependentTy, VK_PRValue, RLoc,
16164 }
16165
16166 // Handle placeholders
16167 UnbridgedCastsSet UnbridgedCasts;
16168 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16169 return ExprError();
16170 }
16171 // Build an empty overload set.
16173
16174 // Subscript can only be overloaded as a member function.
16175
16176 // Add operator candidates that are member functions.
16177 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16178
16179 // Add builtin operator candidates.
16180 if (Args.size() == 2)
16181 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16182
16183 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16184
16185 // Perform overload resolution.
16187 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16188 case OR_Success: {
16189 // We found a built-in operator or an overloaded operator.
16190 FunctionDecl *FnDecl = Best->Function;
16191
16192 if (FnDecl) {
16193 // We matched an overloaded operator. Build a call to that
16194 // operator.
16195
16196 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16197
16198 // Convert the arguments.
16200 SmallVector<Expr *, 2> MethodArgs;
16201
16202 // Initialize the object parameter.
16203 if (Method->isExplicitObjectMemberFunction()) {
16204 ExprResult Res =
16206 if (Res.isInvalid())
16207 return ExprError();
16208 Args[0] = Res.get();
16209 ArgExpr = Args;
16210 } else {
16212 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16213 if (Arg0.isInvalid())
16214 return ExprError();
16215
16216 MethodArgs.push_back(Arg0.get());
16217 }
16218
16220 *this, MethodArgs, Method, ArgExpr, LLoc);
16221 if (IsError)
16222 return ExprError();
16223
16224 // Build the actual expression node.
16225 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16226 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16228 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16229 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16230 if (FnExpr.isInvalid())
16231 return ExprError();
16232
16233 // Determine the result type
16234 QualType ResultTy = FnDecl->getReturnType();
16236 ResultTy = ResultTy.getNonLValueExprType(Context);
16237
16239 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16241
16242 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16243 return ExprError();
16244
16245 if (CheckFunctionCall(Method, TheCall,
16246 Method->getType()->castAs<FunctionProtoType>()))
16247 return ExprError();
16248
16250 FnDecl);
16251 } else {
16252 // We matched a built-in operator. Convert the arguments, then
16253 // break out so that we will build the appropriate built-in
16254 // operator node.
16256 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16259 if (ArgsRes0.isInvalid())
16260 return ExprError();
16261 Args[0] = ArgsRes0.get();
16262
16264 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16267 if (ArgsRes1.isInvalid())
16268 return ExprError();
16269 Args[1] = ArgsRes1.get();
16270
16271 break;
16272 }
16273 }
16274
16275 case OR_No_Viable_Function: {
16277 CandidateSet.empty()
16278 ? (PDiag(diag::err_ovl_no_oper)
16279 << Args[0]->getType() << /*subscript*/ 0
16280 << Args[0]->getSourceRange() << Range)
16281 : (PDiag(diag::err_ovl_no_viable_subscript)
16282 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16283 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16284 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16285 return ExprError();
16286 }
16287
16288 case OR_Ambiguous:
16289 if (Args.size() == 2) {
16290 CandidateSet.NoteCandidates(
16292 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16293 << "[]" << Args[0]->getType() << Args[1]->getType()
16294 << Args[0]->getSourceRange() << Range),
16295 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16296 } else {
16297 CandidateSet.NoteCandidates(
16299 PDiag(diag::err_ovl_ambiguous_subscript_call)
16300 << Args[0]->getType()
16301 << Args[0]->getSourceRange() << Range),
16302 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16303 }
16304 return ExprError();
16305
16306 case OR_Deleted: {
16307 StringLiteral *Msg = Best->Function->getDeletedMessage();
16308 CandidateSet.NoteCandidates(
16310 PDiag(diag::err_ovl_deleted_oper)
16311 << "[]" << (Msg != nullptr)
16312 << (Msg ? Msg->getString() : StringRef())
16313 << Args[0]->getSourceRange() << Range),
16314 *this, OCD_AllCandidates, Args, "[]", LLoc);
16315 return ExprError();
16316 }
16317 }
16318
16319 // We matched a built-in operator; build it.
16320 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16321}
16322
16324 SourceLocation LParenLoc,
16325 MultiExprArg Args,
16326 SourceLocation RParenLoc,
16327 Expr *ExecConfig, bool IsExecConfig,
16328 bool AllowRecovery) {
16329 assert(MemExprE->getType() == Context.BoundMemberTy ||
16330 MemExprE->getType() == Context.OverloadTy);
16331
16332 // Dig out the member expression. This holds both the object
16333 // argument and the member function we're referring to.
16334 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16335
16336 // Determine whether this is a call to a pointer-to-member function.
16337 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16338 assert(op->getType() == Context.BoundMemberTy);
16339 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16340
16341 QualType fnType =
16342 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16343
16344 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16345 QualType resultType = proto->getCallResultType(Context);
16347
16348 // Check that the object type isn't more qualified than the
16349 // member function we're calling.
16350 Qualifiers funcQuals = proto->getMethodQuals();
16351
16352 QualType objectType = op->getLHS()->getType();
16353 if (op->getOpcode() == BO_PtrMemI)
16354 objectType = objectType->castAs<PointerType>()->getPointeeType();
16355 Qualifiers objectQuals = objectType.getQualifiers();
16356
16357 Qualifiers difference = objectQuals - funcQuals;
16358 difference.removeObjCGCAttr();
16359 difference.removeAddressSpace();
16360 if (difference) {
16361 std::string qualsString = difference.getAsString();
16362 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16363 << fnType.getUnqualifiedType()
16364 << qualsString
16365 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16366 }
16367
16369 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16371
16372 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16373 call, nullptr))
16374 return ExprError();
16375
16376 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16377 return ExprError();
16378
16379 if (CheckOtherCall(call, proto))
16380 return ExprError();
16381
16382 return MaybeBindToTemporary(call);
16383 }
16384
16385 // We only try to build a recovery expr at this level if we can preserve
16386 // the return type, otherwise we return ExprError() and let the caller
16387 // recover.
16388 auto BuildRecoveryExpr = [&](QualType Type) {
16389 if (!AllowRecovery)
16390 return ExprError();
16391 std::vector<Expr *> SubExprs = {MemExprE};
16392 llvm::append_range(SubExprs, Args);
16393 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16394 Type);
16395 };
16396 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16397 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16398 RParenLoc, CurFPFeatureOverrides());
16399
16400 UnbridgedCastsSet UnbridgedCasts;
16401 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16402 return ExprError();
16403
16404 MemberExpr *MemExpr;
16405 CXXMethodDecl *Method = nullptr;
16406 bool HadMultipleCandidates = false;
16407 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16408 NestedNameSpecifier Qualifier = std::nullopt;
16409 if (isa<MemberExpr>(NakedMemExpr)) {
16410 MemExpr = cast<MemberExpr>(NakedMemExpr);
16412 FoundDecl = MemExpr->getFoundDecl();
16413 Qualifier = MemExpr->getQualifier();
16414 UnbridgedCasts.restore();
16415 } else {
16416 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16417 Qualifier = UnresExpr->getQualifier();
16418
16419 QualType ObjectType = UnresExpr->getBaseType();
16420 Expr::Classification ObjectClassification
16422 : UnresExpr->getBase()->Classify(Context);
16423
16424 // Add overload candidates
16425 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16427
16428 // FIXME: avoid copy.
16429 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16430 if (UnresExpr->hasExplicitTemplateArgs()) {
16431 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16432 TemplateArgs = &TemplateArgsBuffer;
16433 }
16434
16436 E = UnresExpr->decls_end(); I != E; ++I) {
16437
16438 QualType ExplicitObjectType = ObjectType;
16439
16440 NamedDecl *Func = *I;
16441 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16443 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16444
16445 bool HasExplicitParameter = false;
16446 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16447 M && M->hasCXXExplicitFunctionObjectParameter())
16448 HasExplicitParameter = true;
16449 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16450 M &&
16451 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16452 HasExplicitParameter = true;
16453
16454 if (HasExplicitParameter)
16455 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16456
16457 // Microsoft supports direct constructor calls.
16458 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16460 CandidateSet,
16461 /*SuppressUserConversions*/ false);
16462 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16463 // If explicit template arguments were provided, we can't call a
16464 // non-template member function.
16465 if (TemplateArgs)
16466 continue;
16467
16468 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16469 ObjectClassification, Args, CandidateSet,
16470 /*SuppressUserConversions=*/false);
16471 } else {
16473 I.getPair(), ActingDC, TemplateArgs,
16474 ExplicitObjectType, ObjectClassification,
16475 Args, CandidateSet,
16476 /*SuppressUserConversions=*/false);
16477 }
16478 }
16479
16480 HadMultipleCandidates = (CandidateSet.size() > 1);
16481
16482 DeclarationName DeclName = UnresExpr->getMemberName();
16483
16484 UnbridgedCasts.restore();
16485
16487 bool Succeeded = false;
16488 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16489 Best)) {
16490 case OR_Success:
16491 Method = cast<CXXMethodDecl>(Best->Function);
16492 FoundDecl = Best->FoundDecl;
16493 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16494 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16495 break;
16496 // If FoundDecl is different from Method (such as if one is a template
16497 // and the other a specialization), make sure DiagnoseUseOfDecl is
16498 // called on both.
16499 // FIXME: This would be more comprehensively addressed by modifying
16500 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16501 // being used.
16502 if (Method != FoundDecl.getDecl() &&
16504 break;
16505 Succeeded = true;
16506 break;
16507
16509 CandidateSet.NoteCandidates(
16511 UnresExpr->getMemberLoc(),
16512 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16513 << DeclName << MemExprE->getSourceRange()),
16514 *this, OCD_AllCandidates, Args);
16515 break;
16516 case OR_Ambiguous:
16517 CandidateSet.NoteCandidates(
16518 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16519 PDiag(diag::err_ovl_ambiguous_member_call)
16520 << DeclName << MemExprE->getSourceRange()),
16521 *this, OCD_AmbiguousCandidates, Args);
16522 break;
16523 case OR_Deleted:
16525 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16526 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16527 break;
16528 }
16529 // Overload resolution fails, try to recover.
16530 if (!Succeeded)
16531 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16532
16533 ExprResult Res =
16534 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16535 if (Res.isInvalid())
16536 return ExprError();
16537 MemExprE = Res.get();
16538
16539 // If overload resolution picked a static member
16540 // build a non-member call based on that function.
16541 if (Method->isStatic()) {
16542 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16543 ExecConfig, IsExecConfig);
16544 }
16545
16546 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16547 }
16548
16549 QualType ResultType = Method->getReturnType();
16551 ResultType = ResultType.getNonLValueExprType(Context);
16552
16553 assert(Method && "Member call to something that isn't a method?");
16554 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16555
16556 CallExpr *TheCall = nullptr;
16558 if (Method->isExplicitObjectMemberFunction()) {
16559 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16560 NewArgs))
16561 return ExprError();
16562
16563 // Build the actual expression node.
16564 ExprResult FnExpr =
16565 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16566 HadMultipleCandidates, MemExpr->getExprLoc());
16567 if (FnExpr.isInvalid())
16568 return ExprError();
16569
16570 TheCall =
16571 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16572 CurFPFeatureOverrides(), Proto->getNumParams());
16573 TheCall->setUsesMemberSyntax(true);
16574 } else {
16575 // Convert the object argument (for a non-static member function call).
16577 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16578 if (ObjectArg.isInvalid())
16579 return ExprError();
16580 MemExpr->setBase(ObjectArg.get());
16581 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16582 RParenLoc, CurFPFeatureOverrides(),
16583 Proto->getNumParams());
16584 }
16585
16586 // Check for a valid return type.
16587 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16588 TheCall, Method))
16589 return BuildRecoveryExpr(ResultType);
16590
16591 // Convert the rest of the arguments
16592 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16593 RParenLoc))
16594 return BuildRecoveryExpr(ResultType);
16595
16596 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16597
16598 if (CheckFunctionCall(Method, TheCall, Proto))
16599 return ExprError();
16600
16601 // In the case the method to call was not selected by the overloading
16602 // resolution process, we still need to handle the enable_if attribute. Do
16603 // that here, so it will not hide previous -- and more relevant -- errors.
16604 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16605 if (const EnableIfAttr *Attr =
16606 CheckEnableIf(Method, LParenLoc, Args, true)) {
16607 Diag(MemE->getMemberLoc(),
16608 diag::err_ovl_no_viable_member_function_in_call)
16609 << Method << Method->getSourceRange();
16610 Diag(Method->getLocation(),
16611 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16612 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16613 return ExprError();
16614 }
16615 }
16616
16618 TheCall->getDirectCallee()->isPureVirtual()) {
16619 const FunctionDecl *MD = TheCall->getDirectCallee();
16620
16621 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16623 Diag(MemExpr->getBeginLoc(),
16624 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16626 << MD->getParent();
16627
16628 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16629 if (getLangOpts().AppleKext)
16630 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16631 << MD->getParent() << MD->getDeclName();
16632 }
16633 }
16634
16635 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16636 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16637 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16638 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16639 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16640 MemExpr->getMemberLoc());
16641 }
16642
16644 TheCall->getDirectCallee());
16645}
16646
16649 SourceLocation LParenLoc,
16650 MultiExprArg Args,
16651 SourceLocation RParenLoc) {
16652 if (checkPlaceholderForOverload(*this, Obj))
16653 return ExprError();
16654 ExprResult Object = Obj;
16655
16656 UnbridgedCastsSet UnbridgedCasts;
16657 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16658 return ExprError();
16659
16660 assert(Object.get()->getType()->isRecordType() &&
16661 "Requires object type argument");
16662
16663 // C++ [over.call.object]p1:
16664 // If the primary-expression E in the function call syntax
16665 // evaluates to a class object of type "cv T", then the set of
16666 // candidate functions includes at least the function call
16667 // operators of T. The function call operators of T are obtained by
16668 // ordinary lookup of the name operator() in the context of
16669 // (E).operator().
16670 OverloadCandidateSet CandidateSet(LParenLoc,
16672 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16673
16674 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16675 diag::err_incomplete_object_call, Object.get()))
16676 return true;
16677
16678 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16679 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16681 R.suppressAccessDiagnostics();
16682
16683 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16684 Oper != OperEnd; ++Oper) {
16685 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16686 Object.get()->Classify(Context), Args, CandidateSet,
16687 /*SuppressUserConversion=*/false);
16688 }
16689
16690 // When calling a lambda, both the call operator, and
16691 // the conversion operator to function pointer
16692 // are considered. But when constraint checking
16693 // on the call operator fails, it will also fail on the
16694 // conversion operator as the constraints are always the same.
16695 // As the user probably does not intend to perform a surrogate call,
16696 // we filter them out to produce better error diagnostics, ie to avoid
16697 // showing 2 failed overloads instead of one.
16698 bool IgnoreSurrogateFunctions = false;
16699 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16700 const OverloadCandidate &Candidate = *CandidateSet.begin();
16701 if (!Candidate.Viable &&
16703 IgnoreSurrogateFunctions = true;
16704 }
16705
16706 // C++ [over.call.object]p2:
16707 // In addition, for each (non-explicit in C++0x) conversion function
16708 // declared in T of the form
16709 //
16710 // operator conversion-type-id () cv-qualifier;
16711 //
16712 // where cv-qualifier is the same cv-qualification as, or a
16713 // greater cv-qualification than, cv, and where conversion-type-id
16714 // denotes the type "pointer to function of (P1,...,Pn) returning
16715 // R", or the type "reference to pointer to function of
16716 // (P1,...,Pn) returning R", or the type "reference to function
16717 // of (P1,...,Pn) returning R", a surrogate call function [...]
16718 // is also considered as a candidate function. Similarly,
16719 // surrogate call functions are added to the set of candidate
16720 // functions for each conversion function declared in an
16721 // accessible base class provided the function is not hidden
16722 // within T by another intervening declaration.
16723 const auto &Conversions = Record->getVisibleConversionFunctions();
16724 for (auto I = Conversions.begin(), E = Conversions.end();
16725 !IgnoreSurrogateFunctions && I != E; ++I) {
16726 NamedDecl *D = *I;
16727 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16728 if (isa<UsingShadowDecl>(D))
16729 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16730
16731 // Skip over templated conversion functions; they aren't
16732 // surrogates.
16734 continue;
16735
16737 if (!Conv->isExplicit()) {
16738 // Strip the reference type (if any) and then the pointer type (if
16739 // any) to get down to what might be a function type.
16740 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16741 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16742 ConvType = ConvPtrType->getPointeeType();
16743
16744 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16745 {
16746 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16747 Object.get(), Args, CandidateSet);
16748 }
16749 }
16750 }
16751
16752 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16753
16754 // Perform overload resolution.
16756 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16757 Best)) {
16758 case OR_Success:
16759 // Overload resolution succeeded; we'll build the appropriate call
16760 // below.
16761 break;
16762
16763 case OR_No_Viable_Function: {
16765 CandidateSet.empty()
16766 ? (PDiag(diag::err_ovl_no_oper)
16767 << Object.get()->getType() << /*call*/ 1
16768 << Object.get()->getSourceRange())
16769 : (PDiag(diag::err_ovl_no_viable_object_call)
16770 << Object.get()->getType() << Object.get()->getSourceRange());
16771 CandidateSet.NoteCandidates(
16772 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16773 OCD_AllCandidates, Args);
16774 break;
16775 }
16776 case OR_Ambiguous:
16777 if (!R.isAmbiguous())
16778 CandidateSet.NoteCandidates(
16779 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16780 PDiag(diag::err_ovl_ambiguous_object_call)
16781 << Object.get()->getType()
16782 << Object.get()->getSourceRange()),
16783 *this, OCD_AmbiguousCandidates, Args);
16784 break;
16785
16786 case OR_Deleted: {
16787 // FIXME: Is this diagnostic here really necessary? It seems that
16788 // 1. we don't have any tests for this diagnostic, and
16789 // 2. we already issue err_deleted_function_use for this later on anyway.
16790 StringLiteral *Msg = Best->Function->getDeletedMessage();
16791 CandidateSet.NoteCandidates(
16792 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16793 PDiag(diag::err_ovl_deleted_object_call)
16794 << Object.get()->getType() << (Msg != nullptr)
16795 << (Msg ? Msg->getString() : StringRef())
16796 << Object.get()->getSourceRange()),
16797 *this, OCD_AllCandidates, Args);
16798 break;
16799 }
16800 }
16801
16802 if (Best == CandidateSet.end())
16803 return true;
16804
16805 UnbridgedCasts.restore();
16806
16807 if (Best->Function == nullptr) {
16808 // Since there is no function declaration, this is one of the
16809 // surrogate candidates. Dig out the conversion function.
16810 CXXConversionDecl *Conv
16812 Best->Conversions[0].UserDefined.ConversionFunction);
16813
16814 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16815 Best->FoundDecl);
16816 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16817 return ExprError();
16818 assert(Conv == Best->FoundDecl.getDecl() &&
16819 "Found Decl & conversion-to-functionptr should be same, right?!");
16820 // We selected one of the surrogate functions that converts the
16821 // object parameter to a function pointer. Perform the conversion
16822 // on the object argument, then let BuildCallExpr finish the job.
16823
16824 // Create an implicit member expr to refer to the conversion operator.
16825 // and then call it.
16826 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16827 Conv, HadMultipleCandidates);
16828 if (Call.isInvalid())
16829 return ExprError();
16830 // Record usage of conversion in an implicit cast.
16832 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16833 nullptr, VK_PRValue, CurFPFeatureOverrides());
16834
16835 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16836 }
16837
16838 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16839
16840 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16841 // that calls this method, using Object for the implicit object
16842 // parameter and passing along the remaining arguments.
16843 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16844
16845 // An error diagnostic has already been printed when parsing the declaration.
16846 if (Method->isInvalidDecl())
16847 return ExprError();
16848
16849 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16850 unsigned NumParams = Proto->getNumParams();
16851
16852 DeclarationNameInfo OpLocInfo(
16853 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16854 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16855 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16856 Obj, HadMultipleCandidates,
16857 OpLocInfo.getLoc(),
16858 OpLocInfo.getInfo());
16859 if (NewFn.isInvalid())
16860 return true;
16861
16862 SmallVector<Expr *, 8> MethodArgs;
16863 MethodArgs.reserve(NumParams + 1);
16864
16865 bool IsError = false;
16866
16867 // Initialize the object parameter.
16869 if (Method->isExplicitObjectMemberFunction()) {
16870 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16871 } else {
16873 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16874 if (ObjRes.isInvalid())
16875 IsError = true;
16876 else
16877 Object = ObjRes;
16878 MethodArgs.push_back(Object.get());
16879 }
16880
16882 *this, MethodArgs, Method, Args, LParenLoc);
16883
16884 // If this is a variadic call, handle args passed through "...".
16885 if (Proto->isVariadic()) {
16886 // Promote the arguments (C99 6.5.2.2p7).
16887 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16889 Args[i], VariadicCallType::Method, nullptr);
16890 IsError |= Arg.isInvalid();
16891 MethodArgs.push_back(Arg.get());
16892 }
16893 }
16894
16895 if (IsError)
16896 return true;
16897
16898 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16899
16900 // Once we've built TheCall, all of the expressions are properly owned.
16901 QualType ResultTy = Method->getReturnType();
16903 ResultTy = ResultTy.getNonLValueExprType(Context);
16904
16906 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16908
16909 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16910 return true;
16911
16912 if (CheckFunctionCall(Method, TheCall, Proto))
16913 return true;
16914
16916}
16917
16919 SourceLocation OpLoc,
16920 bool *NoArrowOperatorFound) {
16921 assert(Base->getType()->isRecordType() &&
16922 "left-hand side must have class type");
16923
16925 return ExprError();
16926
16927 SourceLocation Loc = Base->getExprLoc();
16928
16929 // C++ [over.ref]p1:
16930 //
16931 // [...] An expression x->m is interpreted as (x.operator->())->m
16932 // for a class object x of type T if T::operator->() exists and if
16933 // the operator is selected as the best match function by the
16934 // overload resolution mechanism (13.3).
16935 DeclarationName OpName =
16936 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16938
16939 if (RequireCompleteType(Loc, Base->getType(),
16940 diag::err_typecheck_incomplete_tag, Base))
16941 return ExprError();
16942
16943 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16944 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16945 R.suppressAccessDiagnostics();
16946
16947 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16948 Oper != OperEnd; ++Oper) {
16949 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16950 {}, CandidateSet,
16951 /*SuppressUserConversion=*/false);
16952 }
16953
16954 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16955
16956 // Perform overload resolution.
16958 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16959 case OR_Success:
16960 // Overload resolution succeeded; we'll build the call below.
16961 break;
16962
16963 case OR_No_Viable_Function: {
16964 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16965 if (CandidateSet.empty()) {
16966 QualType BaseType = Base->getType();
16967 if (NoArrowOperatorFound) {
16968 // Report this specific error to the caller instead of emitting a
16969 // diagnostic, as requested.
16970 *NoArrowOperatorFound = true;
16971 return ExprError();
16972 }
16973 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16974 << BaseType << Base->getSourceRange();
16975 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16976 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16977 << FixItHint::CreateReplacement(OpLoc, ".");
16978 }
16979 } else
16980 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16981 << "operator->" << Base->getSourceRange();
16982 CandidateSet.NoteCandidates(*this, Base, Cands);
16983 return ExprError();
16984 }
16985 case OR_Ambiguous:
16986 if (!R.isAmbiguous())
16987 CandidateSet.NoteCandidates(
16988 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16989 << "->" << Base->getType()
16990 << Base->getSourceRange()),
16992 return ExprError();
16993
16994 case OR_Deleted: {
16995 StringLiteral *Msg = Best->Function->getDeletedMessage();
16996 CandidateSet.NoteCandidates(
16997 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16998 << "->" << (Msg != nullptr)
16999 << (Msg ? Msg->getString() : StringRef())
17000 << Base->getSourceRange()),
17001 *this, OCD_AllCandidates, Base);
17002 return ExprError();
17003 }
17004 }
17005
17006 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
17007
17008 // Convert the object parameter.
17009 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
17010
17011 if (Method->isExplicitObjectMemberFunction()) {
17013 if (R.isInvalid())
17014 return ExprError();
17015 Base = R.get();
17016 } else {
17018 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17019 if (BaseResult.isInvalid())
17020 return ExprError();
17021 Base = BaseResult.get();
17022 }
17023
17024 // Build the operator call.
17025 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17026 Base, HadMultipleCandidates, OpLoc);
17027 if (FnExpr.isInvalid())
17028 return ExprError();
17029
17030 QualType ResultTy = Method->getReturnType();
17032 ResultTy = ResultTy.getNonLValueExprType(Context);
17033
17034 CallExpr *TheCall =
17035 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17036 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17037
17038 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17039 return ExprError();
17040
17041 if (CheckFunctionCall(Method, TheCall,
17042 Method->getType()->castAs<FunctionProtoType>()))
17043 return ExprError();
17044
17046}
17047
17049 DeclarationNameInfo &SuffixInfo,
17050 ArrayRef<Expr*> Args,
17051 SourceLocation LitEndLoc,
17052 TemplateArgumentListInfo *TemplateArgs) {
17053 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17054
17055 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17057 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17058 TemplateArgs);
17059
17060 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17061
17062 // Perform overload resolution. This will usually be trivial, but might need
17063 // to perform substitutions for a literal operator template.
17065 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17066 case OR_Success:
17067 case OR_Deleted:
17068 break;
17069
17071 CandidateSet.NoteCandidates(
17072 PartialDiagnosticAt(UDSuffixLoc,
17073 PDiag(diag::err_ovl_no_viable_function_in_call)
17074 << R.getLookupName()),
17075 *this, OCD_AllCandidates, Args);
17076 return ExprError();
17077
17078 case OR_Ambiguous:
17079 CandidateSet.NoteCandidates(
17080 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17081 << R.getLookupName()),
17082 *this, OCD_AmbiguousCandidates, Args);
17083 return ExprError();
17084 }
17085
17086 FunctionDecl *FD = Best->Function;
17087 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17088 nullptr, HadMultipleCandidates,
17089 SuffixInfo.getLoc(),
17090 SuffixInfo.getInfo());
17091 if (Fn.isInvalid())
17092 return true;
17093
17094 // Check the argument types. This should almost always be a no-op, except
17095 // that array-to-pointer decay is applied to string literals.
17096 Expr *ConvArgs[2];
17097 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17100 SourceLocation(), Args[ArgIdx]);
17101 if (InputInit.isInvalid())
17102 return true;
17103 ConvArgs[ArgIdx] = InputInit.get();
17104 }
17105
17106 QualType ResultTy = FD->getReturnType();
17108 ResultTy = ResultTy.getNonLValueExprType(Context);
17109
17111 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17112 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17113
17114 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17115 return ExprError();
17116
17117 if (CheckFunctionCall(FD, UDL, nullptr))
17118 return ExprError();
17119
17121}
17122
17125 SourceLocation RangeLoc,
17126 const DeclarationNameInfo &NameInfo,
17127 LookupResult &MemberLookup,
17128 OverloadCandidateSet *CandidateSet,
17129 Expr *Range, ExprResult *CallExpr) {
17130 Scope *S = nullptr;
17131
17133 if (!MemberLookup.empty()) {
17134 ExprResult MemberRef =
17135 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17136 /*IsPtr=*/false, CXXScopeSpec(),
17137 /*TemplateKWLoc=*/SourceLocation(),
17138 /*FirstQualifierInScope=*/nullptr,
17139 MemberLookup,
17140 /*TemplateArgs=*/nullptr, S);
17141 if (MemberRef.isInvalid()) {
17142 *CallExpr = ExprError();
17143 return FRS_DiagnosticIssued;
17144 }
17145 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17146 if (CallExpr->isInvalid()) {
17147 *CallExpr = ExprError();
17148 return FRS_DiagnosticIssued;
17149 }
17150 } else {
17151 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17153 NameInfo, UnresolvedSet<0>());
17154 if (FnR.isInvalid())
17155 return FRS_DiagnosticIssued;
17157
17158 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17159 CandidateSet, CallExpr);
17160 if (CandidateSet->empty() || CandidateSetError) {
17161 *CallExpr = ExprError();
17162 return FRS_NoViableFunction;
17163 }
17165 OverloadingResult OverloadResult =
17166 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17167
17168 if (OverloadResult == OR_No_Viable_Function) {
17169 *CallExpr = ExprError();
17170 return FRS_NoViableFunction;
17171 }
17172 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17173 Loc, nullptr, CandidateSet, &Best,
17174 OverloadResult,
17175 /*AllowTypoCorrection=*/false);
17176 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17177 *CallExpr = ExprError();
17178 return FRS_DiagnosticIssued;
17179 }
17180 }
17181 return FRS_Success;
17182}
17183
17185 FunctionDecl *Fn) {
17186 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17187 ExprResult SubExpr =
17188 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17189 if (SubExpr.isInvalid())
17190 return ExprError();
17191 if (SubExpr.get() == PE->getSubExpr())
17192 return PE;
17193
17194 return new (Context)
17195 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17196 }
17197
17198 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17199 ExprResult SubExpr =
17200 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17201 if (SubExpr.isInvalid())
17202 return ExprError();
17203 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17204 SubExpr.get()->getType()) &&
17205 "Implicit cast type cannot be determined from overload");
17206 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17207 if (SubExpr.get() == ICE->getSubExpr())
17208 return ICE;
17209
17210 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17211 SubExpr.get(), nullptr, ICE->getValueKind(),
17213 }
17214
17215 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17216 if (!GSE->isResultDependent()) {
17217 ExprResult SubExpr =
17218 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17219 if (SubExpr.isInvalid())
17220 return ExprError();
17221 if (SubExpr.get() == GSE->getResultExpr())
17222 return GSE;
17223
17224 // Replace the resulting type information before rebuilding the generic
17225 // selection expression.
17226 ArrayRef<Expr *> A = GSE->getAssocExprs();
17227 SmallVector<Expr *, 4> AssocExprs(A);
17228 unsigned ResultIdx = GSE->getResultIndex();
17229 AssocExprs[ResultIdx] = SubExpr.get();
17230
17231 if (GSE->isExprPredicate())
17233 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17234 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17235 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17236 ResultIdx);
17238 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17239 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17240 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17241 ResultIdx);
17242 }
17243 // Rather than fall through to the unreachable, return the original generic
17244 // selection expression.
17245 return GSE;
17246 }
17247
17248 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17249 assert(UnOp->getOpcode() == UO_AddrOf &&
17250 "Can only take the address of an overloaded function");
17251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17252 if (!Method->isImplicitObjectMemberFunction()) {
17253 // Do nothing: the address of static and
17254 // explicit object member functions is a (non-member) function pointer.
17255 } else {
17256 // Fix the subexpression, which really has to be an
17257 // UnresolvedLookupExpr holding an overloaded member function
17258 // or template.
17259 ExprResult SubExpr =
17260 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17261 if (SubExpr.isInvalid())
17262 return ExprError();
17263 if (SubExpr.get() == UnOp->getSubExpr())
17264 return UnOp;
17265
17266 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17267 SubExpr.get(), Method))
17268 return ExprError();
17269
17270 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17271 "fixed to something other than a decl ref");
17272 NestedNameSpecifier Qualifier =
17273 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17274 assert(Qualifier &&
17275 "fixed to a member ref with no nested name qualifier");
17276
17277 // We have taken the address of a pointer to member
17278 // function. Perform the computation here so that we get the
17279 // appropriate pointer to member type.
17280 QualType MemPtrType = Context.getMemberPointerType(
17281 Fn->getType(), Qualifier,
17282 cast<CXXRecordDecl>(Method->getDeclContext()));
17283 // Under the MS ABI, lock down the inheritance model now.
17284 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17285 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17286
17287 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17288 MemPtrType, VK_PRValue, OK_Ordinary,
17289 UnOp->getOperatorLoc(), false,
17291 }
17292 }
17293 ExprResult SubExpr =
17294 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17295 if (SubExpr.isInvalid())
17296 return ExprError();
17297 if (SubExpr.get() == UnOp->getSubExpr())
17298 return UnOp;
17299
17300 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17301 SubExpr.get());
17302 }
17303
17304 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17305 if (Found.getAccess() == AS_none) {
17307 }
17308 // FIXME: avoid copy.
17309 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17310 if (ULE->hasExplicitTemplateArgs()) {
17311 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17312 TemplateArgs = &TemplateArgsBuffer;
17313 }
17314
17315 QualType Type = Fn->getType();
17316 ExprValueKind ValueKind =
17317 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17318 ? VK_LValue
17319 : VK_PRValue;
17320
17321 // FIXME: Duplicated from BuildDeclarationNameExpr.
17322 if (unsigned BID = Fn->getBuiltinID()) {
17323 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17324 Type = Context.BuiltinFnTy;
17325 ValueKind = VK_PRValue;
17326 }
17327 }
17328
17330 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17331 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17332 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17333 return DRE;
17334 }
17335
17336 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17337 // FIXME: avoid copy.
17338 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17339 if (MemExpr->hasExplicitTemplateArgs()) {
17340 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17341 TemplateArgs = &TemplateArgsBuffer;
17342 }
17343
17344 Expr *Base;
17345
17346 // If we're filling in a static method where we used to have an
17347 // implicit member access, rewrite to a simple decl ref.
17348 if (MemExpr->isImplicitAccess()) {
17349 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17351 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17352 MemExpr->getQualifierLoc(), Found.getDecl(),
17353 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17354 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17355 return DRE;
17356 } else {
17357 SourceLocation Loc = MemExpr->getMemberLoc();
17358 if (MemExpr->getQualifier())
17359 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17360 Base =
17361 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17362 }
17363 } else
17364 Base = MemExpr->getBase();
17365
17366 ExprValueKind valueKind;
17367 QualType type;
17368 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17369 valueKind = VK_LValue;
17370 type = Fn->getType();
17371 } else {
17372 valueKind = VK_PRValue;
17373 type = Context.BoundMemberTy;
17374 }
17375
17376 return BuildMemberExpr(
17377 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17378 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17379 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17380 type, valueKind, OK_Ordinary, TemplateArgs);
17381 }
17382
17383 llvm_unreachable("Invalid reference to overloaded function");
17384}
17385
17391
17392bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17394 if (!PartialOverloading || !Function)
17395 return true;
17396 if (Function->isVariadic())
17397 return false;
17398 if (const auto *Proto =
17399 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17400 if (Proto->isTemplateVariadic())
17401 return false;
17402 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17403 if (const auto *Proto =
17404 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17405 if (Proto->isTemplateVariadic())
17406 return false;
17407 return true;
17408}
17409
17411 DeclarationName Name,
17412 OverloadCandidateSet &CandidateSet,
17413 FunctionDecl *Fn, MultiExprArg Args,
17414 bool IsMember) {
17415 StringLiteral *Msg = Fn->getDeletedMessage();
17416 CandidateSet.NoteCandidates(
17417 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17418 << IsMember << Name << (Msg != nullptr)
17419 << (Msg ? Msg->getString() : StringRef())
17420 << Range),
17421 *this, OCD_AllCandidates, Args);
17422}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress, TemplateSpecCandidateSetKind CandidateSetKind=TemplateSpecCandidateSetKind::Normal)
Diagnose a failed template-argument deduction.
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:484
bool isFloat() const
Definition APValue.h:489
bool isInt() const
Definition APValue.h:488
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
APFloat & getFloat()
Definition APValue.h:525
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:827
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:980
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:943
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:942
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:4006
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:316
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8303
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4049
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2189
StringRef getOpcodeStr() const
Definition Expr.h:4115
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2142
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:5108
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4190
Pointer to a block type.
Definition TypeBase.h:3656
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3292
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:2637
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3106
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2972
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3004
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3008
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:182
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:699
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2288
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:629
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1564
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:289
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2954
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3137
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3118
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3336
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:3355
QualType getElementType() const
Definition TypeBase.h:3365
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:5130
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4520
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4517
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
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:1281
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:1474
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
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:798
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:783
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:774
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:610
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4145
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4363
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4261
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1968
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1952
const Expr * getExpr() const
Definition DeclCXX.h:1953
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
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:3350
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4242
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:842
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:846
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:822
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:4081
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4381
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3294
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
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:105
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2122
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2151
Represents a function declaration or definition.
Definition Decl.h:2058
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2819
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2927
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4236
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3805
param_iterator param_end()
Definition Decl.h:2917
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3709
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3908
QualType getReturnType() const
Definition Decl.h:2975
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2904
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:4307
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4356
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3790
param_iterator param_begin()
Definition Decl.h:2916
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3120
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4372
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4300
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3912
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2596
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4173
bool isConsteval() const
Definition Decl.h:2608
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3753
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3287
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:2992
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:3758
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3869
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2815
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5925
unsigned getNumParams() const
Definition TypeBase.h:5699
Qualifiers getMethodQuals() const
Definition TypeBase.h:5847
QualType getParamType(unsigned i) const
Definition TypeBase.h:5701
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5861
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:4728
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4799
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4656
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
ExtInfo getExtInfo() const
Definition TypeBase.h:4973
CallingConv getCallConv() const
Definition TypeBase.h:4972
QualType getReturnType() const
Definition TypeBase.h:4957
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4985
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:4729
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:3864
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2081
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:623
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:674
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:771
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:678
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:828
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:682
bool hasInitializerListContainerType() const
Definition Overload.h:810
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:735
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:817
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:686
QualType getInitializerListContainerType() const
Definition Overload.h:820
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5319
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5435
unsigned getNumInits() const
Definition Expr.h:5352
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2507
const Expr * getInit(unsigned Init) const
Definition Expr.h:5374
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2525
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
bool isCompatibleWithMSVC() const
Represents the results of name lookup.
Definition Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition Lookup.h:488
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition Lookup.h:643
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4465
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3375
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3564
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3486
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3458
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3472
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3593
Expr * getBase() const
Definition Expr.h:3452
void setBase(Expr *E)
Definition Expr.h:3451
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1802
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3570
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3462
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3799
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5701
QualType getPointeeType() const
Definition TypeBase.h:3785
Describes a module or submodule.
Definition Module.h:340
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:240
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
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:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8066
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8122
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8211
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8180
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8134
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8174
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1915
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8186
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1189
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
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:1361
bool shouldDeferTemplateArgumentDeduction(const Sema &S) const
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1459
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1393
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:1409
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1351
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1186
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1182
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1177
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1172
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1191
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:1369
SourceLocation getLocation() const
Definition Overload.h:1349
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1424
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1350
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1384
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:3131
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3283
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3192
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3247
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3244
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3222
decls_iterator decls_begin() const
Definition ExprCXX.h:3224
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3235
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3257
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3253
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3341
decls_iterator decls_end() const
Definition ExprCXX.h:3227
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3241
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2193
Represents a parameter to a function.
Definition Decl.h:1819
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3045
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5202
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8588
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8582
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8593
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3716
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8504
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8630
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
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:8689
QualType getCanonicalType() const
Definition TypeBase.h:8556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8598
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8658
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8577
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8625
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8550
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8669
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8536
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8444
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8451
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4824
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:854
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:861
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
bool hasOnlyConst() const
Definition TypeBase.h:459
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasConst() const
Definition TypeBase.h:458
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasRestrict() const
Definition TypeBase.h:478
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeUnaligned()
Definition TypeBase.h:516
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
bool hasVolatile() const
Definition TypeBase.h:468
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3749
Represents a struct/union/class.
Definition Decl.h:4459
field_range fields() const
Definition Decl.h:4662
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4647
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
QualType getPointeeType() const
Definition TypeBase.h:3705
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:1539
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1584
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:459
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:396
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:406
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:308
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10350
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
RAII class to control scope of DeferDiags.
Definition Sema.h:10073
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1385
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1420
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:12539
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12573
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1447
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:10091
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:9359
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9386
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9371
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9367
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:417
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:1472
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:10433
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10436
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10442
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10440
@ AR_dependent
Definition Sema.h:1691
@ AR_accessible
Definition Sema.h:1689
@ AR_inaccessible
Definition Sema.h:1690
@ AR_delayed
Definition Sema.h:1692
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:2080
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:1758
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:1305
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:701
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:227
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:933
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:1517
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:763
ASTContext & getASTContext() const
Definition Sema.h:936
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:777
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
@ FRS_Success
Definition Sema.h:10821
@ FRS_DiagnosticIssued
Definition Sema.h:10823
@ FRS_NoViableFunction
Definition Sema.h:10822
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9352
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:10142
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:1209
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:3650
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:12237
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:277
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:929
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:1303
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:1482
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9351
MemberPointerConversionDirection
Definition Sema.h:10274
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:10461
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
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:15604
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9887
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:7001
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:1445
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8194
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:14045
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:7498
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:13788
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:15559
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:126
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:6764
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6733
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:10266
SourceManager & SourceMgr
Definition Sema.h:1308
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1307
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:523
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:6441
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:1452
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:8674
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
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h: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
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1810
StringRef getString() const
Definition Expr.h:1878
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:685
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:739
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:724
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:3672
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBlockPointerType() const
Definition TypeBase.h:8761
bool isVoidType() const
Definition TypeBase.h:9113
bool isBooleanType() const
Definition TypeBase.h:9250
bool isObjCBuiltinType() const
Definition TypeBase.h:8971
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
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:2026
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isIncompleteArrayType() const
Definition TypeBase.h:8848
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isFloat16Type() const
Definition TypeBase.h:9122
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
bool isRValueReferenceType() const
Definition TypeBase.h:8773
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:8844
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9280
bool isArrayType() const
Definition TypeBase.h:8840
bool isCharType() const
Definition Type.cpp:2223
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9185
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2452
bool isPointerType() const
Definition TypeBase.h:8741
bool isArrayParameterType() const
Definition TypeBase.h:8856
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9157
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2697
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
bool isReferenceType() const
Definition TypeBase.h:8765
bool isEnumeralType() const
Definition TypeBase.h:8872
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2186
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8941
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9235
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2259
bool isExtVectorBoolType() const
Definition TypeBase.h:8888
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8928
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2867
bool isLValueReferenceType() const
Definition TypeBase.h:8769
bool isBitIntType() const
Definition TypeBase.h:9016
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2533
bool isAnyComplexType() const
Definition TypeBase.h:8876
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9173
bool isHalfType() const
Definition TypeBase.h:9117
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9095
bool isQueueT() const
Definition TypeBase.h:8997
bool isMemberPointerType() const
Definition TypeBase.h:8822
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9263
bool isObjCIdType() const
Definition TypeBase.h:8953
bool isMatrixType() const
Definition TypeBase.h:8904
bool isOverflowBehaviorType() const
Definition TypeBase.h:8912
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9256
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8989
bool isBFloat16Type() const
Definition TypeBase.h:9134
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2557
bool isFunctionType() const
Definition TypeBase.h:8737
bool isObjCObjectPointerType() const
Definition TypeBase.h:8920
bool isVectorType() const
Definition TypeBase.h:8880
bool isObjCClassType() const
Definition TypeBase.h:8959
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2435
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2718
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9070
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:2362
bool isAnyPointerType() const
Definition TypeBase.h:8749
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:8985
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9340
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9150
bool isRecordType() const
Definition TypeBase.h:8868
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2255
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1436
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5165
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1412
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3389
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3458
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4125
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4233
QualType getBaseType() const
Definition ExprCXX.h:4207
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4217
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4198
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4243
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4237
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:643
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:973
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:289
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
Top level wrappers for InstallAPI frontend operations.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:818
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:829
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:825
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:821
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:65
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
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:860
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:888
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:897
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:880
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:884
@ 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:925
@ ovl_fail_too_few_arguments
Definition Overload.h:862
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:904
@ ovl_fail_too_many_arguments
Definition Overload.h:861
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:912
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:921
@ ovl_fail_bad_conversion
Definition Overload.h:863
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:893
@ ovl_fail_bad_deduction
Definition Overload.h:864
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:908
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:917
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:901
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:869
@ Comparison
A comparison.
Definition Sema.h:662
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1053
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:930
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TemplateSpecCandidateSetKind
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:684
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:707
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:728
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:686
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:724
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:582
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:218
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2018
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:316
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:375
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:425
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:420
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:423
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:396
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:382
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:418
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:427
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:415
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:385
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:379
@ Success
Template argument deduction was successful.
Definition Sema.h:377
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:399
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:388
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:402
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:391
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:412
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:429
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:406
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:409
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1520
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:833
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:836
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:841
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:839
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:837
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:840
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:6034
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:443
__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:523
ConversionSet::const_iterator const_iterator
Definition Overload.h:559
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:524
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:550
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:608
QualType getFromType() const
Definition Overload.h:607
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:1103
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:657
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:659
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:641
SmallVectorImpl< PartialDiagnosticAt > * ExtendedDiag
Location where we spot ptr to int cast or null subobject while evaluating constant expression in MS c...
Definition Expr.h:645
Extra information about a function prototype.
Definition TypeBase.h:5506
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5511
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1196
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:1218
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1245
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1207
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1209
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1235
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:934
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:999
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:990
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1064
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1038
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1003
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:980
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:948
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:944
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:939
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1011
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:960
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:974
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1029
unsigned getNumParams() const
Definition Overload.h:1077
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1007
unsigned TookAddressOfOverload
Definition Overload.h:993
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1016
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1020
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:957
DeductionFailureInfo DeductionFailure
Definition Overload.h:1023
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:964
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:952
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1034
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10553
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10560
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13284
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13333
Abstract class used to diagnose incomplete types.
Definition Sema.h:8271
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
void NoteDeductionFailure(Sema &S, bool ForTakingAddress, TemplateSpecCandidateSetKind CandidateSetKind)
Diagnose a template argument deduction failure.
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:478
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:490
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:512
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:503
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:507
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:498
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:517
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.