clang 24.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
57
59 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
66 Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
67 FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
68 bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo,
69 const TemplateArgumentListInfo *TemplateArgs) {
70 SourceLocation Loc = NameInfo.getLoc();
71
72 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
73 return ExprError();
74 // If FoundDecl is different from Fn (such as if one is a template
75 // and the other a specialization), make sure DiagnoseUseOfDecl is
76 // called on both.
77 // FIXME: This would be more comprehensively addressed by modifying
78 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
79 // being used.
80 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
81 return ExprError();
82 auto *DRE = DeclRefExpr::Create(S.Context, QualifierLoc, TemplateKWLoc, Fn,
83 /*RefersToEnclosingVariableOrCapture=*/false,
84 NameInfo, Fn->getType(), VK_LValue, FoundDecl,
85 TemplateArgs);
86 if (HadMultipleCandidates)
87 DRE->setHadMultipleCandidates(true);
88
90 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
91 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
92 S.ResolveExceptionSpec(Loc, FPT);
93 DRE->setType(Fn->getType());
94 }
95 }
96 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
97 CK_FunctionToPointerDecay);
98}
99
101 NamedDecl *FoundDecl, const Expr *Base,
102 bool HadMultipleCandidates,
103 const DeclarationNameInfo &NameInfo) {
104 return CreateFunctionRefExpr(S, /*QualifierLoc=*/{}, /*TemplateKWLoc=*/{}, Fn,
105 FoundDecl, Base, HadMultipleCandidates, NameInfo,
106 /*TemplateArgs=*/nullptr);
107}
108
110 NamedDecl *FoundDecl, const Expr *Base,
111 bool HadMultipleCandidates,
112 SourceLocation Loc) {
113 return CreateFunctionRefExpr(S, Fn, FoundDecl, Base, HadMultipleCandidates,
114 DeclarationNameInfo(Fn->getDeclName(), Loc));
115}
116
117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
118 bool InOverloadResolution,
120 bool CStyle,
121 bool AllowObjCWritebackConversion);
122
124 QualType &ToType,
125 bool InOverloadResolution,
127 bool CStyle);
129IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
131 OverloadCandidateSet& Conversions,
132 AllowedExplicit AllowExplicit,
133 bool AllowObjCConversionOnExplicit);
134
137 const StandardConversionSequence& SCS1,
138 const StandardConversionSequence& SCS2);
139
142 const StandardConversionSequence& SCS1,
143 const StandardConversionSequence& SCS2);
144
147 const StandardConversionSequence &SCS1,
148 const StandardConversionSequence &SCS2);
149
152 const StandardConversionSequence& SCS1,
153 const StandardConversionSequence& SCS2);
154
155/// GetConversionRank - Retrieve the implicit conversion rank
156/// corresponding to the given implicit conversion kind.
158 static const ImplicitConversionRank Rank[] = {
185 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
186 // it was omitted by the patch that added
187 // ICK_Zero_Event_Conversion
188 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
189 // it was omitted by the patch that added
190 // ICK_Zero_Queue_Conversion
199 };
200 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
201 return Rank[(int)Kind];
202}
203
222
223/// GetImplicitConversionName - Return the name of this kind of
224/// implicit conversion.
226 static const char *const Name[] = {
227 "No conversion",
228 "Lvalue-to-rvalue",
229 "Array-to-pointer",
230 "Function-to-pointer",
231 "Function pointer conversion",
232 "Qualification",
233 "Integral promotion",
234 "Floating point promotion",
235 "Complex promotion",
236 "Integral conversion",
237 "Floating conversion",
238 "Complex conversion",
239 "Floating-integral conversion",
240 "Pointer conversion",
241 "Pointer-to-member conversion",
242 "Boolean conversion",
243 "Compatible-types conversion",
244 "Derived-to-base conversion",
245 "Vector conversion",
246 "SVE Vector conversion",
247 "RVV Vector conversion",
248 "Vector splat",
249 "Complex-real conversion",
250 "Block Pointer conversion",
251 "Transparent Union Conversion",
252 "Writeback conversion",
253 "OpenCL Zero Event Conversion",
254 "OpenCL Zero Queue Conversion",
255 "C specific type conversion",
256 "Incompatible pointer conversion",
257 "Fixed point conversion",
258 "HLSL vector truncation",
259 "HLSL matrix truncation",
260 "Non-decaying array conversion",
261 "HLSL vector splat",
262 "HLSL matrix splat",
263 };
264 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
265 return Name[Kind];
266}
267
268/// StandardConversionSequence - Set the standard conversion
269/// sequence to the identity conversion.
287
288/// getRank - Retrieve the rank of this standard conversion sequence
289/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
290/// implicit conversions.
303
304/// isPointerConversionToBool - Determines whether this conversion is
305/// a conversion of a pointer or pointer-to-member to bool. This is
306/// used as part of the ranking of standard conversion sequences
307/// (C++ 13.3.3.2p4).
309 // Note that FromType has not necessarily been transformed by the
310 // array-to-pointer or function-to-pointer implicit conversions, so
311 // check for their presence as well as checking whether FromType is
312 // a pointer.
313 if (getToType(1)->isBooleanType() &&
314 (getFromType()->isPointerType() ||
315 getFromType()->isMemberPointerType() ||
316 getFromType()->isObjCObjectPointerType() ||
317 getFromType()->isBlockPointerType() ||
319 return true;
320
321 return false;
322}
323
324/// isPointerConversionToVoidPointer - Determines whether this
325/// conversion is a conversion of a pointer to a void pointer. This is
326/// used as part of the ranking of standard conversion sequences (C++
327/// 13.3.3.2p4).
328bool
331 QualType FromType = getFromType();
332 QualType ToType = getToType(1);
333
334 // Note that FromType has not necessarily been transformed by the
335 // array-to-pointer implicit conversion, so check for its presence
336 // and redo the conversion to get a pointer.
338 FromType = Context.getArrayDecayedType(FromType);
339
340 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
341 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
342 return ToPtrType->getPointeeType()->isVoidType();
343
344 return false;
345}
346
347/// Skip any implicit casts which could be either part of a narrowing conversion
348/// or after one in an implicit conversion.
350 const Expr *Converted) {
351 // We can have cleanups wrapping the converted expression; these need to be
352 // preserved so that destructors run if necessary.
353 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
354 Expr *Inner =
355 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
356 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
357 EWC->getObjects());
358 }
359
360 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
361 switch (ICE->getCastKind()) {
362 case CK_NoOp:
363 case CK_IntegralCast:
364 case CK_IntegralToBoolean:
365 case CK_IntegralToFloating:
366 case CK_BooleanToSignedIntegral:
367 case CK_FloatingToIntegral:
368 case CK_FloatingToBoolean:
369 case CK_FloatingCast:
370 Converted = ICE->getSubExpr();
371 continue;
372
373 default:
374 return Converted;
375 }
376 }
377
378 return Converted;
379}
380
381/// Check if this standard conversion sequence represents a narrowing
382/// conversion, according to C++11 [dcl.init.list]p7.
383///
384/// \param Ctx The AST context.
385/// \param Converted The result of applying this standard conversion sequence.
386/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
387/// value of the expression prior to the narrowing conversion.
388/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
389/// type of the expression prior to the narrowing conversion.
390/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
391/// from floating point types to integral types should be ignored.
392/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
393/// to conform MSVC compiler behavior.
395 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
396 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
397 bool AllowRelaxedEval) const {
398 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
399 "narrowing check outside C++");
400
401 // C++11 [dcl.init.list]p7:
402 // A narrowing conversion is an implicit conversion ...
403 QualType FromType = getToType(0);
404 QualType ToType = getToType(1);
405
406 // A conversion to an enumeration type is narrowing if the conversion to
407 // the underlying type is narrowing. This only arises for expressions of
408 // the form 'Enum{init}'.
409 if (const auto *ED = ToType->getAsEnumDecl())
410 ToType = ED->getIntegerType();
411
412 switch (Second) {
413 // 'bool' is an integral type; dispatch to the right place to handle it.
415 if (FromType->isRealFloatingType())
416 goto FloatingIntegralConversion;
418 goto IntegralConversion;
419 // -- from a pointer type or pointer-to-member type to bool, or
420 return NK_Type_Narrowing;
421
422 // -- from a floating-point type to an integer type, or
423 //
424 // -- from an integer type or unscoped enumeration type to a floating-point
425 // type, except where the source is a constant expression and the actual
426 // value after conversion will fit into the target type and will produce
427 // the original value when converted back to the original type, or
429 FloatingIntegralConversion:
430 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
431 return NK_Type_Narrowing;
432 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
433 ToType->isRealFloatingType()) {
434 if (IgnoreFloatToIntegralConversion)
435 return NK_Not_Narrowing;
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
437 assert(Initializer && "Unknown conversion expression");
438
439 // If it's value-dependent, we can't tell whether it's narrowing.
440 if (Initializer->isValueDependent())
442
443 if (std::optional<llvm::APSInt> IntConstantValue =
444 Initializer->getIntegerConstantExpr(Ctx)) {
445 // Convert the integer to the floating type.
446 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
447 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
448 llvm::APFloat::rmNearestTiesToEven);
449 // And back.
450 llvm::APSInt ConvertedValue = *IntConstantValue;
451 bool ignored;
452 llvm::APFloat::opStatus Status = Result.convertToInteger(
453 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
454 // If the converted-back integer has unspecified value, or if the
455 // resulting value is different, this was a narrowing conversion.
456 if (Status == llvm::APFloat::opInvalidOp ||
457 *IntConstantValue != ConvertedValue) {
458 ConstantValue = APValue(*IntConstantValue);
459 ConstantType = Initializer->getType();
461 }
462 } else {
463 // Variables are always narrowings.
465 }
466 }
467 return NK_Not_Narrowing;
468
469 // -- from long double to double or float, or from double to float, except
470 // where the source is a constant expression and the actual value after
471 // conversion is within the range of values that can be represented (even
472 // if it cannot be represented exactly), or
474 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
475 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
476 // FromType is larger than ToType.
477 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
478
479 // If it's value-dependent, we can't tell whether it's narrowing.
480 if (Initializer->isValueDependent())
482
484 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
485 ((Ctx.getLangOpts().CPlusPlus &&
486 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue,
487 AllowRelaxedEval)))) {
488 // Constant!
489 if (Ctx.getLangOpts().C23)
490 ConstantValue = R.Val;
491 assert(ConstantValue.isFloat());
492 llvm::APFloat FloatVal = ConstantValue.getFloat();
493 // Convert the source value into the target type.
494 bool ignored;
495 llvm::APFloat Converted = FloatVal;
496 llvm::APFloat::opStatus ConvertStatus =
497 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
498 llvm::APFloat::rmNearestTiesToEven, &ignored);
499 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
500 llvm::APFloat::rmNearestTiesToEven, &ignored);
501 if (Ctx.getLangOpts().C23) {
502 if (FloatVal.isNaN() && Converted.isNaN() &&
503 !FloatVal.isSignaling() && !Converted.isSignaling()) {
504 // Quiet NaNs are considered the same value, regardless of
505 // payloads.
506 return NK_Not_Narrowing;
507 }
508 // For normal values, check exact equality.
509 if (!Converted.bitwiseIsEqual(FloatVal)) {
510 ConstantType = Initializer->getType();
512 }
513 } else {
514 // If there was no overflow, the source value is within the range of
515 // values that can be represented.
516 if (ConvertStatus & llvm::APFloat::opOverflow) {
517 ConstantType = Initializer->getType();
519 }
520 }
521 } else {
523 }
524 }
525 return NK_Not_Narrowing;
526
527 // -- from an integer type or unscoped enumeration type to an integer type
528 // that cannot represent all the values of the original type, except where
529 // (CWG2627) -- the source is a bit-field whose width w is less than that
530 // of its type (or, for an enumeration type, its underlying type) and the
531 // target type can represent all the values of a hypothetical extended
532 // integer type with width w and with the same signedness as the original
533 // type or
534 // -- the source is a constant expression and the actual value after
535 // conversion will fit into the target type and will produce the original
536 // value when converted back to the original type.
538 IntegralConversion: {
539 assert(FromType->isIntegralOrUnscopedEnumerationType());
540 assert(ToType->isIntegralOrUnscopedEnumerationType());
541 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
542 unsigned FromWidth = Ctx.getIntWidth(FromType);
543 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
544 const unsigned ToWidth = Ctx.getIntWidth(ToType);
545
546 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
547 bool ToSigned, unsigned ToWidth) {
548 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
549 !(FromSigned && !ToSigned);
550 };
551
552 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
553 return NK_Not_Narrowing;
554
555 // Not all values of FromType can be represented in ToType.
556 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
557
558 bool DependentBitField = false;
559 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
560 if (BitField->getBitWidth()->isValueDependent())
561 DependentBitField = true;
562 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
563 BitFieldWidth < FromWidth) {
564 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
565 return NK_Not_Narrowing;
566
567 // The initializer will be truncated to the bit-field width
568 FromWidth = BitFieldWidth;
569 }
570 }
571
572 // If it's value-dependent, we can't tell whether it's narrowing.
573 if (Initializer->isValueDependent())
575
576 std::optional<llvm::APSInt> OptInitializerValue =
577 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
578 if (!OptInitializerValue) {
579 // If the bit-field width was dependent, it might end up being small
580 // enough to fit in the target type (unless the target type is unsigned
581 // and the source type is signed, in which case it will never fit)
582 if (DependentBitField && !(FromSigned && !ToSigned))
584
585 // Otherwise, such a conversion is always narrowing
587 }
588 llvm::APSInt &InitializerValue = *OptInitializerValue;
589 bool Narrowing = false;
590 if (FromWidth < ToWidth) {
591 // Negative -> unsigned is narrowing. Otherwise, more bits is never
592 // narrowing.
593 if (InitializerValue.isSigned() && InitializerValue.isNegative())
594 Narrowing = true;
595 } else {
596 // Add a bit to the InitializerValue so we don't have to worry about
597 // signed vs. unsigned comparisons.
598 InitializerValue =
599 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
600 // Convert the initializer to and from the target width and signed-ness.
601 llvm::APSInt ConvertedValue = InitializerValue;
602 ConvertedValue = ConvertedValue.trunc(ToWidth);
603 ConvertedValue.setIsSigned(ToSigned);
604 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
605 ConvertedValue.setIsSigned(InitializerValue.isSigned());
606 // If the result is different, this was a narrowing conversion.
607 if (ConvertedValue != InitializerValue)
608 Narrowing = true;
609 }
610 if (Narrowing) {
611 ConstantType = Initializer->getType();
612 ConstantValue = APValue(InitializerValue);
614 }
615
616 return NK_Not_Narrowing;
617 }
618 case ICK_Complex_Real:
619 if (FromType->isComplexType() && !ToType->isComplexType())
620 return NK_Type_Narrowing;
621 return NK_Not_Narrowing;
622
624 if (Ctx.getLangOpts().C23) {
625 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
627 if (Initializer->EvaluateAsRValue(R, Ctx)) {
628 ConstantValue = R.Val;
629 assert(ConstantValue.isFloat());
630 llvm::APFloat FloatVal = ConstantValue.getFloat();
631 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
632 // value, the unqualified versions of the type of the initializer and
633 // the corresponding real type of the object declared shall be
634 // compatible.
635 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
636 ConstantType = Initializer->getType();
638 }
639 }
640 }
641 return NK_Not_Narrowing;
642 default:
643 // Other kinds of conversions are not narrowings.
644 return NK_Not_Narrowing;
645 }
646}
647
648/// dump - Print this standard conversion sequence to standard
649/// error. Useful for debugging overloading issues.
650LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
651 raw_ostream &OS = llvm::errs();
652 bool PrintedSomething = false;
653 if (First != ICK_Identity) {
655 PrintedSomething = true;
656 }
657
658 if (Second != ICK_Identity) {
659 if (PrintedSomething) {
660 OS << " -> ";
661 }
663
664 if (CopyConstructor) {
665 OS << " (by copy constructor)";
666 } else if (DirectBinding) {
667 OS << " (direct reference binding)";
668 } else if (ReferenceBinding) {
669 OS << " (reference binding)";
670 }
671 PrintedSomething = true;
672 }
673
674 if (Third != ICK_Identity) {
675 if (PrintedSomething) {
676 OS << " -> ";
677 }
679 PrintedSomething = true;
680 }
681
682 if (!PrintedSomething) {
683 OS << "No conversions required";
684 }
685}
686
687/// dump - Print this user-defined conversion sequence to standard
688/// error. Useful for debugging overloading issues.
690 raw_ostream &OS = llvm::errs();
691 if (Before.First || Before.Second || Before.Third) {
692 Before.dump();
693 OS << " -> ";
694 }
696 OS << '\'' << *ConversionFunction << '\'';
697 else
698 OS << "aggregate initialization";
699 if (After.First || After.Second || After.Third) {
700 OS << " -> ";
701 After.dump();
702 }
703}
704
705/// dump - Print this implicit conversion sequence to standard
706/// error. Useful for debugging overloading issues.
708 raw_ostream &OS = llvm::errs();
710 OS << "Worst list element conversion: ";
711 switch (ConversionKind) {
713 OS << "Standard conversion: ";
714 Standard.dump();
715 break;
717 OS << "User-defined conversion: ";
718 UserDefined.dump();
719 break;
721 OS << "Ellipsis conversion";
722 break;
724 OS << "Ambiguous conversion";
725 break;
726 case BadConversion:
727 OS << "Bad conversion";
728 break;
729 }
730
731 OS << "\n";
732}
733
737
739 conversions().~ConversionSet();
740}
741
742void
748
749namespace {
750 // Structure used by DeductionFailureInfo to store
751 // template argument information.
752 struct DFIArguments {
753 TemplateArgument FirstArg;
754 TemplateArgument SecondArg;
755 };
756 // Structure used by DeductionFailureInfo to store
757 // template parameter and template argument information.
758 struct DFIParamWithArguments : DFIArguments {
759 TemplateParameter Param;
760 };
761 // Structure used by DeductionFailureInfo to store template argument
762 // information and the index of the problematic call argument.
763 struct DFIDeducedMismatchArgs : DFIArguments {
764 TemplateArgumentList *TemplateArgs;
765 unsigned CallArgIndex;
766 };
767 // Structure used by DeductionFailureInfo to store information about
768 // unsatisfied constraints.
769 struct CNSInfo {
770 TemplateArgumentList *TemplateArgs;
771 ConstraintSatisfaction Satisfaction;
772 };
773}
774
775/// Convert from Sema's representation of template deduction information
776/// to the form used in overload-candidate information.
780 TemplateDeductionInfo &Info) {
782 Result.Result = static_cast<unsigned>(TDK);
783 Result.HasDiagnostic = false;
784 switch (TDK) {
791 Result.Data = nullptr;
792 break;
793
795 Result.Data = Info.Param.getOpaqueValue();
796 break;
798 Result.Data = Info.Param.getOpaqueValue();
799 if (Info.hasSFINAEDiagnostic()) {
803 Result.HasDiagnostic = true;
804 }
805 break;
806
809 // FIXME: Should allocate from normal heap so that we can free this later.
810 auto *Saved = new (Context) DFIDeducedMismatchArgs;
811 Saved->FirstArg = Info.FirstArg;
812 Saved->SecondArg = Info.SecondArg;
813 Saved->TemplateArgs = Info.takeSugared();
814 Saved->CallArgIndex = Info.CallArgIndex;
815 Result.Data = Saved;
816 break;
817 }
818
820 // FIXME: Should allocate from normal heap so that we can free this later.
821 DFIArguments *Saved = new (Context) DFIArguments;
822 Saved->FirstArg = Info.FirstArg;
823 Saved->SecondArg = Info.SecondArg;
824 Result.Data = Saved;
825 break;
826 }
827
829 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
832 // FIXME: Should allocate from normal heap so that we can free this later.
833 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
834 Saved->Param = Info.Param;
835 Saved->FirstArg = Info.FirstArg;
836 Saved->SecondArg = Info.SecondArg;
837 Result.Data = Saved;
838 break;
839 }
840
842 Result.Data = Info.takeSugared();
843 if (Info.hasSFINAEDiagnostic()) {
847 Result.HasDiagnostic = true;
848 }
849 break;
850
852 CNSInfo *Saved = new (Context) CNSInfo;
853 Saved->TemplateArgs = Info.takeSugared();
854 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
855 Result.Data = Saved;
856 break;
857 }
858
862 llvm_unreachable("not a deduction failure");
863 }
864
865 return Result;
866}
867
869 switch (static_cast<TemplateDeductionResult>(Result)) {
878 break;
879
886 // FIXME: Destroy the data?
887 Data = nullptr;
888 break;
889
892 // FIXME: Destroy the template argument list?
893 Data = nullptr;
895 Diag->~PartialDiagnosticAt();
896 HasDiagnostic = false;
897 }
898 break;
899
901 // FIXME: Destroy the template argument list?
902 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
903 Data = nullptr;
905 Diag->~PartialDiagnosticAt();
906 HasDiagnostic = false;
907 }
908 break;
909
910 // Unhandled
913 break;
914 }
915}
916
918 if (HasDiagnostic)
919 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
920 return nullptr;
921}
922
956
992
1024
1056
1058 switch (static_cast<TemplateDeductionResult>(Result)) {
1061 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1062
1063 default:
1064 return std::nullopt;
1065 }
1066}
1067
1069 const FunctionDecl *Y) {
1070 if (!X || !Y)
1071 return false;
1072 if (X->getNumParams() != Y->getNumParams())
1073 return false;
1074 // FIXME: when do rewritten comparison operators
1075 // with explicit object parameters correspond?
1076 // https://cplusplus.github.io/CWG/issues/2797.html
1077 for (unsigned I = 0; I < X->getNumParams(); ++I)
1078 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1079 Y->getParamDecl(I)->getType()))
1080 return false;
1081 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1082 auto *FTY = Y->getDescribedFunctionTemplate();
1083 if (!FTY)
1084 return false;
1085 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1086 FTY->getTemplateParameters()))
1087 return false;
1088 }
1089 return true;
1090}
1091
1093 Expr *FirstOperand, FunctionDecl *EqFD) {
1094 assert(EqFD->getOverloadedOperator() ==
1095 OverloadedOperatorKind::OO_EqualEqual);
1096 // C++2a [over.match.oper]p4:
1097 // A non-template function or function template F named operator== is a
1098 // rewrite target with first operand o unless a search for the name operator!=
1099 // in the scope S from the instantiation context of the operator expression
1100 // finds a function or function template that would correspond
1101 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1102 // scope of the class type of o if F is a class member, and the namespace
1103 // scope of which F is a member otherwise. A function template specialization
1104 // named operator== is a rewrite target if its function template is a rewrite
1105 // target.
1107 OverloadedOperatorKind::OO_ExclaimEqual);
1108 if (isa<CXXMethodDecl>(EqFD)) {
1109 // If F is a class member, search scope is class type of first operand.
1110 QualType RHS = FirstOperand->getType();
1111 auto *RHSRec = RHS->getAsCXXRecordDecl();
1112 if (!RHSRec)
1113 return true;
1114 LookupResult Members(S, NotEqOp, OpLoc,
1116 S.LookupQualifiedName(Members, RHSRec);
1117 Members.suppressAccessDiagnostics();
1118 for (NamedDecl *Op : Members)
1119 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1120 return false;
1121 return true;
1122 }
1123 // Otherwise the search scope is the namespace scope of which F is a member.
1124 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1125 auto *NotEqFD = Op->getAsFunction();
1126 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1127 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1128 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1130 cast<Decl>(Op->getLexicalDeclContext())))
1131 return false;
1132 }
1133 return true;
1134}
1135
1137 OverloadedOperatorKind Op) const {
1139 return false;
1140 return Op == OO_EqualEqual || Op == OO_Spaceship;
1141}
1142
1144 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1145 auto Op = FD->getOverloadedOperator();
1146 if (!allowsReversed(Op))
1147 return false;
1148 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1149 assert(OriginalArgs.size() == 2);
1151 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1152 return false;
1153 }
1154 // Don't bother adding a reversed candidate that can never be a better
1155 // match than the non-reversed version.
1156 return FD->getNumNonObjectParams() != 2 ||
1158 FD->getParamDecl(1)->getType()) ||
1159 FD->hasAttr<EnableIfAttr>();
1160}
1161
1162void OverloadCandidateSet::destroyCandidates() {
1163 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1164 for (auto &C : i->Conversions)
1165 C.~ImplicitConversionSequence();
1166 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1167 i->DeductionFailure.Destroy();
1168 }
1169}
1170
1172 destroyCandidates();
1173 SlabAllocator.Reset();
1174 NumInlineBytesUsed = 0;
1175 Candidates.clear();
1176 Functions.clear();
1177 Kind = CSK;
1178 FirstDeferredCandidate = nullptr;
1179 DeferredCandidatesCount = 0;
1180 HasDeferredTemplateConstructors = false;
1181 ResolutionByPerfectCandidateIsDisabled = false;
1182}
1183
1184namespace {
1185 class UnbridgedCastsSet {
1186 struct Entry {
1187 Expr **Addr;
1188 Expr *Saved;
1189 };
1190 SmallVector<Entry, 2> Entries;
1191
1192 public:
1193 void save(Sema &S, Expr *&E) {
1194 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1195 Entry entry = { &E, E };
1196 Entries.push_back(entry);
1197 E = S.ObjC().stripARCUnbridgedCast(E);
1198 }
1199
1200 void restore() {
1201 for (SmallVectorImpl<Entry>::iterator
1202 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1203 *i->Addr = i->Saved;
1204 }
1205 };
1206}
1207
1208/// checkPlaceholderForOverload - Do any interesting placeholder-like
1209/// preprocessing on the given expression.
1210///
1211/// \param unbridgedCasts a collection to which to add unbridged casts;
1212/// without this, they will be immediately diagnosed as errors
1213///
1214/// Return true on unrecoverable error.
1215static bool
1217 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1218 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1219 // We can't handle overloaded expressions here because overload
1220 // resolution might reasonably tweak them.
1221 if (placeholder->getKind() == BuiltinType::Overload) return false;
1222
1223 // If the context potentially accepts unbridged ARC casts, strip
1224 // the unbridged cast and add it to the collection for later restoration.
1225 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1226 unbridgedCasts) {
1227 unbridgedCasts->save(S, E);
1228 return false;
1229 }
1230
1231 // Go ahead and check everything else.
1232 ExprResult result = S.CheckPlaceholderExpr(E);
1233 if (result.isInvalid())
1234 return true;
1235
1236 E = result.get();
1237 return false;
1238 }
1239
1240 // Nothing to do.
1241 return false;
1242}
1243
1244/// checkArgPlaceholdersForOverload - Check a set of call operands for
1245/// placeholders.
1247 UnbridgedCastsSet &unbridged) {
1248 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1249 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1250 return true;
1251
1252 return false;
1253}
1254
1256 const LookupResult &Old, NamedDecl *&Match,
1257 bool NewIsUsingDecl) {
1258 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1259 I != E; ++I) {
1260 NamedDecl *OldD = *I;
1261
1262 bool OldIsUsingDecl = false;
1263 if (isa<UsingShadowDecl>(OldD)) {
1264 OldIsUsingDecl = true;
1265
1266 // We can always introduce two using declarations into the same
1267 // context, even if they have identical signatures.
1268 if (NewIsUsingDecl) continue;
1269
1270 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1271 }
1272
1273 // A using-declaration does not conflict with another declaration
1274 // if one of them is hidden.
1275 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1276 continue;
1277
1278 // If either declaration was introduced by a using declaration,
1279 // we'll need to use slightly different rules for matching.
1280 // Essentially, these rules are the normal rules, except that
1281 // function templates hide function templates with different
1282 // return types or template parameter lists.
1283 bool UseMemberUsingDeclRules =
1284 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1285 !New->getFriendObjectKind();
1286
1287 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1288 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1289 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1291 continue;
1292 }
1293
1294 if (!isa<FunctionTemplateDecl>(OldD) &&
1295 !shouldLinkPossiblyHiddenDecl(*I, New))
1296 continue;
1297
1298 Match = *I;
1299 return OverloadKind::Match;
1300 }
1301
1302 // Builtins that have custom typechecking or have a reference should
1303 // not be overloadable or redeclarable.
1304 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1305 Match = *I;
1307 }
1308 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1309 // We can overload with these, which can show up when doing
1310 // redeclaration checks for UsingDecls.
1311 assert(Old.getLookupKind() == LookupUsingDeclName);
1312 } else if (isa<TagDecl>(OldD)) {
1313 // We can always overload with tags by hiding them.
1314 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1315 // Optimistically assume that an unresolved using decl will
1316 // overload; if it doesn't, we'll have to diagnose during
1317 // template instantiation.
1318 //
1319 // Exception: if the scope is dependent and this is not a class
1320 // member, the using declaration can only introduce an enumerator.
1321 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1322 Match = *I;
1324 }
1325 } else {
1326 // (C++ 13p1):
1327 // Only function declarations can be overloaded; object and type
1328 // declarations cannot be overloaded.
1329 Match = *I;
1331 }
1332 }
1333
1334 // C++ [temp.friend]p1:
1335 // For a friend function declaration that is not a template declaration:
1336 // -- if the name of the friend is a qualified or unqualified template-id,
1337 // [...], otherwise
1338 // -- if the name of the friend is a qualified-id and a matching
1339 // non-template function is found in the specified class or namespace,
1340 // the friend declaration refers to that function, otherwise,
1341 // -- if the name of the friend is a qualified-id and a matching function
1342 // template is found in the specified class or namespace, the friend
1343 // declaration refers to the deduced specialization of that function
1344 // template, otherwise
1345 // -- the name shall be an unqualified-id [...]
1346 // If we get here for a qualified friend declaration, we've just reached the
1347 // third bullet. If the type of the friend is dependent, skip this lookup
1348 // until instantiation.
1349 if (New->getFriendObjectKind() && New->getQualifier() &&
1350 !New->getDescribedFunctionTemplate() &&
1351 !New->getDependentSpecializationInfo() &&
1352 !New->getType()->isDependentType()) {
1353 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1354 TemplateSpecResult.addAllDecls(Old);
1355 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1356 /*QualifiedFriend*/true)) {
1357 New->setInvalidDecl();
1359 }
1360
1361 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1362 return OverloadKind::Match;
1363 }
1364
1366}
1367
1368template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1369 assert(D && "function decl should not be null");
1370 if (auto *A = D->getAttr<AttrT>())
1371 return !A->isImplicit();
1372 return false;
1373}
1374
1376 FunctionDecl *Old,
1377 bool UseMemberUsingDeclRules,
1378 bool ConsiderCudaAttrs,
1379 bool UseOverrideRules = false) {
1380 // C++ [basic.start.main]p2: This function shall not be overloaded.
1381 if (New->isMain())
1382 return false;
1383
1384 // MSVCRT user defined entry points cannot be overloaded.
1385 if (New->isMSVCRTEntryPoint())
1386 return false;
1387
1388 NamedDecl *OldDecl = Old;
1389 NamedDecl *NewDecl = New;
1391 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1392
1393 // C++ [temp.fct]p2:
1394 // A function template can be overloaded with other function templates
1395 // and with normal (non-template) functions.
1396 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1397 return true;
1398
1399 // Is the function New an overload of the function Old?
1400 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1401 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1402
1403 // Compare the signatures (C++ 1.3.10) of the two functions to
1404 // determine whether they are overloads. If we find any mismatch
1405 // in the signature, they are overloads.
1406
1407 // If either of these functions is a K&R-style function (no
1408 // prototype), then we consider them to have matching signatures.
1409 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1411 return false;
1412
1413 const auto *OldType = cast<FunctionProtoType>(OldQType);
1414 const auto *NewType = cast<FunctionProtoType>(NewQType);
1415
1416 // The signature of a function includes the types of its
1417 // parameters (C++ 1.3.10), which includes the presence or absence
1418 // of the ellipsis; see C++ DR 357).
1419 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1420 return true;
1421
1422 // For member-like friends, the enclosing class is part of the signature.
1423 if ((New->isMemberLikeConstrainedFriend() ||
1425 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1426 return true;
1427
1428 // Compare the parameter lists.
1429 // This can only be done once we have establish that friend functions
1430 // inhabit the same context, otherwise we might tried to instantiate
1431 // references to non-instantiated entities during constraint substitution.
1432 // GH78101.
1433 if (NewTemplate) {
1434 OldDecl = OldTemplate;
1435 NewDecl = NewTemplate;
1436 // C++ [temp.over.link]p4:
1437 // The signature of a function template consists of its function
1438 // signature, its return type and its template parameter list. The names
1439 // of the template parameters are significant only for establishing the
1440 // relationship between the template parameters and the rest of the
1441 // signature.
1442 //
1443 // We check the return type and template parameter lists for function
1444 // templates first; the remaining checks follow.
1445 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1446 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1447 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1448 bool SameReturnType = SemaRef.Context.hasSameType(
1449 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1450 // FIXME(GH58571): Match template parameter list even for non-constrained
1451 // template heads. This currently ensures that the code prior to C++20 is
1452 // not newly broken.
1453 bool ConstraintsInTemplateHead =
1456 // C++ [namespace.udecl]p11:
1457 // The set of declarations named by a using-declarator that inhabits a
1458 // class C does not include member functions and member function
1459 // templates of a base class that "correspond" to (and thus would
1460 // conflict with) a declaration of a function or function template in
1461 // C.
1462 // Comparing return types is not required for the "correspond" check to
1463 // decide whether a member introduced by a shadow declaration is hidden.
1464 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1465 !SameTemplateParameterList)
1466 return true;
1467 if (!UseMemberUsingDeclRules &&
1468 (!SameTemplateParameterList || !SameReturnType))
1469 return true;
1470 }
1471
1472 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1473 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1474
1475 int OldParamsOffset = 0;
1476 int NewParamsOffset = 0;
1477
1478 // When determining if a method is an overload from a base class, act as if
1479 // the implicit object parameter are of the same type.
1480
1481 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1483 auto ThisType = M->getFunctionObjectParameterReferenceType();
1484 if (ThisType.isConstQualified())
1485 Q.removeConst();
1486 return Q;
1487 }
1488
1489 // We do not allow overloading based off of '__restrict'.
1490 Q.removeRestrict();
1491
1492 // We may not have applied the implicit const for a constexpr member
1493 // function yet (because we haven't yet resolved whether this is a static
1494 // or non-static member function). Add it now, on the assumption that this
1495 // is a redeclaration of OldMethod.
1496 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1497 (M->isConstexpr() || M->isConsteval()) &&
1498 !isa<CXXConstructorDecl>(NewMethod))
1499 Q.addConst();
1500 return Q;
1501 };
1502
1503 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1504 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1505 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1506
1507 if (OldMethod->isExplicitObjectMemberFunction()) {
1508 BS.Quals.removeVolatile();
1509 DS.Quals.removeVolatile();
1510 }
1511
1512 return BS.Quals == DS.Quals;
1513 };
1514
1515 auto CompareType = [&](QualType Base, QualType D) {
1516 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1517 auto DS = D.getNonReferenceType().getCanonicalType().split();
1518
1519 if (!AreQualifiersEqual(BS, DS))
1520 return false;
1521
1522 if (OldMethod->isImplicitObjectMemberFunction() &&
1523 OldMethod->getParent() != NewMethod->getParent()) {
1524 CanQualType ParentType =
1525 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1526 if (ParentType.getTypePtr() != BS.Ty)
1527 return false;
1528 BS.Ty = DS.Ty;
1529 }
1530
1531 // FIXME: should we ignore some type attributes here?
1532 if (BS.Ty != DS.Ty)
1533 return false;
1534
1535 if (Base->isLValueReferenceType())
1536 return D->isLValueReferenceType();
1537 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1538 };
1539
1540 // If the function is a class member, its signature includes the
1541 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1542 auto DiagnoseInconsistentRefQualifiers = [&]() {
1543 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1544 return false;
1545 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1546 return false;
1547 if (OldMethod->isExplicitObjectMemberFunction() ||
1548 NewMethod->isExplicitObjectMemberFunction())
1549 return false;
1550 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1551 NewMethod->getRefQualifier() == RQ_None)) {
1552 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1553 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1554 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1555 return true;
1556 }
1557 return false;
1558 };
1559
1560 // We look at the parameters first, as it is the common case.
1561 // However we should not emit diagnostic before checking
1562 // the overloads do not differ by constraints or other discriminant.
1563 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1564 bool HaveInconsistentQualifiers = false;
1565
1566 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1567 OldParamsOffset++;
1568 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1569 NewParamsOffset++;
1570
1571 if (OldType->getNumParams() - OldParamsOffset !=
1572 NewType->getNumParams() - NewParamsOffset ||
1574 {OldType->param_type_begin() + OldParamsOffset,
1575 OldType->param_type_end()},
1576 {NewType->param_type_begin() + NewParamsOffset,
1577 NewType->param_type_end()},
1578 nullptr)) {
1579 return true;
1580 }
1581
1582 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1583 !NewMethod->isStatic()) {
1584 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1585 const CXXMethodDecl *New) {
1586 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1587 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1588
1589 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1590 return F->getRefQualifier() == RQ_None &&
1591 !F->isExplicitObjectMemberFunction();
1592 };
1593
1594 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1595 CompareType(OldObjectType.getNonReferenceType(),
1596 NewObjectType.getNonReferenceType()))
1597 return true;
1598 return CompareType(OldObjectType, NewObjectType);
1599 }(OldMethod, NewMethod);
1600
1601 if (!HaveCorrespondingObjectParameters) {
1602 ShouldDiagnoseInconsistentRefQualifiers = true;
1603 // CWG2554
1604 // and, if at least one is an explicit object member function, ignoring
1605 // object parameters
1606 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1607 !OldMethod->isExplicitObjectMemberFunction()))
1608 HaveInconsistentQualifiers = true;
1609 }
1610 }
1611
1612 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1613 NewMethod->isImplicitObjectMemberFunction())
1614 ShouldDiagnoseInconsistentRefQualifiers = true;
1615
1616 if (!UseOverrideRules &&
1617 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1618 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1619 OldRC = Old->getTrailingRequiresClause();
1620 if (!NewRC != !OldRC)
1621 return true;
1622 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1623 return true;
1624 if (NewRC &&
1625 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1626 NewDecl, NewRC.ConstraintExpr))
1627 return true;
1628 }
1629
1630 // Though pass_object_size is placed on parameters and takes an argument, we
1631 // consider it to be a function-level modifier for the sake of function
1632 // identity. Either the function has one or more parameters with
1633 // pass_object_size or it doesn't.
1636 return true;
1637
1638 // enable_if attributes are an order-sensitive part of the signature.
1640 NewI = New->specific_attr_begin<EnableIfAttr>(),
1641 NewE = New->specific_attr_end<EnableIfAttr>(),
1642 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1643 OldE = Old->specific_attr_end<EnableIfAttr>();
1644 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1645 if (NewI == NewE || OldI == OldE)
1646 return true;
1647 llvm::FoldingSetNodeID NewID, OldID;
1648 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1649 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1650 if (NewID != OldID)
1651 return true;
1652 }
1653
1654 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1655 DiagnoseInconsistentRefQualifiers()) ||
1656 HaveInconsistentQualifiers)
1657 return true;
1658
1659 // At this point, it is known that the two functions have the same signature.
1660 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1661 // Don't allow overloading of destructors. (In theory we could, but it
1662 // would be a giant change to clang.)
1664 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1665 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1666 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1667 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1668 "Unexpected invalid target.");
1669
1670 // Allow overloading of functions with same signature and different CUDA
1671 // target attributes.
1672 if (NewTarget != OldTarget) {
1673 // Special case: non-constexpr function is allowed to override
1674 // constexpr virtual function
1675 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1676 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1681 return false;
1682 }
1683 return true;
1684 }
1685 }
1686 }
1687 }
1688
1689 // The signatures match; this is not an overload.
1690 return false;
1691}
1692
1694 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1695 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1696 ConsiderCudaAttrs);
1697}
1698
1700 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1701 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1702 /*UseMemberUsingDeclRules=*/false,
1703 /*ConsiderCudaAttrs=*/true,
1704 /*UseOverrideRules=*/true);
1705}
1706
1707/// Tries a user-defined conversion from From to ToType.
1708///
1709/// Produces an implicit conversion sequence for when a standard conversion
1710/// is not an option. See TryImplicitConversion for more information.
1713 bool SuppressUserConversions,
1714 AllowedExplicit AllowExplicit,
1715 bool InOverloadResolution,
1716 bool CStyle,
1717 bool AllowObjCWritebackConversion,
1718 bool AllowObjCConversionOnExplicit) {
1720
1721 if (SuppressUserConversions) {
1722 // We're not in the case above, so there is no conversion that
1723 // we can perform.
1725 return ICS;
1726 }
1727
1728 // Attempt user-defined conversion.
1729 OverloadCandidateSet Conversions(From->getExprLoc(),
1731 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1732 Conversions, AllowExplicit,
1733 AllowObjCConversionOnExplicit)) {
1734 case OR_Success:
1735 case OR_Deleted:
1736 ICS.setUserDefined();
1737 // C++ [over.ics.user]p4:
1738 // A conversion of an expression of class type to the same class
1739 // type is given Exact Match rank, and a conversion of an
1740 // expression of class type to a base class of that type is
1741 // given Conversion rank, in spite of the fact that a copy
1742 // constructor (i.e., a user-defined conversion function) is
1743 // called for those cases.
1745 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1746 QualType FromType;
1747 SourceLocation FromLoc;
1748 // C++11 [over.ics.list]p6, per DR2137:
1749 // C++17 [over.ics.list]p6:
1750 // If C is not an initializer-list constructor and the initializer list
1751 // has a single element of type cv U, where U is X or a class derived
1752 // from X, the implicit conversion sequence has Exact Match rank if U is
1753 // X, or Conversion rank if U is derived from X.
1754 bool FromListInit = false;
1755 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1756 InitList && InitList->getNumInits() == 1 &&
1758 const Expr *SingleInit = InitList->getInit(0);
1759 FromType = SingleInit->getType();
1760 FromLoc = SingleInit->getBeginLoc();
1761 FromListInit = true;
1762 } else {
1763 FromType = From->getType();
1764 FromLoc = From->getBeginLoc();
1765 }
1766 QualType FromCanon =
1768 QualType ToCanon
1770 if ((FromCanon == ToCanon ||
1771 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1772 // Turn this into a "standard" conversion sequence, so that it
1773 // gets ranked with standard conversion sequences.
1775 ICS.setStandard();
1777 ICS.Standard.setFromType(FromType);
1778 ICS.Standard.setAllToTypes(ToType);
1779 ICS.Standard.FromBracedInitList = FromListInit;
1782 if (ToCanon != FromCanon)
1784 }
1785 }
1786 break;
1787
1788 case OR_Ambiguous:
1789 ICS.setAmbiguous();
1790 ICS.Ambiguous.setFromType(From->getType());
1791 ICS.Ambiguous.setToType(ToType);
1792 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1793 Cand != Conversions.end(); ++Cand)
1794 if (Cand->Best)
1795 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1796 break;
1797
1798 // Fall through.
1801 break;
1802 }
1803
1804 return ICS;
1805}
1806
1807/// TryImplicitConversion - Attempt to perform an implicit conversion
1808/// from the given expression (Expr) to the given type (ToType). This
1809/// function returns an implicit conversion sequence that can be used
1810/// to perform the initialization. Given
1811///
1812/// void f(float f);
1813/// void g(int i) { f(i); }
1814///
1815/// this routine would produce an implicit conversion sequence to
1816/// describe the initialization of f from i, which will be a standard
1817/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1818/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1819//
1820/// Note that this routine only determines how the conversion can be
1821/// performed; it does not actually perform the conversion. As such,
1822/// it will not produce any diagnostics if no conversion is available,
1823/// but will instead return an implicit conversion sequence of kind
1824/// "BadConversion".
1825///
1826/// If @p SuppressUserConversions, then user-defined conversions are
1827/// not permitted.
1828/// If @p AllowExplicit, then explicit user-defined conversions are
1829/// permitted.
1830///
1831/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1832/// writeback conversion, which allows __autoreleasing id* parameters to
1833/// be initialized with __strong id* or __weak id* arguments.
1834static ImplicitConversionSequence
1836 bool SuppressUserConversions,
1837 AllowedExplicit AllowExplicit,
1838 bool InOverloadResolution,
1839 bool CStyle,
1840 bool AllowObjCWritebackConversion,
1841 bool AllowObjCConversionOnExplicit) {
1843 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1844 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1845 ICS.setStandard();
1846 return ICS;
1847 }
1848
1849 if (!S.getLangOpts().CPlusPlus) {
1851 return ICS;
1852 }
1853
1854 // C++ [over.ics.user]p4:
1855 // A conversion of an expression of class type to the same class
1856 // type is given Exact Match rank, and a conversion of an
1857 // expression of class type to a base class of that type is
1858 // given Conversion rank, in spite of the fact that a copy/move
1859 // constructor (i.e., a user-defined conversion function) is
1860 // called for those cases.
1861 QualType FromType = From->getType();
1862 if (ToType->isRecordType() &&
1863 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1864 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1865 ICS.setStandard();
1867 ICS.Standard.setFromType(FromType);
1868 ICS.Standard.setAllToTypes(ToType);
1869
1870 // We don't actually check at this point whether there is a valid
1871 // copy/move constructor, since overloading just assumes that it
1872 // exists. When we actually perform initialization, we'll find the
1873 // appropriate constructor to copy the returned object, if needed.
1874 ICS.Standard.CopyConstructor = nullptr;
1875
1876 // In HLSL, a conversion of an expression of class type to the same class
1877 // type needs implicit LvaluetoRvalue conversion.
1878 if (S.getLangOpts().HLSL)
1880
1881 // Determine whether this is considered a derived-to-base conversion.
1882 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1884
1885 return ICS;
1886 }
1887
1888 if (S.getLangOpts().HLSL) {
1889 // Handle conversion of the HLSL resource types.
1890 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1891 if (FromTy->isHLSLAttributedResourceType()) {
1892 // Attributed resource types can convert to other attributed
1893 // resource types with the same attributes and contained types,
1894 // or to __hlsl_resource_t without any attributes.
1895 bool CanConvert = false;
1896 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1897 if (ToTy->isHLSLAttributedResourceType()) {
1898 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1899 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1900 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1901 FromResType->getWrappedType()) &&
1902 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1903 FromResType->getContainedType()) &&
1904 ToResType->getAttrs() == FromResType->getAttrs())
1905 CanConvert = true;
1906 } else if (ToTy->isHLSLResourceType()) {
1907 CanConvert = true;
1908 }
1909 if (CanConvert) {
1910 ICS.setStandard();
1912 ICS.Standard.setFromType(FromType);
1913 ICS.Standard.setAllToTypes(ToType);
1914 return ICS;
1915 }
1916 }
1917 }
1918
1919 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1920 AllowExplicit, InOverloadResolution, CStyle,
1921 AllowObjCWritebackConversion,
1922 AllowObjCConversionOnExplicit);
1923}
1924
1925ImplicitConversionSequence
1927 bool SuppressUserConversions,
1928 AllowedExplicit AllowExplicit,
1929 bool InOverloadResolution,
1930 bool CStyle,
1931 bool AllowObjCWritebackConversion) {
1932 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1933 AllowExplicit, InOverloadResolution, CStyle,
1934 AllowObjCWritebackConversion,
1935 /*AllowObjCConversionOnExplicit=*/false);
1936}
1937
1939 AssignmentAction Action,
1940 bool AllowExplicit) {
1941 if (checkPlaceholderForOverload(*this, From))
1942 return ExprError();
1943
1944 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1945 bool AllowObjCWritebackConversion =
1946 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1947 Action == AssignmentAction::Sending);
1948 if (getLangOpts().ObjC)
1949 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1950 From->getType(), From);
1952 *this, From, ToType,
1953 /*SuppressUserConversions=*/false,
1954 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1955 /*InOverloadResolution=*/false,
1956 /*CStyle=*/false, AllowObjCWritebackConversion,
1957 /*AllowObjCConversionOnExplicit=*/false);
1958 return PerformImplicitConversion(From, ToType, ICS, Action);
1959}
1960
1962 QualType &ResultTy) const {
1963 bool Changed = IsFunctionConversion(FromType, ToType);
1964 if (Changed)
1965 ResultTy = ToType;
1966 return Changed;
1967}
1968
1969bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1970 if (Context.hasSameUnqualifiedType(FromType, ToType))
1971 return false;
1972
1973 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1974 // or F(t noexcept) -> F(t)
1975 // where F adds one of the following at most once:
1976 // - a pointer
1977 // - a member pointer
1978 // - a block pointer
1979 // Changes here need matching changes in FindCompositePointerType.
1980 CanQualType CanTo = Context.getCanonicalType(ToType);
1981 CanQualType CanFrom = Context.getCanonicalType(FromType);
1982 Type::TypeClass TyClass = CanTo->getTypeClass();
1983 if (TyClass != CanFrom->getTypeClass()) return false;
1984 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1985 if (TyClass == Type::Pointer) {
1986 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1987 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1988 } else if (TyClass == Type::BlockPointer) {
1989 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1990 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1991 } else if (TyClass == Type::MemberPointer) {
1992 auto ToMPT = CanTo.castAs<MemberPointerType>();
1993 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1994 // A function pointer conversion cannot change the class of the function.
1995 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1996 FromMPT->getMostRecentCXXRecordDecl()))
1997 return false;
1998 CanTo = ToMPT->getPointeeType();
1999 CanFrom = FromMPT->getPointeeType();
2000 } else {
2001 return false;
2002 }
2003
2004 TyClass = CanTo->getTypeClass();
2005 if (TyClass != CanFrom->getTypeClass()) return false;
2006 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
2007 return false;
2008 }
2009
2010 const auto *FromFn = cast<FunctionType>(CanFrom);
2011 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
2012
2013 const auto *ToFn = cast<FunctionType>(CanTo);
2014 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
2015
2016 bool Changed = false;
2017
2018 // Drop 'noreturn' if not present in target type.
2019 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
2020 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
2021 Changed = true;
2022 }
2023
2024 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
2025 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
2026
2027 if (FromFPT && ToFPT) {
2028 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2029 QualType NewTy = Context.getFunctionType(
2030 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2031 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2032 ToFPT->hasCFIUncheckedCallee()));
2033 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2034 FromFn = FromFPT;
2035 Changed = true;
2036 }
2037 }
2038
2039 // Drop 'noexcept' if not present in target type.
2040 if (FromFPT && ToFPT) {
2041 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2042 FromFn = cast<FunctionType>(
2043 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2044 EST_None)
2045 .getTypePtr());
2046 Changed = true;
2047 }
2048
2049 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2050 // only if the ExtParameterInfo lists of the two function prototypes can be
2051 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2053 bool CanUseToFPT, CanUseFromFPT;
2054 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2055 CanUseFromFPT, NewParamInfos) &&
2056 CanUseToFPT && !CanUseFromFPT) {
2057 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2058 ExtInfo.ExtParameterInfos =
2059 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2060 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2061 FromFPT->getParamTypes(), ExtInfo);
2062 FromFn = QT->getAs<FunctionType>();
2063 Changed = true;
2064 }
2065
2066 if (Context.hasAnyFunctionEffects()) {
2067 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2068
2069 // Transparently add/drop effects; here we are concerned with
2070 // language rules/canonicalization. Adding/dropping effects is a warning.
2071 const auto FromFX = FromFPT->getFunctionEffects();
2072 const auto ToFX = ToFPT->getFunctionEffects();
2073 if (FromFX != ToFX) {
2074 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2075 ExtInfo.FunctionEffects = ToFX;
2076 QualType QT = Context.getFunctionType(
2077 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2078 FromFn = QT->getAs<FunctionType>();
2079 Changed = true;
2080 }
2081 }
2082 }
2083
2084 if (!Changed)
2085 return false;
2086
2087 assert(QualType(FromFn, 0).isCanonical());
2088 if (QualType(FromFn, 0) != CanTo) return false;
2089
2090 return true;
2091}
2092
2093/// Determine whether the conversion from FromType to ToType is a valid
2094/// floating point conversion.
2095///
2096static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2097 QualType ToType) {
2098 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2099 return false;
2100 // FIXME: disable conversions between long double, __ibm128 and __float128
2101 // if their representation is different until there is back end support
2102 // We of course allow this conversion if long double is really double.
2103
2104 // Conversions between bfloat16 and float16 are currently not supported.
2105 if ((FromType->isBFloat16Type() &&
2106 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2107 (ToType->isBFloat16Type() &&
2108 (FromType->isFloat16Type() || FromType->isHalfType())))
2109 return false;
2110
2111 // Conversions between IEEE-quad and IBM-extended semantics are not
2112 // permitted.
2113 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2114 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2115 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2116 &ToSem == &llvm::APFloat::IEEEquad()) ||
2117 (&FromSem == &llvm::APFloat::IEEEquad() &&
2118 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2119 return false;
2120 return true;
2121}
2122
2124 QualType ToType,
2126 Expr *From) {
2127 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2128 return true;
2129
2130 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2132 return true;
2133 }
2134
2135 if (IsFloatingPointConversion(S, FromType, ToType)) {
2137 return true;
2138 }
2139
2140 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2142 return true;
2143 }
2144
2145 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2147 ToType->isRealFloatingType())) {
2149 return true;
2150 }
2151
2152 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2154 return true;
2155 }
2156
2157 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2158 ToType->isIntegralType(S.Context)) {
2160 return true;
2161 }
2162
2163 return false;
2164}
2165
2166/// Determine whether the conversion from FromType to ToType is a valid
2167/// matrix conversion.
2168///
2169/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2170/// conversion.
2171static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2173 ImplicitConversionKind &ElConv, Expr *From,
2174 bool InOverloadResolution, bool CStyle) {
2175 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2176 if (!S.getLangOpts().HLSL)
2177 return false;
2178
2179 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2180 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2181
2182 // If both arguments are matrix, handle possible matrix truncation and
2183 // element conversion.
2184 if (ToMatrixType && FromMatrixType) {
2185 unsigned FromCols = FromMatrixType->getNumColumns();
2186 unsigned ToCols = ToMatrixType->getNumColumns();
2187 if (FromCols < ToCols)
2188 return false;
2189
2190 unsigned FromRows = FromMatrixType->getNumRows();
2191 unsigned ToRows = ToMatrixType->getNumRows();
2192 if (FromRows < ToRows)
2193 return false;
2194
2195 if (FromRows == ToRows && FromCols == ToCols)
2196 ElConv = ICK_Identity;
2197 else
2199
2200 QualType FromElTy = FromMatrixType->getElementType();
2201 QualType ToElTy = ToMatrixType->getElementType();
2202 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2203 return true;
2204 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2205 }
2206
2207 // Matrix splat from any arithmetic type to a matrix.
2208 if (ToMatrixType && FromType->isArithmeticType()) {
2209 ElConv = ICK_HLSL_Matrix_Splat;
2210 QualType ToElTy = ToMatrixType->getElementType();
2211 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2212 }
2213 if (FromMatrixType && !ToMatrixType) {
2215 QualType FromElTy = FromMatrixType->getElementType();
2216 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2217 return true;
2218 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2219 }
2220
2221 return false;
2222}
2223
2224/// Determine whether the conversion from FromType to ToType is a valid
2225/// vector conversion.
2226///
2227/// \param ICK Will be set to the vector conversion kind, if this is a vector
2228/// conversion.
2229static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2231 ImplicitConversionKind &ElConv, Expr *From,
2232 bool InOverloadResolution, bool CStyle) {
2233 // We need at least one of these types to be a vector type to have a vector
2234 // conversion.
2235 if (!ToType->isVectorType() && !FromType->isVectorType())
2236 return false;
2237
2238 // Identical types require no conversions.
2239 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2240 return false;
2241
2242 // HLSL allows implicit truncation of vector types.
2243 if (S.getLangOpts().HLSL) {
2244 auto *ToExtType = ToType->getAs<ExtVectorType>();
2245 auto *FromExtType = FromType->getAs<ExtVectorType>();
2246
2247 // If both arguments are vectors, handle possible vector truncation and
2248 // element conversion.
2249 if (ToExtType && FromExtType) {
2250 unsigned FromElts = FromExtType->getNumElements();
2251 unsigned ToElts = ToExtType->getNumElements();
2252 if (FromElts < ToElts)
2253 return false;
2254 if (FromElts == ToElts)
2255 ElConv = ICK_Identity;
2256 else
2258
2259 QualType FromElTy = FromExtType->getElementType();
2260 QualType ToElTy = ToExtType->getElementType();
2261 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2262 return true;
2263 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2264 }
2265 if (FromExtType && !ToExtType) {
2267 QualType FromElTy = FromExtType->getElementType();
2268 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2269 return true;
2270 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2271 }
2272 // Fallthrough for the case where ToType is a vector and FromType is not.
2273 }
2274
2275 // There are no conversions between extended vector types, only identity.
2276 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2277 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2278 // Implicit conversions require the same number of elements.
2279 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2280 return false;
2281
2282 // Permit implicit conversions from integral values to boolean vectors.
2283 if (ToType->isExtVectorBoolType() &&
2284 FromExtType->getElementType()->isIntegerType()) {
2286 return true;
2287 }
2288 // There are no other conversions between extended vector types.
2289 return false;
2290 }
2291
2292 // Vector splat from any arithmetic type to a vector.
2293 if (FromType->isArithmeticType()) {
2294 if (S.getLangOpts().HLSL) {
2295 ElConv = ICK_HLSL_Vector_Splat;
2296 QualType ToElTy = ToExtType->getElementType();
2297 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2298 From);
2299 }
2300 ICK = ICK_Vector_Splat;
2301 return true;
2302 }
2303 }
2304
2305 if (ToType->isSVESizelessBuiltinType() ||
2306 FromType->isSVESizelessBuiltinType())
2307 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2308 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2310 return true;
2311 }
2312
2313 if (ToType->isRVVSizelessBuiltinType() ||
2314 FromType->isRVVSizelessBuiltinType())
2315 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2316 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2318 return true;
2319 }
2320
2321 // We can perform the conversion between vector types in the following cases:
2322 // 1)vector types are equivalent AltiVec and GCC vector types
2323 // 2)lax vector conversions are permitted and the vector types are of the
2324 // same size
2325 // 3)the destination type does not have the ARM MVE strict-polymorphism
2326 // attribute, which inhibits lax vector conversion for overload resolution
2327 // only
2328 if (ToType->isVectorType() && FromType->isVectorType()) {
2329 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2330 (S.isLaxVectorConversion(FromType, ToType) &&
2331 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2332 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2333 S.isLaxVectorConversion(FromType, ToType) &&
2334 S.anyAltivecTypes(FromType, ToType) &&
2335 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2336 !InOverloadResolution && !CStyle) {
2337 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2338 << FromType << ToType;
2339 }
2341 return true;
2342 }
2343 }
2344
2345 return false;
2346}
2347
2348static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2349 bool InOverloadResolution,
2350 StandardConversionSequence &SCS,
2351 bool CStyle);
2352
2353static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2354 QualType ToType,
2355 bool InOverloadResolution,
2356 StandardConversionSequence &SCS,
2357 bool CStyle);
2358
2359/// IsStandardConversion - Determines whether there is a standard
2360/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2361/// expression From to the type ToType. Standard conversion sequences
2362/// only consider non-class types; for conversions that involve class
2363/// types, use TryImplicitConversion. If a conversion exists, SCS will
2364/// contain the standard conversion sequence required to perform this
2365/// conversion and this routine will return true. Otherwise, this
2366/// routine will return false and the value of SCS is unspecified.
2367static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2368 bool InOverloadResolution,
2370 bool CStyle,
2371 bool AllowObjCWritebackConversion) {
2372 QualType FromType = From->getType();
2373
2374 // Standard conversions (C++ [conv])
2376 SCS.IncompatibleObjC = false;
2377 SCS.setFromType(FromType);
2378 SCS.CopyConstructor = nullptr;
2379
2380 // There are no standard conversions for class types in C++, so
2381 // abort early. When overloading in C, however, we do permit them.
2382 if (S.getLangOpts().CPlusPlus &&
2383 (FromType->isRecordType() || ToType->isRecordType()))
2384 return false;
2385
2386 // The first conversion can be an lvalue-to-rvalue conversion,
2387 // array-to-pointer conversion, or function-to-pointer conversion
2388 // (C++ 4p1).
2389
2390 if (FromType == S.Context.OverloadTy) {
2391 DeclAccessPair AccessPair;
2392 if (FunctionDecl *Fn
2393 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2394 AccessPair)) {
2395 // We were able to resolve the address of the overloaded function,
2396 // so we can convert to the type of that function.
2397 FromType = Fn->getType();
2398 SCS.setFromType(FromType);
2399
2400 // we can sometimes resolve &foo<int> regardless of ToType, so check
2401 // if the type matches (identity) or we are converting to bool
2403 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2404 // if the function type matches except for [[noreturn]], it's ok
2405 if (!S.IsFunctionConversion(FromType,
2407 // otherwise, only a boolean conversion is standard
2408 if (!ToType->isBooleanType())
2409 return false;
2410 }
2411
2412 // Check if the "from" expression is taking the address of an overloaded
2413 // function and recompute the FromType accordingly. Take advantage of the
2414 // fact that non-static member functions *must* have such an address-of
2415 // expression.
2416 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2417 if (Method && !Method->isStatic() &&
2418 !Method->isExplicitObjectMemberFunction()) {
2419 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2420 "Non-unary operator on non-static member address");
2421 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2422 == UO_AddrOf &&
2423 "Non-address-of operator on non-static member address");
2424 FromType = S.Context.getMemberPointerType(
2425 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2426 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2427 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2428 UO_AddrOf &&
2429 "Non-address-of operator for overloaded function expression");
2430 FromType = S.Context.getPointerType(FromType);
2431 }
2432 } else {
2433 return false;
2434 }
2435 }
2436
2437 bool argIsLValue = From->isGLValue();
2438 // To handle conversion from ArrayParameterType to ConstantArrayType
2439 // this block must be above the one below because Array parameters
2440 // do not decay and when handling HLSLOutArgExprs and
2441 // the From expression is an LValue.
2442 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2443 ToType->isConstantArrayType()) {
2444 // HLSL constant array parameters do not decay, so if the argument is a
2445 // constant array and the parameter is an ArrayParameterType we have special
2446 // handling here.
2447 if (ToType->isArrayParameterType()) {
2448 FromType = S.Context.getArrayParameterType(FromType);
2449 } else if (FromType->isArrayParameterType()) {
2450 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2451 FromType = APT->getConstantArrayType(S.Context);
2452 }
2453
2455
2456 // Don't consider qualifiers, which include things like address spaces
2457 if (FromType.getCanonicalType().getUnqualifiedType() !=
2459 return false;
2460
2461 SCS.setAllToTypes(ToType);
2462 return true;
2463 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2464 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2465 // Lvalue-to-rvalue conversion (C++11 4.1):
2466 // A glvalue (3.10) of a non-function, non-array type T can
2467 // be converted to a prvalue.
2468
2470
2471 // C11 6.3.2.1p2:
2472 // ... if the lvalue has atomic type, the value has the non-atomic version
2473 // of the type of the lvalue ...
2474 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2475 FromType = Atomic->getValueType();
2476
2477 // If T is a non-class type, the type of the rvalue is the
2478 // cv-unqualified version of T. Otherwise, the type of the rvalue
2479 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2480 // just strip the qualifiers because they don't matter.
2481 FromType = FromType.getUnqualifiedType();
2482 } else if (FromType->isArrayType()) {
2483 // Array-to-pointer conversion (C++ 4.2)
2485
2486 // An lvalue or rvalue of type "array of N T" or "array of unknown
2487 // bound of T" can be converted to an rvalue of type "pointer to
2488 // T" (C++ 4.2p1).
2489 FromType = S.Context.getArrayDecayedType(FromType);
2490
2491 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2492 // This conversion is deprecated in C++03 (D.4)
2494
2495 // For the purpose of ranking in overload resolution
2496 // (13.3.3.1.1), this conversion is considered an
2497 // array-to-pointer conversion followed by a qualification
2498 // conversion (4.4). (C++ 4.2p2)
2499 SCS.Second = ICK_Identity;
2502 SCS.setAllToTypes(FromType);
2503 return true;
2504 }
2505 } else if (FromType->isFunctionType() && argIsLValue) {
2506 // Function-to-pointer conversion (C++ 4.3).
2508
2509 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2512 return false;
2513
2514 // An lvalue of function type T can be converted to an rvalue of
2515 // type "pointer to T." The result is a pointer to the
2516 // function. (C++ 4.3p1).
2517 FromType = S.Context.getPointerType(FromType);
2518 } else {
2519 // We don't require any conversions for the first step.
2520 SCS.First = ICK_Identity;
2521 }
2522 SCS.setToType(0, FromType);
2523
2524 // The second conversion can be an integral promotion, floating
2525 // point promotion, integral conversion, floating point conversion,
2526 // floating-integral conversion, pointer conversion,
2527 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2528 // For overloading in C, this can also be a "compatible-type"
2529 // conversion.
2530 bool IncompatibleObjC = false;
2532 ImplicitConversionKind DimensionICK = ICK_Identity;
2533 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2534 // The unqualified versions of the types are the same: there's no
2535 // conversion to do.
2536 SCS.Second = ICK_Identity;
2537 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2538 // Integral promotion (C++ 4.5).
2540 FromType = ToType.getUnqualifiedType();
2541 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2542 // Floating point promotion (C++ 4.6).
2544 FromType = ToType.getUnqualifiedType();
2545 } else if (S.IsComplexPromotion(FromType, ToType)) {
2546 // Complex promotion (Clang extension)
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2550 // OverflowBehaviorType promotions
2552 FromType = ToType.getUnqualifiedType();
2553 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2554 // OverflowBehaviorType conversions
2556 FromType = ToType.getUnqualifiedType();
2557 } else if (ToType->isBooleanType() &&
2558 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2559 FromType->isBlockPointerType() ||
2560 FromType->isMemberPointerType())) {
2561 // Boolean conversions (C++ 4.12).
2563 FromType = S.Context.BoolTy;
2564 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2565 ToType->isIntegralType(S.Context)) {
2566 // Integral conversions (C++ 4.7).
2568 FromType = ToType.getUnqualifiedType();
2569 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2570 // Complex conversions (C99 6.3.1.6)
2572 FromType = ToType.getUnqualifiedType();
2573 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2574 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2575 // Complex-real conversions (C99 6.3.1.7)
2577 FromType = ToType.getUnqualifiedType();
2578 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2579 // Floating point conversions (C++ 4.8).
2581 FromType = ToType.getUnqualifiedType();
2582 } else if ((FromType->isRealFloatingType() &&
2583 ToType->isIntegralType(S.Context)) ||
2585 ToType->isRealFloatingType())) {
2586
2587 // Floating-integral conversions (C++ 4.9).
2589 FromType = ToType.getUnqualifiedType();
2590 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2592 } else if (AllowObjCWritebackConversion &&
2593 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2595 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2596 FromType, IncompatibleObjC)) {
2597 // Pointer conversions (C++ 4.10).
2599 SCS.IncompatibleObjC = IncompatibleObjC;
2600 FromType = FromType.getUnqualifiedType();
2601 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2602 InOverloadResolution, FromType)) {
2603 // Pointer to member conversions (4.11).
2605 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2606 From, InOverloadResolution, CStyle)) {
2607 SCS.Second = SecondICK;
2608 SCS.Dimension = DimensionICK;
2609 FromType = ToType.getUnqualifiedType();
2610 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2611 From, InOverloadResolution, CStyle)) {
2612 SCS.Second = SecondICK;
2613 SCS.Dimension = DimensionICK;
2614 FromType = ToType.getUnqualifiedType();
2615 } else if (!S.getLangOpts().CPlusPlus &&
2616 S.Context.typesAreCompatible(ToType, FromType)) {
2617 // Compatible conversions (Clang extension for C function overloading)
2619 FromType = ToType.getUnqualifiedType();
2621 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2623 FromType = ToType;
2624 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2625 CStyle)) {
2626 // tryAtomicConversion has updated the standard conversion sequence
2627 // appropriately.
2628 return true;
2630 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2631 return true;
2632 } else if (ToType->isEventT() &&
2634 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2636 FromType = ToType;
2637 } else if (ToType->isQueueT() &&
2639 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2641 FromType = ToType;
2642 } else if (ToType->isSamplerT() &&
2645 FromType = ToType;
2646 } else if ((ToType->isFixedPointType() &&
2647 FromType->isConvertibleToFixedPointType()) ||
2648 (FromType->isFixedPointType() &&
2649 ToType->isConvertibleToFixedPointType())) {
2651 FromType = ToType;
2652 } else {
2653 // No second conversion required.
2654 SCS.Second = ICK_Identity;
2655 }
2656 SCS.setToType(1, FromType);
2657
2658 // The third conversion can be a function pointer conversion or a
2659 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2660 bool ObjCLifetimeConversion;
2661 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2662 // Function pointer conversions (removing 'noexcept') including removal of
2663 // 'noreturn' (Clang extension).
2665 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2666 ObjCLifetimeConversion)) {
2668 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2669 FromType = ToType;
2670 } else {
2671 // No conversion required
2672 SCS.Third = ICK_Identity;
2673 }
2674
2675 // C++ [over.best.ics]p6:
2676 // [...] Any difference in top-level cv-qualification is
2677 // subsumed by the initialization itself and does not constitute
2678 // a conversion. [...]
2679 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2680 QualType CanonTo = S.Context.getCanonicalType(ToType);
2681 if (CanonFrom.getLocalUnqualifiedType()
2682 == CanonTo.getLocalUnqualifiedType() &&
2683 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2684 FromType = ToType;
2685 CanonFrom = CanonTo;
2686 }
2687
2688 SCS.setToType(2, FromType);
2689
2690 if (CanonFrom == CanonTo)
2691 return true;
2692
2693 // If we have not converted the argument type to the parameter type,
2694 // this is a bad conversion sequence, unless we're resolving an overload in C.
2695 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2696 return false;
2697
2698 ExprResult ER = ExprResult{From};
2699 AssignConvertType Conv =
2701 /*Diagnose=*/false,
2702 /*DiagnoseCFAudited=*/false,
2703 /*ConvertRHS=*/false);
2704 ImplicitConversionKind SecondConv;
2705 switch (Conv) {
2707 case AssignConvertType::
2708 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2709 SecondConv = ICK_C_Only_Conversion;
2710 break;
2711 // For our purposes, discarding qualifiers is just as bad as using an
2712 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2713 // qualifiers, as well.
2718 break;
2719 default:
2720 return false;
2721 }
2722
2723 // First can only be an lvalue conversion, so we pretend that this was the
2724 // second conversion. First should already be valid from earlier in the
2725 // function.
2726 SCS.Second = SecondConv;
2727 SCS.setToType(1, ToType);
2728
2729 // Third is Identity, because Second should rank us worse than any other
2730 // conversion. This could also be ICK_Qualification, but it's simpler to just
2731 // lump everything in with the second conversion, and we don't gain anything
2732 // from making this ICK_Qualification.
2733 SCS.Third = ICK_Identity;
2734 SCS.setToType(2, ToType);
2735 return true;
2736}
2737
2738static bool
2740 QualType &ToType,
2741 bool InOverloadResolution,
2743 bool CStyle) {
2744
2745 const RecordType *UT = ToType->getAsUnionType();
2746 if (!UT)
2747 return false;
2748 // The field to initialize within the transparent union.
2749 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2750 if (!UD->hasAttr<TransparentUnionAttr>())
2751 return false;
2752 // It's compatible if the expression matches any of the fields.
2753 for (const auto *it : UD->fields()) {
2754 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2755 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2756 ToType = it->getType();
2757 return true;
2758 }
2759 }
2760 return false;
2761}
2762
2763bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2764 const BuiltinType *To = ToType->getAs<BuiltinType>();
2765 // All integers are built-in.
2766 if (!To) {
2767 return false;
2768 }
2769
2770 // An rvalue of type char, signed char, unsigned char, short int, or
2771 // unsigned short int can be converted to an rvalue of type int if
2772 // int can represent all the values of the source type; otherwise,
2773 // the source rvalue can be converted to an rvalue of type unsigned
2774 // int (C++ 4.5p1).
2775 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2776 !FromType->isEnumeralType()) {
2777 if ( // We can promote any signed, promotable integer type to an int
2778 (FromType->isSignedIntegerType() ||
2779 // We can promote any unsigned integer type whose size is
2780 // less than int to an int.
2781 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2782 return To->getKind() == BuiltinType::Int;
2783 }
2784
2785 return To->getKind() == BuiltinType::UInt;
2786 }
2787
2788 // C++11 [conv.prom]p3:
2789 // A prvalue of an unscoped enumeration type whose underlying type is not
2790 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2791 // following types that can represent all the values of the enumeration
2792 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2793 // unsigned int, long int, unsigned long int, long long int, or unsigned
2794 // long long int. If none of the types in that list can represent all the
2795 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2796 // type can be converted to an rvalue a prvalue of the extended integer type
2797 // with lowest integer conversion rank (4.13) greater than the rank of long
2798 // long in which all the values of the enumeration can be represented. If
2799 // there are two such extended types, the signed one is chosen.
2800 // C++11 [conv.prom]p4:
2801 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2802 // can be converted to a prvalue of its underlying type. Moreover, if
2803 // integral promotion can be applied to its underlying type, a prvalue of an
2804 // unscoped enumeration type whose underlying type is fixed can also be
2805 // converted to a prvalue of the promoted underlying type.
2806 if (const auto *FromED = FromType->getAsEnumDecl()) {
2807 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2808 // provided for a scoped enumeration.
2809 if (FromED->isScoped())
2810 return false;
2811
2812 // We can perform an integral promotion to the underlying type of the enum,
2813 // even if that's not the promoted type. Note that the check for promoting
2814 // the underlying type is based on the type alone, and does not consider
2815 // the bitfield-ness of the actual source expression.
2816 if (FromED->isFixed()) {
2817 QualType Underlying = FromED->getIntegerType();
2818 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2819 IsIntegralPromotion(nullptr, Underlying, ToType);
2820 }
2821
2822 // We have already pre-calculated the promotion type, so this is trivial.
2823 if (ToType->isIntegerType() &&
2824 isCompleteType(From->getBeginLoc(), FromType))
2825 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2826
2827 // C++ [conv.prom]p5:
2828 // If the bit-field has an enumerated type, it is treated as any other
2829 // value of that type for promotion purposes.
2830 //
2831 // ... so do not fall through into the bit-field checks below in C++.
2832 if (getLangOpts().CPlusPlus)
2833 return false;
2834 }
2835
2836 // C++0x [conv.prom]p2:
2837 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2838 // to an rvalue a prvalue of the first of the following types that can
2839 // represent all the values of its underlying type: int, unsigned int,
2840 // long int, unsigned long int, long long int, or unsigned long long int.
2841 // If none of the types in that list can represent all the values of its
2842 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2843 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2844 // type.
2845 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2846 ToType->isIntegerType()) {
2847 // Determine whether the type we're converting from is signed or
2848 // unsigned.
2849 bool FromIsSigned = FromType->isSignedIntegerType();
2850 uint64_t FromSize = Context.getTypeSize(FromType);
2851
2852 // The types we'll try to promote to, in the appropriate
2853 // order. Try each of these types.
2854 QualType PromoteTypes[6] = {
2855 Context.IntTy, Context.UnsignedIntTy,
2856 Context.LongTy, Context.UnsignedLongTy ,
2857 Context.LongLongTy, Context.UnsignedLongLongTy
2858 };
2859 for (int Idx = 0; Idx < 6; ++Idx) {
2860 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2861 if (FromSize < ToSize ||
2862 (FromSize == ToSize &&
2863 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2864 // We found the type that we can promote to. If this is the
2865 // type we wanted, we have a promotion. Otherwise, no
2866 // promotion.
2867 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2868 }
2869 }
2870 }
2871
2872 // An rvalue for an integral bit-field (9.6) can be converted to an
2873 // rvalue of type int if int can represent all the values of the
2874 // bit-field; otherwise, it can be converted to unsigned int if
2875 // unsigned int can represent all the values of the bit-field. If
2876 // the bit-field is larger yet, no integral promotion applies to
2877 // it. If the bit-field has an enumerated type, it is treated as any
2878 // other value of that type for promotion purposes (C++ 4.5p3).
2879 // FIXME: We should delay checking of bit-fields until we actually perform the
2880 // conversion.
2881 //
2882 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2883 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2884 // bit-fields and those whose underlying type is larger than int) for GCC
2885 // compatibility.
2886 if (From) {
2887 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2888 std::optional<llvm::APSInt> BitWidth;
2889 if (FromType->isIntegralType(Context) &&
2890 (BitWidth =
2891 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2892 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2893 ToSize = Context.getTypeSize(ToType);
2894
2895 // Are we promoting to an int from a bitfield that fits in an int?
2896 if (*BitWidth < ToSize ||
2897 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2898 return To->getKind() == BuiltinType::Int;
2899 }
2900
2901 // Are we promoting to an unsigned int from an unsigned bitfield
2902 // that fits into an unsigned int?
2903 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2904 return To->getKind() == BuiltinType::UInt;
2905 }
2906
2907 return false;
2908 }
2909 }
2910 }
2911
2912 // An rvalue of type bool can be converted to an rvalue of type int,
2913 // with false becoming zero and true becoming one (C++ 4.5p4).
2914 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2915 return true;
2916 }
2917
2918 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2919 // integral type.
2920 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2921 ToType->isIntegerType())
2922 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2923
2924 return false;
2925}
2926
2928 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2929 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2930 /// An rvalue of type float can be converted to an rvalue of type
2931 /// double. (C++ 4.6p1).
2932 if (FromBuiltin->getKind() == BuiltinType::Float &&
2933 ToBuiltin->getKind() == BuiltinType::Double)
2934 return true;
2935
2936 // C99 6.3.1.5p1:
2937 // When a float is promoted to double or long double, or a
2938 // double is promoted to long double [...].
2939 if (!getLangOpts().CPlusPlus &&
2940 (FromBuiltin->getKind() == BuiltinType::Float ||
2941 FromBuiltin->getKind() == BuiltinType::Double) &&
2942 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2943 ToBuiltin->getKind() == BuiltinType::Float128 ||
2944 ToBuiltin->getKind() == BuiltinType::Ibm128))
2945 return true;
2946
2947 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2948 // or not native half types are enabled.
2949 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2950 (ToBuiltin->getKind() == BuiltinType::Float ||
2951 ToBuiltin->getKind() == BuiltinType::Double))
2952 return true;
2953
2954 // Half can be promoted to float.
2955 if (!getLangOpts().NativeHalfType &&
2956 FromBuiltin->getKind() == BuiltinType::Half &&
2957 ToBuiltin->getKind() == BuiltinType::Float)
2958 return true;
2959 }
2960
2961 return false;
2962}
2963
2965 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2966 if (!FromComplex)
2967 return false;
2968
2969 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2970 if (!ToComplex)
2971 return false;
2972
2973 return IsFloatingPointPromotion(FromComplex->getElementType(),
2974 ToComplex->getElementType()) ||
2975 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2976 ToComplex->getElementType());
2977}
2978
2980 if (!getLangOpts().OverflowBehaviorTypes)
2981 return false;
2982
2983 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2984 return false;
2985
2986 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2987}
2988
2990 QualType ToType) {
2991 if (!getLangOpts().OverflowBehaviorTypes)
2992 return false;
2993
2994 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2995 if (ToType->isBooleanType())
2996 return false;
2997 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2998 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2999 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
3000 if (ToED->isScoped())
3001 return false;
3002 }
3003 return true;
3004 }
3005
3006 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3007 return true;
3008
3009 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
3010 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
3011
3012 return false;
3013}
3014
3015/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
3016/// the pointer type FromPtr to a pointer to type ToPointee, with the
3017/// same type qualifiers as FromPtr has on its pointee type. ToType,
3018/// if non-empty, will be a pointer to ToType that may or may not have
3019/// the right set of qualifiers on its pointee.
3020///
3021static QualType
3023 QualType ToPointee, QualType ToType,
3024 ASTContext &Context,
3025 bool StripObjCLifetime = false) {
3026 assert((FromPtr->getTypeClass() == Type::Pointer ||
3027 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3028 "Invalid similarly-qualified pointer type");
3029
3030 /// Conversions to 'id' subsume cv-qualifier conversions.
3031 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3032 return ToType.getUnqualifiedType();
3033
3034 QualType CanonFromPointee
3035 = Context.getCanonicalType(FromPtr->getPointeeType());
3036 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3037 Qualifiers Quals = CanonFromPointee.getQualifiers();
3038
3039 if (StripObjCLifetime)
3040 Quals.removeObjCLifetime();
3041
3042 // Exact qualifier match -> return the pointer type we're converting to.
3043 if (CanonToPointee.getLocalQualifiers() == Quals) {
3044 // ToType is exactly what we need. Return it.
3045 if (!ToType.isNull())
3046 return ToType.getUnqualifiedType();
3047
3048 // Build a pointer to ToPointee. It has the right qualifiers
3049 // already.
3050 if (isa<ObjCObjectPointerType>(ToType))
3051 return Context.getObjCObjectPointerType(ToPointee);
3052 return Context.getPointerType(ToPointee);
3053 }
3054
3055 // Just build a canonical type that has the right qualifiers.
3056 QualType QualifiedCanonToPointee
3057 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3058
3059 if (isa<ObjCObjectPointerType>(ToType))
3060 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3061 return Context.getPointerType(QualifiedCanonToPointee);
3062}
3063
3065 bool InOverloadResolution,
3066 ASTContext &Context) {
3067 // Handle value-dependent integral null pointer constants correctly.
3068 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3069 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3071 return !InOverloadResolution;
3072
3073 return Expr->isNullPointerConstant(Context,
3074 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3076}
3077
3079 bool InOverloadResolution,
3080 QualType& ConvertedType,
3081 bool &IncompatibleObjC) {
3082 IncompatibleObjC = false;
3083 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3084 IncompatibleObjC))
3085 return true;
3086
3087 // Conversion from a null pointer constant to any Objective-C pointer type.
3088 if (ToType->isObjCObjectPointerType() &&
3089 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3090 ConvertedType = ToType;
3091 return true;
3092 }
3093
3094 // Blocks: Block pointers can be converted to void*.
3095 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3096 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3097 ConvertedType = ToType;
3098 return true;
3099 }
3100 // Blocks: A null pointer constant can be converted to a block
3101 // pointer type.
3102 if (ToType->isBlockPointerType() &&
3103 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3104 ConvertedType = ToType;
3105 return true;
3106 }
3107
3108 // If the left-hand-side is nullptr_t, the right side can be a null
3109 // pointer constant.
3110 if (ToType->isNullPtrType() &&
3111 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3112 ConvertedType = ToType;
3113 return true;
3114 }
3115
3116 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3117 if (!ToTypePtr)
3118 return false;
3119
3120 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3121 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3122 ConvertedType = ToType;
3123 return true;
3124 }
3125
3126 // Beyond this point, both types need to be pointers
3127 // , including objective-c pointers.
3128 QualType ToPointeeType = ToTypePtr->getPointeeType();
3129 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3130 !getLangOpts().ObjCAutoRefCount) {
3131 ConvertedType = BuildSimilarlyQualifiedPointerType(
3132 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3133 Context);
3134 return true;
3135 }
3136 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3137 if (!FromTypePtr)
3138 return false;
3139
3140 QualType FromPointeeType = FromTypePtr->getPointeeType();
3141
3142 // If the unqualified pointee types are the same, this can't be a
3143 // pointer conversion, so don't do all of the work below.
3144 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3145 return false;
3146
3147 // An rvalue of type "pointer to cv T," where T is an object type,
3148 // can be converted to an rvalue of type "pointer to cv void" (C++
3149 // 4.10p2).
3150 if (FromPointeeType->isIncompleteOrObjectType() &&
3151 ToPointeeType->isVoidType()) {
3152 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3153 ToPointeeType,
3154 ToType, Context,
3155 /*StripObjCLifetime=*/true);
3156 return true;
3157 }
3158
3159 // MSVC allows implicit function to void* type conversion.
3160 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3161 ToPointeeType->isVoidType()) {
3162 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3163 ToPointeeType,
3164 ToType, Context);
3165 return true;
3166 }
3167
3168 // When we're overloading in C, we allow a special kind of pointer
3169 // conversion for compatible-but-not-identical pointee types.
3170 if (!getLangOpts().CPlusPlus &&
3171 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3172 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3173 ToPointeeType,
3174 ToType, Context);
3175 return true;
3176 }
3177
3178 // C++ [conv.ptr]p3:
3179 //
3180 // An rvalue of type "pointer to cv D," where D is a class type,
3181 // can be converted to an rvalue of type "pointer to cv B," where
3182 // B is a base class (clause 10) of D. If B is an inaccessible
3183 // (clause 11) or ambiguous (10.2) base class of D, a program that
3184 // necessitates this conversion is ill-formed. The result of the
3185 // conversion is a pointer to the base class sub-object of the
3186 // derived class object. The null pointer value is converted to
3187 // the null pointer value of the destination type.
3188 //
3189 // Note that we do not check for ambiguity or inaccessibility
3190 // here. That is handled by CheckPointerConversion.
3191 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3192 ToPointeeType->isRecordType() &&
3193 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3194 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3196 ToPointeeType,
3197 ToType, Context);
3198 return true;
3199 }
3200
3201 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3202 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3203 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3204 ToPointeeType,
3205 ToType, Context);
3206 return true;
3207 }
3208
3209 return false;
3210}
3211
3212/// Adopt the given qualifiers for the given type.
3214 Qualifiers TQs = T.getQualifiers();
3215
3216 // Check whether qualifiers already match.
3217 if (TQs == Qs)
3218 return T;
3219
3220 if (Qs.compatiblyIncludes(TQs, Context))
3221 return Context.getQualifiedType(T, Qs);
3222
3223 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3224}
3225
3227 QualType& ConvertedType,
3228 bool &IncompatibleObjC) {
3229 if (!getLangOpts().ObjC)
3230 return false;
3231
3232 // The set of qualifiers on the type we're converting from.
3233 Qualifiers FromQualifiers = FromType.getQualifiers();
3234
3235 // First, we handle all conversions on ObjC object pointer types.
3236 const ObjCObjectPointerType* ToObjCPtr =
3237 ToType->getAs<ObjCObjectPointerType>();
3238 const ObjCObjectPointerType *FromObjCPtr =
3239 FromType->getAs<ObjCObjectPointerType>();
3240
3241 if (ToObjCPtr && FromObjCPtr) {
3242 // If the pointee types are the same (ignoring qualifications),
3243 // then this is not a pointer conversion.
3244 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3245 FromObjCPtr->getPointeeType()))
3246 return false;
3247
3248 // Conversion between Objective-C pointers.
3249 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3250 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3251 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3252 if (getLangOpts().CPlusPlus && LHS && RHS &&
3254 FromObjCPtr->getPointeeType(), getASTContext()))
3255 return false;
3256 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3257 ToObjCPtr->getPointeeType(),
3258 ToType, Context);
3259 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3260 return true;
3261 }
3262
3263 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3264 // Okay: this is some kind of implicit downcast of Objective-C
3265 // interfaces, which is permitted. However, we're going to
3266 // complain about it.
3267 IncompatibleObjC = true;
3268 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3269 ToObjCPtr->getPointeeType(),
3270 ToType, Context);
3271 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3272 return true;
3273 }
3274 }
3275 // Beyond this point, both types need to be C pointers or block pointers.
3276 QualType ToPointeeType;
3277 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3278 ToPointeeType = ToCPtr->getPointeeType();
3279 else if (const BlockPointerType *ToBlockPtr =
3280 ToType->getAs<BlockPointerType>()) {
3281 // Objective C++: We're able to convert from a pointer to any object
3282 // to a block pointer type.
3283 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3284 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3285 return true;
3286 }
3287 ToPointeeType = ToBlockPtr->getPointeeType();
3288 }
3289 else if (FromType->getAs<BlockPointerType>() &&
3290 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3291 // Objective C++: We're able to convert from a block pointer type to a
3292 // pointer to any object.
3293 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3294 return true;
3295 }
3296 else
3297 return false;
3298
3299 QualType FromPointeeType;
3300 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3301 FromPointeeType = FromCPtr->getPointeeType();
3302 else if (const BlockPointerType *FromBlockPtr =
3303 FromType->getAs<BlockPointerType>())
3304 FromPointeeType = FromBlockPtr->getPointeeType();
3305 else
3306 return false;
3307
3308 // If we have pointers to pointers, recursively check whether this
3309 // is an Objective-C conversion.
3310 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3311 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3312 IncompatibleObjC)) {
3313 // We always complain about this conversion.
3314 IncompatibleObjC = true;
3315 ConvertedType = Context.getPointerType(ConvertedType);
3316 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3317 return true;
3318 }
3319 // Allow conversion of pointee being objective-c pointer to another one;
3320 // as in I* to id.
3321 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3322 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3323 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3324 IncompatibleObjC)) {
3325
3326 ConvertedType = Context.getPointerType(ConvertedType);
3327 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3328 return true;
3329 }
3330
3331 // If we have pointers to functions or blocks, check whether the only
3332 // differences in the argument and result types are in Objective-C
3333 // pointer conversions. If so, we permit the conversion (but
3334 // complain about it).
3335 const FunctionProtoType *FromFunctionType
3336 = FromPointeeType->getAs<FunctionProtoType>();
3337 const FunctionProtoType *ToFunctionType
3338 = ToPointeeType->getAs<FunctionProtoType>();
3339 if (FromFunctionType && ToFunctionType) {
3340 // If the function types are exactly the same, this isn't an
3341 // Objective-C pointer conversion.
3342 if (Context.getCanonicalType(FromPointeeType)
3343 == Context.getCanonicalType(ToPointeeType))
3344 return false;
3345
3346 // Perform the quick checks that will tell us whether these
3347 // function types are obviously different.
3348 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3349 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3350 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3351 return false;
3352
3353 bool HasObjCConversion = false;
3354 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3355 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3356 // Okay, the types match exactly. Nothing to do.
3357 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3358 ToFunctionType->getReturnType(),
3359 ConvertedType, IncompatibleObjC)) {
3360 // Okay, we have an Objective-C pointer conversion.
3361 HasObjCConversion = true;
3362 } else {
3363 // Function types are too different. Abort.
3364 return false;
3365 }
3366
3367 // Check argument types.
3368 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3369 ArgIdx != NumArgs; ++ArgIdx) {
3370 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3371 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3372 if (Context.getCanonicalType(FromArgType)
3373 == Context.getCanonicalType(ToArgType)) {
3374 // Okay, the types match exactly. Nothing to do.
3375 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3376 ConvertedType, IncompatibleObjC)) {
3377 // Okay, we have an Objective-C pointer conversion.
3378 HasObjCConversion = true;
3379 } else {
3380 // Argument types are too different. Abort.
3381 return false;
3382 }
3383 }
3384
3385 if (HasObjCConversion) {
3386 // We had an Objective-C conversion. Allow this pointer
3387 // conversion, but complain about it.
3388 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3389 IncompatibleObjC = true;
3390 return true;
3391 }
3392 }
3393
3394 return false;
3395}
3396
3398 QualType& ConvertedType) {
3399 QualType ToPointeeType;
3400 if (const BlockPointerType *ToBlockPtr =
3401 ToType->getAs<BlockPointerType>())
3402 ToPointeeType = ToBlockPtr->getPointeeType();
3403 else
3404 return false;
3405
3406 QualType FromPointeeType;
3407 if (const BlockPointerType *FromBlockPtr =
3408 FromType->getAs<BlockPointerType>())
3409 FromPointeeType = FromBlockPtr->getPointeeType();
3410 else
3411 return false;
3412 // We have pointer to blocks, check whether the only
3413 // differences in the argument and result types are in Objective-C
3414 // pointer conversions. If so, we permit the conversion.
3415
3416 const FunctionProtoType *FromFunctionType
3417 = FromPointeeType->getAs<FunctionProtoType>();
3418 const FunctionProtoType *ToFunctionType
3419 = ToPointeeType->getAs<FunctionProtoType>();
3420
3421 if (!FromFunctionType || !ToFunctionType)
3422 return false;
3423
3424 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3425 return true;
3426
3427 // Perform the quick checks that will tell us whether these
3428 // function types are obviously different.
3429 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3430 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3431 return false;
3432
3433 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3434 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3435 if (FromEInfo != ToEInfo)
3436 return false;
3437
3438 bool IncompatibleObjC = false;
3439 if (Context.hasSameType(FromFunctionType->getReturnType(),
3440 ToFunctionType->getReturnType())) {
3441 // Okay, the types match exactly. Nothing to do.
3442 } else {
3443 QualType RHS = FromFunctionType->getReturnType();
3444 QualType LHS = ToFunctionType->getReturnType();
3445 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3446 !RHS.hasQualifiers() && LHS.hasQualifiers())
3447 LHS = LHS.getUnqualifiedType();
3448
3449 if (Context.hasSameType(RHS,LHS)) {
3450 // OK exact match.
3451 } else if (isObjCPointerConversion(RHS, LHS,
3452 ConvertedType, IncompatibleObjC)) {
3453 if (IncompatibleObjC)
3454 return false;
3455 // Okay, we have an Objective-C pointer conversion.
3456 }
3457 else
3458 return false;
3459 }
3460
3461 // Check argument types.
3462 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3463 ArgIdx != NumArgs; ++ArgIdx) {
3464 IncompatibleObjC = false;
3465 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3466 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3467 if (Context.hasSameType(FromArgType, ToArgType)) {
3468 // Okay, the types match exactly. Nothing to do.
3469 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3470 ConvertedType, IncompatibleObjC)) {
3471 if (IncompatibleObjC)
3472 return false;
3473 // Okay, we have an Objective-C pointer conversion.
3474 } else
3475 // Argument types are too different. Abort.
3476 return false;
3477 }
3478
3480 bool CanUseToFPT, CanUseFromFPT;
3481 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3482 CanUseToFPT, CanUseFromFPT,
3483 NewParamInfos))
3484 return false;
3485
3486 ConvertedType = ToType;
3487 return true;
3488}
3489
3490enum {
3498};
3499
3500/// Attempts to get the FunctionProtoType from a Type. Handles
3501/// MemberFunctionPointers properly.
3503 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3504 return FPT;
3505
3506 if (auto *MPT = FromType->getAs<MemberPointerType>())
3507 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3508
3509 return nullptr;
3510}
3511
3513 QualType FromType, QualType ToType) {
3514 // If either type is not valid, include no extra info.
3515 if (FromType.isNull() || ToType.isNull()) {
3516 PDiag << ft_default;
3517 return;
3518 }
3519
3520 // Get the function type from the pointers.
3521 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3522 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3523 *ToMember = ToType->castAs<MemberPointerType>();
3524 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3525 ToMember->getMostRecentCXXRecordDecl())) {
3527 if (ToMember->isSugared())
3528 PDiag << Context.getCanonicalTagType(
3529 ToMember->getMostRecentCXXRecordDecl());
3530 else
3531 PDiag << ToMember->getQualifier();
3532 if (FromMember->isSugared())
3533 PDiag << Context.getCanonicalTagType(
3534 FromMember->getMostRecentCXXRecordDecl());
3535 else
3536 PDiag << FromMember->getQualifier();
3537 return;
3538 }
3539 FromType = FromMember->getPointeeType();
3540 ToType = ToMember->getPointeeType();
3541 }
3542
3543 if (FromType->isPointerType())
3544 FromType = FromType->getPointeeType();
3545 if (ToType->isPointerType())
3546 ToType = ToType->getPointeeType();
3547
3548 // Remove references.
3549 FromType = FromType.getNonReferenceType();
3550 ToType = ToType.getNonReferenceType();
3551
3552 // Don't print extra info for non-specialized template functions.
3553 if (FromType->isInstantiationDependentType() &&
3554 !FromType->getAs<TemplateSpecializationType>()) {
3555 PDiag << ft_default;
3556 return;
3557 }
3558
3559 // No extra info for same types.
3560 if (Context.hasSameType(FromType, ToType)) {
3561 PDiag << ft_default;
3562 return;
3563 }
3564
3565 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3566 *ToFunction = tryGetFunctionProtoType(ToType);
3567
3568 // Both types need to be function types.
3569 if (!FromFunction || !ToFunction) {
3570 PDiag << ft_default;
3571 return;
3572 }
3573
3574 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3575 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3576 << FromFunction->getNumParams();
3577 return;
3578 }
3579
3580 // Handle different parameter types.
3581 unsigned ArgPos;
3582 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3583 PDiag << ft_parameter_mismatch << ArgPos + 1
3584 << ToFunction->getParamType(ArgPos)
3585 << FromFunction->getParamType(ArgPos);
3586 return;
3587 }
3588
3589 // Handle different return type.
3590 if (!Context.hasSameType(FromFunction->getReturnType(),
3591 ToFunction->getReturnType())) {
3592 PDiag << ft_return_type << ToFunction->getReturnType()
3593 << FromFunction->getReturnType();
3594 return;
3595 }
3596
3597 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3598 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3599 << FromFunction->getMethodQuals();
3600 return;
3601 }
3602
3603 // Handle exception specification differences on canonical type (in C++17
3604 // onwards).
3606 ->isNothrow() !=
3607 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3608 ->isNothrow()) {
3609 PDiag << ft_noexcept;
3610 return;
3611 }
3612
3613 // Unable to find a difference, so add no extra info.
3614 PDiag << ft_default;
3615}
3616
3618 ArrayRef<QualType> New, unsigned *ArgPos,
3619 bool Reversed) {
3620 assert(llvm::size(Old) == llvm::size(New) &&
3621 "Can't compare parameters of functions with different number of "
3622 "parameters!");
3623
3624 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3625 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3626 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3627
3628 // Ignore address spaces in pointee type. This is to disallow overloading
3629 // on __ptr32/__ptr64 address spaces.
3630 QualType OldType =
3631 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3632 QualType NewType =
3633 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3634
3635 if (!Context.hasSameType(OldType, NewType)) {
3636 if (ArgPos)
3637 *ArgPos = Idx;
3638 return false;
3639 }
3640 }
3641 return true;
3642}
3643
3645 const FunctionProtoType *NewType,
3646 unsigned *ArgPos, bool Reversed) {
3647 return FunctionParamTypesAreEqual(OldType->param_types(),
3648 NewType->param_types(), ArgPos, Reversed);
3649}
3650
3652 const FunctionDecl *NewFunction,
3653 unsigned *ArgPos,
3654 bool Reversed) {
3655
3656 if (OldFunction->getNumNonObjectParams() !=
3657 NewFunction->getNumNonObjectParams())
3658 return false;
3659
3660 unsigned OldIgnore =
3662 unsigned NewIgnore =
3664
3665 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3666 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3667
3668 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3669 NewPT->param_types().slice(NewIgnore),
3670 ArgPos, Reversed);
3671}
3672
3674 CastKind &Kind,
3675 CXXCastPath& BasePath,
3676 bool IgnoreBaseAccess,
3677 bool Diagnose) {
3678 QualType FromType = From->getType();
3679 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3680
3681 Kind = CK_BitCast;
3682
3683 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3686 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3687 DiagRuntimeBehavior(From->getExprLoc(), From,
3688 PDiag(diag::warn_impcast_bool_to_null_pointer)
3689 << ToType << From->getSourceRange());
3690 else if (!isUnevaluatedContext())
3691 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3692 << ToType << From->getSourceRange();
3693 }
3694 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3695 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3696 QualType FromPointeeType = FromPtrType->getPointeeType(),
3697 ToPointeeType = ToPtrType->getPointeeType();
3698
3699 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3700 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3701 // We must have a derived-to-base conversion. Check an
3702 // ambiguous or inaccessible conversion.
3703 unsigned InaccessibleID = 0;
3704 unsigned AmbiguousID = 0;
3705 if (Diagnose) {
3706 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3707 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3708 }
3710 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3711 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3712 &BasePath, IgnoreBaseAccess))
3713 return true;
3714
3715 // The conversion was successful.
3716 Kind = CK_DerivedToBase;
3717 }
3718
3719 if (Diagnose && !IsCStyleOrFunctionalCast &&
3720 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3721 assert(getLangOpts().MSVCCompat &&
3722 "this should only be possible with MSVCCompat!");
3723 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3724 << From->getSourceRange();
3725 }
3726 }
3727 } else if (const ObjCObjectPointerType *ToPtrType =
3728 ToType->getAs<ObjCObjectPointerType>()) {
3729 if (const ObjCObjectPointerType *FromPtrType =
3730 FromType->getAs<ObjCObjectPointerType>()) {
3731 // Objective-C++ conversions are always okay.
3732 // FIXME: We should have a different class of conversions for the
3733 // Objective-C++ implicit conversions.
3734 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3735 return false;
3736 } else if (FromType->isBlockPointerType()) {
3737 Kind = CK_BlockPointerToObjCPointerCast;
3738 } else {
3739 Kind = CK_CPointerToObjCPointerCast;
3740 }
3741 } else if (ToType->isBlockPointerType()) {
3742 if (!FromType->isBlockPointerType())
3743 Kind = CK_AnyPointerToBlockPointerCast;
3744 }
3745
3746 // We shouldn't fall into this case unless it's valid for other
3747 // reasons.
3749 Kind = CK_NullToPointer;
3750
3751 return false;
3752}
3753
3755 QualType ToType,
3756 bool InOverloadResolution,
3757 QualType &ConvertedType) {
3758 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3759 if (!ToTypePtr)
3760 return false;
3761
3762 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3764 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3766 ConvertedType = ToType;
3767 return true;
3768 }
3769
3770 // Otherwise, both types have to be member pointers.
3771 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3772 if (!FromTypePtr)
3773 return false;
3774
3775 // A pointer to member of B can be converted to a pointer to member of D,
3776 // where D is derived from B (C++ 4.11p2).
3777 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3778 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3779
3780 if (!declaresSameEntity(FromClass, ToClass) &&
3781 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3782 ConvertedType = Context.getMemberPointerType(
3783 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3784 return true;
3785 }
3786
3787 return false;
3788}
3789
3791 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3792 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3793 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3794 // Lock down the inheritance model right now in MS ABI, whether or not the
3795 // pointee types are the same.
3796 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3797 (void)isCompleteType(CheckLoc, FromType);
3798 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3799 }
3800
3801 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3802 if (!FromPtrType) {
3803 // This must be a null pointer to member pointer conversion
3804 Kind = CK_NullToMemberPointer;
3806 }
3807
3808 // T == T, modulo cv
3810 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3811 ToPtrType->getPointeeType()))
3813
3814 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3815 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3816
3817 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3818 const CXXRecordDecl *Cls) {
3819 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3820 PD << Qual;
3821 else
3822 PD << Context.getCanonicalTagType(Cls);
3823 };
3824 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3825 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3826 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3827 return PD;
3828 };
3829
3830 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3832 std::swap(Base, Derived);
3833
3834 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3835 /*DetectVirtual=*/true);
3836 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3838
3839 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3840 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3841 PD << int(Direction);
3842 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3843 Diag(CheckLoc, PD);
3845 }
3846
3847 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3848 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3849 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3850 Diag(CheckLoc, PD);
3852 }
3853
3854 // Must be a base to derived member conversion.
3855 BuildBasePathArray(Paths, BasePath);
3857 ? CK_DerivedToBaseMemberPointer
3858 : CK_BaseToDerivedMemberPointer;
3859
3860 if (!IgnoreBaseAccess)
3861 switch (CheckBaseClassAccess(
3862 CheckLoc, Base, Derived, Paths.front(),
3864 ? diag::err_upcast_to_inaccessible_base
3865 : diag::err_downcast_from_inaccessible_base,
3866 [&](PartialDiagnostic &PD) {
3867 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3868 DerivedQual = ToPtrType->getQualifier();
3869 if (Direction == MemberPointerConversionDirection::Upcast)
3870 std::swap(BaseQual, DerivedQual);
3871 DiagCls(PD, DerivedQual, Derived);
3872 DiagCls(PD, BaseQual, Base);
3873 })) {
3875 case Sema::AR_delayed:
3876 case Sema::AR_dependent:
3877 // Optimistically assume that the delayed and dependent cases
3878 // will work out.
3879 break;
3880
3883 }
3884
3886}
3887
3888/// Determine whether the lifetime conversion between the two given
3889/// qualifiers sets is nontrivial.
3891 Qualifiers ToQuals) {
3892 // Converting anything to const __unsafe_unretained is trivial.
3893 if (ToQuals.hasConst() &&
3895 return false;
3896
3897 return true;
3898}
3899
3900/// Perform a single iteration of the loop for checking if a qualification
3901/// conversion is valid.
3902///
3903/// Specifically, check whether any change between the qualifiers of \p
3904/// FromType and \p ToType is permissible, given knowledge about whether every
3905/// outer layer is const-qualified.
3907 bool CStyle, bool IsTopLevel,
3908 bool &PreviousToQualsIncludeConst,
3909 bool &ObjCLifetimeConversion,
3910 const ASTContext &Ctx) {
3911 Qualifiers FromQuals = FromType.getQualifiers();
3912 Qualifiers ToQuals = ToType.getQualifiers();
3913
3914 // Ignore __unaligned qualifier.
3915 FromQuals.removeUnaligned();
3916
3917 // Objective-C ARC:
3918 // Check Objective-C lifetime conversions.
3919 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3920 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3921 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3922 ObjCLifetimeConversion = true;
3923 FromQuals.removeObjCLifetime();
3924 ToQuals.removeObjCLifetime();
3925 } else {
3926 // Qualification conversions cannot cast between different
3927 // Objective-C lifetime qualifiers.
3928 return false;
3929 }
3930 }
3931
3932 // Allow addition/removal of GC attributes but not changing GC attributes.
3933 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3934 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3935 FromQuals.removeObjCGCAttr();
3936 ToQuals.removeObjCGCAttr();
3937 }
3938
3939 // __ptrauth qualifiers must match exactly.
3940 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3941 return false;
3942
3943 // -- for every j > 0, if const is in cv 1,j then const is in cv
3944 // 2,j, and similarly for volatile.
3945 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3946 return false;
3947
3948 // If address spaces mismatch:
3949 // - in top level it is only valid to convert to addr space that is a
3950 // superset in all cases apart from C-style casts where we allow
3951 // conversions between overlapping address spaces.
3952 // - in non-top levels it is not a valid conversion.
3953 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3954 (!IsTopLevel ||
3955 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3956 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3957 return false;
3958
3959 // -- if the cv 1,j and cv 2,j are different, then const is in
3960 // every cv for 0 < k < j.
3961 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3962 !PreviousToQualsIncludeConst)
3963 return false;
3964
3965 // The following wording is from C++20, where the result of the conversion
3966 // is T3, not T2.
3967 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3968 // "array of unknown bound of"
3969 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3970 return false;
3971
3972 // -- if the resulting P3,i is different from P1,i [...], then const is
3973 // added to every cv 3_k for 0 < k < i.
3974 if (!CStyle && FromType->isConstantArrayType() &&
3975 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3976 return false;
3977
3978 // Keep track of whether all prior cv-qualifiers in the "to" type
3979 // include const.
3980 PreviousToQualsIncludeConst =
3981 PreviousToQualsIncludeConst && ToQuals.hasConst();
3982 return true;
3983}
3984
3985bool
3987 bool CStyle, bool &ObjCLifetimeConversion) {
3988 FromType = Context.getCanonicalType(FromType);
3989 ToType = Context.getCanonicalType(ToType);
3990 ObjCLifetimeConversion = false;
3991
3992 // If FromType and ToType are the same type, this is not a
3993 // qualification conversion.
3994 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3995 return false;
3996
3997 // (C++ 4.4p4):
3998 // A conversion can add cv-qualifiers at levels other than the first
3999 // in multi-level pointers, subject to the following rules: [...]
4000 bool PreviousToQualsIncludeConst = true;
4001 bool UnwrappedAnyPointer = false;
4002 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
4003 if (!isQualificationConversionStep(FromType, ToType, CStyle,
4004 !UnwrappedAnyPointer,
4005 PreviousToQualsIncludeConst,
4006 ObjCLifetimeConversion, getASTContext()))
4007 return false;
4008 UnwrappedAnyPointer = true;
4009 }
4010
4011 // We are left with FromType and ToType being the pointee types
4012 // after unwrapping the original FromType and ToType the same number
4013 // of times. If we unwrapped any pointers, and if FromType and
4014 // ToType have the same unqualified type (since we checked
4015 // qualifiers above), then this is a qualification conversion.
4016 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
4017}
4018
4019/// - Determine whether this is a conversion from a scalar type to an
4020/// atomic type.
4021///
4022/// If successful, updates \c SCS's second and third steps in the conversion
4023/// sequence to finish the conversion.
4024static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4025 bool InOverloadResolution,
4027 bool CStyle) {
4028 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4029 if (!ToAtomic)
4030 return false;
4031
4033 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4034 InOverloadResolution, InnerSCS,
4035 CStyle, /*AllowObjCWritebackConversion=*/false))
4036 return false;
4037
4038 SCS.Second = InnerSCS.Second;
4039 SCS.setToType(1, InnerSCS.getToType(1));
4040 SCS.Third = InnerSCS.Third;
4043 SCS.setToType(2, InnerSCS.getToType(2));
4044 return true;
4045}
4046
4048 QualType ToType,
4049 bool InOverloadResolution,
4051 bool CStyle) {
4052 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4053 if (!ToOBT)
4054 return false;
4055
4056 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4057 QualType FromType = From->getType();
4058 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4059 return false;
4060
4062 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4063 InOverloadResolution, InnerSCS, CStyle,
4064 /*AllowObjCWritebackConversion=*/false))
4065 return false;
4066
4067 SCS.Second = InnerSCS.Second;
4068 SCS.setToType(1, InnerSCS.getToType(1));
4069 SCS.Third = InnerSCS.Third;
4072 SCS.setToType(2, InnerSCS.getToType(2));
4073 return true;
4074}
4075
4078 QualType Type) {
4079 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4080 if (CtorType->getNumParams() > 0) {
4081 QualType FirstArg = CtorType->getParamType(0);
4082 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4083 return true;
4084 }
4085 return false;
4086}
4087
4088static OverloadingResult
4090 CXXRecordDecl *To,
4092 OverloadCandidateSet &CandidateSet,
4093 bool AllowExplicit) {
4095 for (auto *D : S.LookupConstructors(To)) {
4096 auto Info = getConstructorInfo(D);
4097 if (!Info)
4098 continue;
4099
4100 bool Usable = !Info.Constructor->isInvalidDecl() &&
4101 S.isInitListConstructor(Info.Constructor);
4102 if (Usable) {
4103 bool SuppressUserConversions = false;
4104 if (Info.ConstructorTmpl)
4105 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4106 /*ExplicitArgs*/ nullptr, From,
4107 CandidateSet, SuppressUserConversions,
4108 /*PartialOverloading*/ false,
4109 AllowExplicit);
4110 else
4111 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4112 CandidateSet, SuppressUserConversions,
4113 /*PartialOverloading*/ false, AllowExplicit);
4114 }
4115 }
4116
4117 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4118
4120 switch (auto Result =
4121 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4122 case OR_Deleted:
4123 case OR_Success: {
4124 // Record the standard conversion we used and the conversion function.
4126 QualType ThisType = Constructor->getFunctionObjectParameterType();
4127 // Initializer lists don't have conversions as such.
4129 User.HadMultipleCandidates = HadMultipleCandidates;
4131 User.FoundConversionFunction = Best->FoundDecl;
4133 User.After.setFromType(ThisType);
4134 User.After.setAllToTypes(ToType);
4135 return Result;
4136 }
4137
4139 return OR_No_Viable_Function;
4140 case OR_Ambiguous:
4141 return OR_Ambiguous;
4142 }
4143
4144 llvm_unreachable("Invalid OverloadResult!");
4145}
4146
4147/// Determines whether there is a user-defined conversion sequence
4148/// (C++ [over.ics.user]) that converts expression From to the type
4149/// ToType. If such a conversion exists, User will contain the
4150/// user-defined conversion sequence that performs such a conversion
4151/// and this routine will return true. Otherwise, this routine returns
4152/// false and User is unspecified.
4153///
4154/// \param AllowExplicit true if the conversion should consider C++0x
4155/// "explicit" conversion functions as well as non-explicit conversion
4156/// functions (C++0x [class.conv.fct]p2).
4157///
4158/// \param AllowObjCConversionOnExplicit true if the conversion should
4159/// allow an extra Objective-C pointer conversion on uses of explicit
4160/// constructors. Requires \c AllowExplicit to also be set.
4161static OverloadingResult
4164 OverloadCandidateSet &CandidateSet,
4165 AllowedExplicit AllowExplicit,
4166 bool AllowObjCConversionOnExplicit) {
4167 assert(AllowExplicit != AllowedExplicit::None ||
4168 !AllowObjCConversionOnExplicit);
4170
4171 // Whether we will only visit constructors.
4172 bool ConstructorsOnly = false;
4173
4174 // If the type we are conversion to is a class type, enumerate its
4175 // constructors.
4176 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4177 // C++ [over.match.ctor]p1:
4178 // When objects of class type are direct-initialized (8.5), or
4179 // copy-initialized from an expression of the same or a
4180 // derived class type (8.5), overload resolution selects the
4181 // constructor. [...] For copy-initialization, the candidate
4182 // functions are all the converting constructors (12.3.1) of
4183 // that class. The argument list is the expression-list within
4184 // the parentheses of the initializer.
4185 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4186 (From->getType()->isRecordType() &&
4187 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4188 ConstructorsOnly = true;
4189
4190 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4191 // We're not going to find any constructors.
4192 } else if (auto *ToRecordDecl =
4193 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4194 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4195
4196 Expr **Args = &From;
4197 unsigned NumArgs = 1;
4198 bool ListInitializing = false;
4199 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4200 // But first, see if there is an init-list-constructor that will work.
4202 S, From, ToType, ToRecordDecl, User, CandidateSet,
4203 AllowExplicit == AllowedExplicit::All);
4205 return Result;
4206 // Never mind.
4207 CandidateSet.clear(
4209
4210 // If we're list-initializing, we pass the individual elements as
4211 // arguments, not the entire list.
4212 Args = InitList->getInits();
4213 NumArgs = InitList->getNumInits();
4214 ListInitializing = true;
4215 }
4216
4217 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4218 auto Info = getConstructorInfo(D);
4219 if (!Info)
4220 continue;
4221
4222 bool Usable = !Info.Constructor->isInvalidDecl();
4223 if (!ListInitializing)
4224 Usable = Usable && Info.Constructor->isConvertingConstructor(
4225 /*AllowExplicit*/ true);
4226 if (Usable) {
4227 bool SuppressUserConversions = !ConstructorsOnly;
4228 // C++20 [over.best.ics.general]/4.5:
4229 // if the target is the first parameter of a constructor [of class
4230 // X] and the constructor [...] is a candidate by [...] the second
4231 // phase of [over.match.list] when the initializer list has exactly
4232 // one element that is itself an initializer list, [...] and the
4233 // conversion is to X or reference to cv X, user-defined conversion
4234 // sequences are not considered.
4235 if (SuppressUserConversions && ListInitializing) {
4236 SuppressUserConversions =
4237 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4238 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4239 ToType);
4240 }
4241 if (Info.ConstructorTmpl)
4243 Info.ConstructorTmpl, Info.FoundDecl,
4244 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4245 CandidateSet, SuppressUserConversions,
4246 /*PartialOverloading*/ false,
4247 AllowExplicit == AllowedExplicit::All);
4248 else
4249 // Allow one user-defined conversion when user specifies a
4250 // From->ToType conversion via an static cast (c-style, etc).
4251 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4252 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4253 SuppressUserConversions,
4254 /*PartialOverloading*/ false,
4255 AllowExplicit == AllowedExplicit::All);
4256 }
4257 }
4258 }
4259 }
4260
4261 // Enumerate conversion functions, if we're allowed to.
4262 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4263 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4264 // No conversion functions from incomplete types.
4265 } else if (const RecordType *FromRecordType =
4266 From->getType()->getAsCanonical<RecordType>()) {
4267 if (auto *FromRecordDecl =
4268 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4269 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4270 // Add all of the conversion functions as candidates.
4271 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4272 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4273 DeclAccessPair FoundDecl = I.getPair();
4274 NamedDecl *D = FoundDecl.getDecl();
4275 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4276 if (isa<UsingShadowDecl>(D))
4277 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4278
4279 CXXConversionDecl *Conv;
4280 FunctionTemplateDecl *ConvTemplate;
4281 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4282 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4283 else
4284 Conv = cast<CXXConversionDecl>(D);
4285
4286 if (ConvTemplate)
4288 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4289 CandidateSet, AllowObjCConversionOnExplicit,
4290 AllowExplicit != AllowedExplicit::None);
4291 else
4292 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4293 CandidateSet, AllowObjCConversionOnExplicit,
4294 AllowExplicit != AllowedExplicit::None);
4295 }
4296 }
4297 }
4298
4299 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4300
4302 switch (auto Result =
4303 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4304 case OR_Success:
4305 case OR_Deleted:
4306 // Record the standard conversion we used and the conversion function.
4308 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4309 // C++ [over.ics.user]p1:
4310 // If the user-defined conversion is specified by a
4311 // constructor (12.3.1), the initial standard conversion
4312 // sequence converts the source type to the type required by
4313 // the argument of the constructor.
4314 //
4315 if (isa<InitListExpr>(From)) {
4316 // Initializer lists don't have conversions as such.
4318 User.Before.FromBracedInitList = true;
4319 } else {
4320 if (Best->Conversions[0].isEllipsis())
4321 User.EllipsisConversion = true;
4322 else {
4323 User.Before = Best->Conversions[0].Standard;
4324 User.EllipsisConversion = false;
4325 }
4326 }
4327 User.HadMultipleCandidates = HadMultipleCandidates;
4329 User.FoundConversionFunction = Best->FoundDecl;
4331 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4332 User.After.setAllToTypes(ToType);
4333 return Result;
4334 }
4335 if (CXXConversionDecl *Conversion
4336 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4337
4338 assert(Best->HasFinalConversion);
4339
4340 // C++ [over.ics.user]p1:
4341 //
4342 // [...] If the user-defined conversion is specified by a
4343 // conversion function (12.3.2), the initial standard
4344 // conversion sequence converts the source type to the
4345 // implicit object parameter of the conversion function.
4346 User.Before = Best->Conversions[0].Standard;
4347 User.HadMultipleCandidates = HadMultipleCandidates;
4348 User.ConversionFunction = Conversion;
4349 User.FoundConversionFunction = Best->FoundDecl;
4350 User.EllipsisConversion = false;
4351
4352 // C++ [over.ics.user]p2:
4353 // The second standard conversion sequence converts the
4354 // result of the user-defined conversion to the target type
4355 // for the sequence. Since an implicit conversion sequence
4356 // is an initialization, the special rules for
4357 // initialization by user-defined conversion apply when
4358 // selecting the best user-defined conversion for a
4359 // user-defined conversion sequence (see 13.3.3 and
4360 // 13.3.3.1).
4361 User.After = Best->FinalConversion;
4362 return Result;
4363 }
4364 llvm_unreachable("Not a constructor or conversion function?");
4365
4367 return OR_No_Viable_Function;
4368
4369 case OR_Ambiguous:
4370 return OR_Ambiguous;
4371 }
4372
4373 llvm_unreachable("Invalid OverloadResult!");
4374}
4375
4376bool
4379 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4381 OverloadingResult OvResult =
4382 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4383 CandidateSet, AllowedExplicit::None, false);
4384
4385 if (!(OvResult == OR_Ambiguous ||
4386 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4387 return false;
4388
4389 auto Cands = CandidateSet.CompleteCandidates(
4390 *this,
4392 From);
4393 if (OvResult == OR_Ambiguous)
4394 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4395 << From->getType() << ToType << From->getSourceRange();
4396 else { // OR_No_Viable_Function && !CandidateSet.empty()
4397 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4398 diag::err_typecheck_nonviable_condition_incomplete,
4399 From->getType(), From->getSourceRange()))
4400 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4401 << false << From->getType() << From->getSourceRange() << ToType;
4402 }
4403
4404 CandidateSet.NoteCandidates(
4405 *this, From, Cands);
4406 return true;
4407}
4408
4409// Helper for compareConversionFunctions that gets the FunctionType that the
4410// conversion-operator return value 'points' to, or nullptr.
4411static const FunctionType *
4413 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4414 const PointerType *RetPtrTy =
4415 ConvFuncTy->getReturnType()->getAs<PointerType>();
4416
4417 if (!RetPtrTy)
4418 return nullptr;
4419
4420 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4421}
4422
4423/// Compare the user-defined conversion functions or constructors
4424/// of two user-defined conversion sequences to determine whether any ordering
4425/// is possible.
4428 FunctionDecl *Function2) {
4429 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4430 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4431 if (!Conv1 || !Conv2)
4433
4434 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4436
4437 // Objective-C++:
4438 // If both conversion functions are implicitly-declared conversions from
4439 // a lambda closure type to a function pointer and a block pointer,
4440 // respectively, always prefer the conversion to a function pointer,
4441 // because the function pointer is more lightweight and is more likely
4442 // to keep code working.
4443 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4444 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4445 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4446 if (Block1 != Block2)
4447 return Block1 ? ImplicitConversionSequence::Worse
4449 }
4450
4451 // In order to support multiple calling conventions for the lambda conversion
4452 // operator (such as when the free and member function calling convention is
4453 // different), prefer the 'free' mechanism, followed by the calling-convention
4454 // of operator(). The latter is in place to support the MSVC-like solution of
4455 // defining ALL of the possible conversions in regards to calling-convention.
4456 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4457 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4458
4459 if (Conv1FuncRet && Conv2FuncRet &&
4460 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4461 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4462 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4463
4464 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4465 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4466
4467 CallingConv CallOpCC =
4468 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4470 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4472 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4473
4474 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4475 for (CallingConv CC : PrefOrder) {
4476 if (Conv1CC == CC)
4478 if (Conv2CC == CC)
4480 }
4481 }
4482
4484}
4485
4492
4493/// CompareImplicitConversionSequences - Compare two implicit
4494/// conversion sequences to determine whether one is better than the
4495/// other or if they are indistinguishable (C++ 13.3.3.2).
4498 const ImplicitConversionSequence& ICS1,
4499 const ImplicitConversionSequence& ICS2)
4500{
4501 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4502 // conversion sequences (as defined in 13.3.3.1)
4503 // -- a standard conversion sequence (13.3.3.1.1) is a better
4504 // conversion sequence than a user-defined conversion sequence or
4505 // an ellipsis conversion sequence, and
4506 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4507 // conversion sequence than an ellipsis conversion sequence
4508 // (13.3.3.1.3).
4509 //
4510 // C++0x [over.best.ics]p10:
4511 // For the purpose of ranking implicit conversion sequences as
4512 // described in 13.3.3.2, the ambiguous conversion sequence is
4513 // treated as a user-defined sequence that is indistinguishable
4514 // from any other user-defined conversion sequence.
4515
4516 // String literal to 'char *' conversion has been deprecated in C++03. It has
4517 // been removed from C++11. We still accept this conversion, if it happens at
4518 // the best viable function. Otherwise, this conversion is considered worse
4519 // than ellipsis conversion. Consider this as an extension; this is not in the
4520 // standard. For example:
4521 //
4522 // int &f(...); // #1
4523 // void f(char*); // #2
4524 // void g() { int &r = f("foo"); }
4525 //
4526 // In C++03, we pick #2 as the best viable function.
4527 // In C++11, we pick #1 as the best viable function, because ellipsis
4528 // conversion is better than string-literal to char* conversion (since there
4529 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4530 // convert arguments, #2 would be the best viable function in C++11.
4531 // If the best viable function has this conversion, a warning will be issued
4532 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4533
4534 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4537 // Ill-formedness must not differ
4538 ICS1.isBad() == ICS2.isBad())
4542
4543 if (ICS1.getKindRank() < ICS2.getKindRank())
4545 if (ICS2.getKindRank() < ICS1.getKindRank())
4547
4548 // The following checks require both conversion sequences to be of
4549 // the same kind.
4550 if (ICS1.getKind() != ICS2.getKind())
4552
4555
4556 // Two implicit conversion sequences of the same form are
4557 // indistinguishable conversion sequences unless one of the
4558 // following rules apply: (C++ 13.3.3.2p3):
4559
4560 // List-initialization sequence L1 is a better conversion sequence than
4561 // list-initialization sequence L2 if:
4562 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4563 // if not that,
4564 // — L1 and L2 convert to arrays of the same element type, and either the
4565 // number of elements n_1 initialized by L1 is less than the number of
4566 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4567 // an array of unknown bound and L1 does not,
4568 // even if one of the other rules in this paragraph would otherwise apply.
4569 if (!ICS1.isBad()) {
4570 bool StdInit1 = false, StdInit2 = false;
4573 nullptr);
4576 nullptr);
4577 if (StdInit1 != StdInit2)
4578 return StdInit1 ? ImplicitConversionSequence::Better
4580
4583 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4585 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4587 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4588 CAT2->getElementType())) {
4589 // Both to arrays of the same element type
4590 if (CAT1->getSize() != CAT2->getSize())
4591 // Different sized, the smaller wins
4592 return CAT1->getSize().ult(CAT2->getSize())
4597 // One is incomplete, it loses
4601 }
4602 }
4603 }
4604
4605 if (ICS1.isStandard())
4606 // Standard conversion sequence S1 is a better conversion sequence than
4607 // standard conversion sequence S2 if [...]
4609 ICS1.Standard, ICS2.Standard);
4610 else if (ICS1.isUserDefined()) {
4611 // With lazy template loading, it is possible to find non-canonical
4612 // FunctionDecls, depending on when redecl chains are completed. Make sure
4613 // to compare the canonical decls of conversion functions. This avoids
4614 // ambiguity problems for templated conversion operators.
4615 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4616 if (ConvFunc1)
4617 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4618 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4619 if (ConvFunc2)
4620 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4621 // User-defined conversion sequence U1 is a better conversion
4622 // sequence than another user-defined conversion sequence U2 if
4623 // they contain the same user-defined conversion function or
4624 // constructor and if the second standard conversion sequence of
4625 // U1 is better than the second standard conversion sequence of
4626 // U2 (C++ 13.3.3.2p3).
4627 if (ConvFunc1 == ConvFunc2)
4629 ICS1.UserDefined.After,
4630 ICS2.UserDefined.After);
4631 else
4635 }
4636
4637 return Result;
4638}
4639
4640// Per 13.3.3.2p3, compare the given standard conversion sequences to
4641// determine if one is a proper subset of the other.
4644 const StandardConversionSequence& SCS1,
4645 const StandardConversionSequence& SCS2) {
4648
4649 // the identity conversion sequence is considered to be a subsequence of
4650 // any non-identity conversion sequence
4651 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4653 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4655
4656 if (SCS1.Second != SCS2.Second) {
4657 if (SCS1.Second == ICK_Identity)
4659 else if (SCS2.Second == ICK_Identity)
4661 else
4663 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4665
4666 if (SCS1.Third == SCS2.Third) {
4667 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4669 }
4670
4671 if (SCS1.Third == ICK_Identity)
4675
4676 if (SCS2.Third == ICK_Identity)
4680
4682}
4683
4684/// Determine whether one of the given reference bindings is better
4685/// than the other based on what kind of bindings they are.
4686static bool
4688 const StandardConversionSequence &SCS2) {
4689 // C++0x [over.ics.rank]p3b4:
4690 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4691 // implicit object parameter of a non-static member function declared
4692 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4693 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4694 // lvalue reference to a function lvalue and S2 binds an rvalue
4695 // reference*.
4696 //
4697 // FIXME: Rvalue references. We're going rogue with the above edits,
4698 // because the semantics in the current C++0x working paper (N3225 at the
4699 // time of this writing) break the standard definition of std::forward
4700 // and std::reference_wrapper when dealing with references to functions.
4701 // Proposed wording changes submitted to CWG for consideration.
4704 return false;
4705
4706 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4707 SCS2.IsLvalueReference) ||
4710}
4711
4717
4718/// Returns kind of fixed enum promotion the \a SCS uses.
4719static FixedEnumPromotion
4721
4722 if (SCS.Second != ICK_Integral_Promotion)
4724
4725 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4726 if (!Enum)
4728
4729 if (!Enum->isFixed())
4731
4732 QualType UnderlyingType = Enum->getIntegerType();
4733 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4735
4737}
4738
4739/// CompareStandardConversionSequences - Compare two standard
4740/// conversion sequences to determine whether one is better than the
4741/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4744 const StandardConversionSequence& SCS1,
4745 const StandardConversionSequence& SCS2)
4746{
4747 // Standard conversion sequence S1 is a better conversion sequence
4748 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4749
4750 // -- S1 is a proper subsequence of S2 (comparing the conversion
4751 // sequences in the canonical form defined by 13.3.3.1.1,
4752 // excluding any Lvalue Transformation; the identity conversion
4753 // sequence is considered to be a subsequence of any
4754 // non-identity conversion sequence) or, if not that,
4757 return CK;
4758
4759 // -- the rank of S1 is better than the rank of S2 (by the rules
4760 // defined below), or, if not that,
4761 ImplicitConversionRank Rank1 = SCS1.getRank();
4762 ImplicitConversionRank Rank2 = SCS2.getRank();
4763 if (Rank1 < Rank2)
4765 else if (Rank2 < Rank1)
4767
4768 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4769 // are indistinguishable unless one of the following rules
4770 // applies:
4771
4772 // A conversion that is not a conversion of a pointer, or
4773 // pointer to member, to bool is better than another conversion
4774 // that is such a conversion.
4776 return SCS2.isPointerConversionToBool()
4779
4780 // C++14 [over.ics.rank]p4b2:
4781 // This is retroactively applied to C++11 by CWG 1601.
4782 //
4783 // A conversion that promotes an enumeration whose underlying type is fixed
4784 // to its underlying type is better than one that promotes to the promoted
4785 // underlying type, if the two are different.
4788 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4789 FEP1 != FEP2)
4793
4794 // C++ [over.ics.rank]p4b2:
4795 //
4796 // If class B is derived directly or indirectly from class A,
4797 // conversion of B* to A* is better than conversion of B* to
4798 // void*, and conversion of A* to void* is better than conversion
4799 // of B* to void*.
4800 bool SCS1ConvertsToVoid
4802 bool SCS2ConvertsToVoid
4804 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4805 // Exactly one of the conversion sequences is a conversion to
4806 // a void pointer; it's the worse conversion.
4807 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4809 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4810 // Neither conversion sequence converts to a void pointer; compare
4811 // their derived-to-base conversions.
4813 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4814 return DerivedCK;
4815 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4816 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4817 // Both conversion sequences are conversions to void
4818 // pointers. Compare the source types to determine if there's an
4819 // inheritance relationship in their sources.
4820 QualType FromType1 = SCS1.getFromType();
4821 QualType FromType2 = SCS2.getFromType();
4822
4823 // Adjust the types we're converting from via the array-to-pointer
4824 // conversion, if we need to.
4825 if (SCS1.First == ICK_Array_To_Pointer)
4826 FromType1 = S.Context.getArrayDecayedType(FromType1);
4827 if (SCS2.First == ICK_Array_To_Pointer)
4828 FromType2 = S.Context.getArrayDecayedType(FromType2);
4829
4830 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4831 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4832
4833 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4835 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4837
4838 // Objective-C++: If one interface is more specific than the
4839 // other, it is the better one.
4840 const ObjCObjectPointerType* FromObjCPtr1
4841 = FromType1->getAs<ObjCObjectPointerType>();
4842 const ObjCObjectPointerType* FromObjCPtr2
4843 = FromType2->getAs<ObjCObjectPointerType>();
4844 if (FromObjCPtr1 && FromObjCPtr2) {
4845 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4846 FromObjCPtr2);
4847 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4848 FromObjCPtr1);
4849 if (AssignLeft != AssignRight) {
4850 return AssignLeft? ImplicitConversionSequence::Better
4852 }
4853 }
4854 }
4855
4856 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4857 // Check for a better reference binding based on the kind of bindings.
4858 if (isBetterReferenceBindingKind(SCS1, SCS2))
4860 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4862 }
4863
4864 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4865 // bullet 3).
4867 = CompareQualificationConversions(S, SCS1, SCS2))
4868 return QualCK;
4869
4872 return ObtCK;
4873
4874 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4875 // C++ [over.ics.rank]p3b4:
4876 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4877 // which the references refer are the same type except for
4878 // top-level cv-qualifiers, and the type to which the reference
4879 // initialized by S2 refers is more cv-qualified than the type
4880 // to which the reference initialized by S1 refers.
4881 QualType T1 = SCS1.getToType(2);
4882 QualType T2 = SCS2.getToType(2);
4883 T1 = S.Context.getCanonicalType(T1);
4884 T2 = S.Context.getCanonicalType(T2);
4885 Qualifiers T1Quals, T2Quals;
4886 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4887 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4888 if (UnqualT1 == UnqualT2) {
4889 // Objective-C++ ARC: If the references refer to objects with different
4890 // lifetimes, prefer bindings that don't change lifetime.
4896 }
4897
4898 // If the type is an array type, promote the element qualifiers to the
4899 // type for comparison.
4900 if (isa<ArrayType>(T1) && T1Quals)
4901 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4902 if (isa<ArrayType>(T2) && T2Quals)
4903 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4904 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4906 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4908 }
4909 }
4910
4911 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4912 // floating-to-integral conversion if the integral conversion
4913 // is between types of the same size.
4914 // For example:
4915 // void f(float);
4916 // void f(int);
4917 // int main {
4918 // long a;
4919 // f(a);
4920 // }
4921 // Here, MSVC will call f(int) instead of generating a compile error
4922 // as clang will do in standard mode.
4923 if (S.getLangOpts().MSVCCompat &&
4926 SCS2.Second == ICK_Floating_Integral &&
4927 S.Context.getTypeSize(SCS1.getFromType()) ==
4928 S.Context.getTypeSize(SCS1.getToType(2)))
4930
4931 // Prefer a compatible vector conversion over a lax vector conversion
4932 // For example:
4933 //
4934 // typedef float __v4sf __attribute__((__vector_size__(16)));
4935 // void f(vector float);
4936 // void f(vector signed int);
4937 // int main() {
4938 // __v4sf a;
4939 // f(a);
4940 // }
4941 // Here, we'd like to choose f(vector float) and not
4942 // report an ambiguous call error
4943 if (SCS1.Second == ICK_Vector_Conversion &&
4944 SCS2.Second == ICK_Vector_Conversion) {
4945 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4946 SCS1.getFromType(), SCS1.getToType(2));
4947 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4948 SCS2.getFromType(), SCS2.getToType(2));
4949
4950 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4951 return SCS1IsCompatibleVectorConversion
4954 }
4955
4956 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4958 bool SCS1IsCompatibleSVEVectorConversion =
4959 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4960 bool SCS2IsCompatibleSVEVectorConversion =
4961 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4962
4963 if (SCS1IsCompatibleSVEVectorConversion !=
4964 SCS2IsCompatibleSVEVectorConversion)
4965 return SCS1IsCompatibleSVEVectorConversion
4968 }
4969
4970 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4972 bool SCS1IsCompatibleRVVVectorConversion =
4974 bool SCS2IsCompatibleRVVVectorConversion =
4976
4977 if (SCS1IsCompatibleRVVVectorConversion !=
4978 SCS2IsCompatibleRVVVectorConversion)
4979 return SCS1IsCompatibleRVVVectorConversion
4982 }
4984}
4985
4986/// CompareOverflowBehaviorConversions - Compares two standard conversion
4987/// sequences to determine whether they can be ranked based on their
4988/// OverflowBehaviorType's underlying type.
5004
5005/// CompareQualificationConversions - Compares two standard conversion
5006/// sequences to determine whether they can be ranked based on their
5007/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
5010 const StandardConversionSequence& SCS1,
5011 const StandardConversionSequence& SCS2) {
5012 // C++ [over.ics.rank]p3:
5013 // -- S1 and S2 differ only in their qualification conversion and
5014 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
5015 // [C++98]
5016 // [...] and the cv-qualification signature of type T1 is a proper subset
5017 // of the cv-qualification signature of type T2, and S1 is not the
5018 // deprecated string literal array-to-pointer conversion (4.2).
5019 // [C++2a]
5020 // [...] where T1 can be converted to T2 by a qualification conversion.
5021 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5022 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5024
5025 // FIXME: the example in the standard doesn't use a qualification
5026 // conversion (!)
5027 QualType T1 = SCS1.getToType(2);
5028 QualType T2 = SCS2.getToType(2);
5029 T1 = S.Context.getCanonicalType(T1);
5030 T2 = S.Context.getCanonicalType(T2);
5031 assert(!T1->isReferenceType() && !T2->isReferenceType());
5032 Qualifiers T1Quals, T2Quals;
5033 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5034 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5035
5036 // If the types are the same, we won't learn anything by unwrapping
5037 // them.
5038 if (UnqualT1 == UnqualT2)
5040
5041 // Don't ever prefer a standard conversion sequence that uses the deprecated
5042 // string literal array to pointer conversion.
5043 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5044 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5045
5046 // Objective-C++ ARC:
5047 // Prefer qualification conversions not involving a change in lifetime
5048 // to qualification conversions that do change lifetime.
5051 CanPick1 = false;
5054 CanPick2 = false;
5055
5056 bool ObjCLifetimeConversion;
5057 if (CanPick1 &&
5058 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5059 CanPick1 = false;
5060 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5061 // directions, so we can't short-cut this second check in general.
5062 if (CanPick2 &&
5063 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5064 CanPick2 = false;
5065
5066 if (CanPick1 != CanPick2)
5067 return CanPick1 ? ImplicitConversionSequence::Better
5070}
5071
5072/// CompareDerivedToBaseConversions - Compares two standard conversion
5073/// sequences to determine whether they can be ranked based on their
5074/// various kinds of derived-to-base conversions (C++
5075/// [over.ics.rank]p4b3). As part of these checks, we also look at
5076/// conversions between Objective-C interface types.
5079 const StandardConversionSequence& SCS1,
5080 const StandardConversionSequence& SCS2) {
5081 QualType FromType1 = SCS1.getFromType();
5082 QualType ToType1 = SCS1.getToType(1);
5083 QualType FromType2 = SCS2.getFromType();
5084 QualType ToType2 = SCS2.getToType(1);
5085
5086 // Adjust the types we're converting from via the array-to-pointer
5087 // conversion, if we need to.
5088 if (SCS1.First == ICK_Array_To_Pointer)
5089 FromType1 = S.Context.getArrayDecayedType(FromType1);
5090 if (SCS2.First == ICK_Array_To_Pointer)
5091 FromType2 = S.Context.getArrayDecayedType(FromType2);
5092
5093 // Canonicalize all of the types.
5094 FromType1 = S.Context.getCanonicalType(FromType1);
5095 ToType1 = S.Context.getCanonicalType(ToType1);
5096 FromType2 = S.Context.getCanonicalType(FromType2);
5097 ToType2 = S.Context.getCanonicalType(ToType2);
5098
5099 // C++ [over.ics.rank]p4b3:
5100 //
5101 // If class B is derived directly or indirectly from class A and
5102 // class C is derived directly or indirectly from B,
5103 //
5104 // Compare based on pointer conversions.
5105 if (SCS1.Second == ICK_Pointer_Conversion &&
5107 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5108 FromType1->isPointerType() && FromType2->isPointerType() &&
5109 ToType1->isPointerType() && ToType2->isPointerType()) {
5110 QualType FromPointee1 =
5112 QualType ToPointee1 =
5114 QualType FromPointee2 =
5116 QualType ToPointee2 =
5118
5119 // -- conversion of C* to B* is better than conversion of C* to A*,
5120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5125 }
5126
5127 // -- conversion of B* to A* is better than conversion of C* to A*,
5128 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5129 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5131 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5133 }
5134 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5136 const ObjCObjectPointerType *FromPtr1
5137 = FromType1->getAs<ObjCObjectPointerType>();
5138 const ObjCObjectPointerType *FromPtr2
5139 = FromType2->getAs<ObjCObjectPointerType>();
5140 const ObjCObjectPointerType *ToPtr1
5141 = ToType1->getAs<ObjCObjectPointerType>();
5142 const ObjCObjectPointerType *ToPtr2
5143 = ToType2->getAs<ObjCObjectPointerType>();
5144
5145 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5146 // Apply the same conversion ranking rules for Objective-C pointer types
5147 // that we do for C++ pointers to class types. However, we employ the
5148 // Objective-C pseudo-subtyping relationship used for assignment of
5149 // Objective-C pointer types.
5150 bool FromAssignLeft
5151 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5152 bool FromAssignRight
5153 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5154 bool ToAssignLeft
5155 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5156 bool ToAssignRight
5157 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5158
5159 // A conversion to an a non-id object pointer type or qualified 'id'
5160 // type is better than a conversion to 'id'.
5161 if (ToPtr1->isObjCIdType() &&
5162 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5164 if (ToPtr2->isObjCIdType() &&
5165 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5167
5168 // A conversion to a non-id object pointer type is better than a
5169 // conversion to a qualified 'id' type
5170 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5172 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5174
5175 // A conversion to an a non-Class object pointer type or qualified 'Class'
5176 // type is better than a conversion to 'Class'.
5177 if (ToPtr1->isObjCClassType() &&
5178 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5180 if (ToPtr2->isObjCClassType() &&
5181 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5183
5184 // A conversion to a non-Class object pointer type is better than a
5185 // conversion to a qualified 'Class' type.
5186 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5188 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5190
5191 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5192 if (S.Context.hasSameType(FromType1, FromType2) &&
5193 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5194 (ToAssignLeft != ToAssignRight)) {
5195 if (FromPtr1->isSpecialized()) {
5196 // "conversion of B<A> * to B * is better than conversion of B * to
5197 // C *.
5198 bool IsFirstSame =
5199 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5200 bool IsSecondSame =
5201 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5202 if (IsFirstSame) {
5203 if (!IsSecondSame)
5205 } else if (IsSecondSame)
5207 }
5208 return ToAssignLeft? ImplicitConversionSequence::Worse
5210 }
5211
5212 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5213 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5214 (FromAssignLeft != FromAssignRight))
5215 return FromAssignLeft? ImplicitConversionSequence::Better
5217 }
5218 }
5219
5220 // Ranking of member-pointer types.
5221 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5222 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5223 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5224 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5225 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5226 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5227 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5228 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5229 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5230 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5231 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5232 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5233 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5234 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5236 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5238 }
5239 // conversion of B::* to C::* is better than conversion of A::* to C::*
5240 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5241 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5243 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5245 }
5246 }
5247
5248 if (SCS1.Second == ICK_Derived_To_Base) {
5249 // -- conversion of C to B is better than conversion of C to A,
5250 // -- binding of an expression of type C to a reference of type
5251 // B& is better than binding an expression of type C to a
5252 // reference of type A&,
5253 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5254 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5255 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5257 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5259 }
5260
5261 // -- conversion of B to A is better than conversion of C to A.
5262 // -- binding of an expression of type B to a reference of type
5263 // A& is better than binding an expression of type C to a
5264 // reference of type A&,
5265 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5266 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5267 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5269 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5271 }
5272 }
5273
5275}
5276
5278 if (!T.getQualifiers().hasUnaligned())
5279 return T;
5280
5281 Qualifiers Q;
5282 T = Ctx.getUnqualifiedArrayType(T, Q);
5283 Q.removeUnaligned();
5284 return Ctx.getQualifiedType(T, Q);
5285}
5286
5289 QualType OrigT1, QualType OrigT2,
5290 ReferenceConversions *ConvOut) {
5291 assert(!OrigT1->isReferenceType() &&
5292 "T1 must be the pointee type of the reference type");
5293 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5294
5295 QualType T1 = Context.getCanonicalType(OrigT1);
5296 QualType T2 = Context.getCanonicalType(OrigT2);
5297 Qualifiers T1Quals, T2Quals;
5298 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5299 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5300
5301 ReferenceConversions ConvTmp;
5302 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5303 Conv = ReferenceConversions();
5304
5305 // C++2a [dcl.init.ref]p4:
5306 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5307 // reference-related to "cv2 T2" if T1 is similar to T2, or
5308 // T1 is a base class of T2.
5309 // "cv1 T1" is reference-compatible with "cv2 T2" if
5310 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5311 // "pointer to cv1 T1" via a standard conversion sequence.
5312
5313 // Check for standard conversions we can apply to pointers: derived-to-base
5314 // conversions, ObjC pointer conversions, and function pointer conversions.
5315 // (Qualification conversions are checked last.)
5316 if (UnqualT1 == UnqualT2) {
5317 // Nothing to do.
5318 } else if (isCompleteType(Loc, OrigT2) &&
5319 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5320 Conv |= ReferenceConversions::DerivedToBase;
5321 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5322 UnqualT2->isObjCObjectOrInterfaceType() &&
5323 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5324 Conv |= ReferenceConversions::ObjC;
5325 else if (UnqualT2->isFunctionType() &&
5326 IsFunctionConversion(UnqualT2, UnqualT1)) {
5327 Conv |= ReferenceConversions::Function;
5328 // No need to check qualifiers; function types don't have them.
5329 return Ref_Compatible;
5330 }
5331 bool ConvertedReferent = Conv != 0;
5332
5333 // We can have a qualification conversion. Compute whether the types are
5334 // similar at the same time.
5335 bool PreviousToQualsIncludeConst = true;
5336 bool TopLevel = true;
5337 do {
5338 if (T1 == T2)
5339 break;
5340
5341 // We will need a qualification conversion.
5342 Conv |= ReferenceConversions::Qualification;
5343
5344 // Track whether we performed a qualification conversion anywhere other
5345 // than the top level. This matters for ranking reference bindings in
5346 // overload resolution.
5347 if (!TopLevel)
5348 Conv |= ReferenceConversions::NestedQualification;
5349
5350 // MS compiler ignores __unaligned qualifier for references; do the same.
5351 T1 = withoutUnaligned(Context, T1);
5352 T2 = withoutUnaligned(Context, T2);
5353
5354 // If we find a qualifier mismatch, the types are not reference-compatible,
5355 // but are still be reference-related if they're similar.
5356 bool ObjCLifetimeConversion = false;
5357 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5358 PreviousToQualsIncludeConst,
5359 ObjCLifetimeConversion, getASTContext()))
5360 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5361 ? Ref_Related
5363
5364 // FIXME: Should we track this for any level other than the first?
5365 if (ObjCLifetimeConversion)
5366 Conv |= ReferenceConversions::ObjCLifetime;
5367
5368 TopLevel = false;
5369 } while (Context.UnwrapSimilarTypes(T1, T2));
5370
5371 // At this point, if the types are reference-related, we must either have the
5372 // same inner type (ignoring qualifiers), or must have already worked out how
5373 // to convert the referent.
5374 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5377}
5378
5379/// Look for a user-defined conversion to a value reference-compatible
5380/// with DeclType. Return true if something definite is found.
5381static bool
5383 QualType DeclType, SourceLocation DeclLoc,
5384 Expr *Init, QualType T2, bool AllowRvalues,
5385 bool AllowExplicit) {
5386 assert(T2->isRecordType() && "Can only find conversions of record types.");
5387 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5388 OverloadCandidateSet CandidateSet(
5390 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5391 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5392 NamedDecl *D = *I;
5394 if (isa<UsingShadowDecl>(D))
5395 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5396
5397 FunctionTemplateDecl *ConvTemplate
5398 = dyn_cast<FunctionTemplateDecl>(D);
5399 CXXConversionDecl *Conv;
5400 if (ConvTemplate)
5401 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5402 else
5403 Conv = cast<CXXConversionDecl>(D);
5404
5405 if (AllowRvalues) {
5406 // If we are initializing an rvalue reference, don't permit conversion
5407 // functions that return lvalues.
5408 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5409 const ReferenceType *RefType
5411 if (RefType && !RefType->getPointeeType()->isFunctionType())
5412 continue;
5413 }
5414
5415 if (!ConvTemplate &&
5417 DeclLoc,
5418 Conv->getConversionType()
5423 continue;
5424 } else {
5425 // If the conversion function doesn't return a reference type,
5426 // it can't be considered for this conversion. An rvalue reference
5427 // is only acceptable if its referencee is a function type.
5428
5429 const ReferenceType *RefType =
5431 if (!RefType ||
5432 (!RefType->isLValueReferenceType() &&
5433 !RefType->getPointeeType()->isFunctionType()))
5434 continue;
5435 }
5436
5437 if (ConvTemplate)
5439 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5440 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5441 else
5443 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5444 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5445 }
5446
5447 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5448
5450 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5451 case OR_Success:
5452
5453 assert(Best->HasFinalConversion);
5454
5455 // C++ [over.ics.ref]p1:
5456 //
5457 // [...] If the parameter binds directly to the result of
5458 // applying a conversion function to the argument
5459 // expression, the implicit conversion sequence is a
5460 // user-defined conversion sequence (13.3.3.1.2), with the
5461 // second standard conversion sequence either an identity
5462 // conversion or, if the conversion function returns an
5463 // entity of a type that is a derived class of the parameter
5464 // type, a derived-to-base Conversion.
5465 if (!Best->FinalConversion.DirectBinding)
5466 return false;
5467
5468 ICS.setUserDefined();
5469 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5470 ICS.UserDefined.After = Best->FinalConversion;
5471 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5472 ICS.UserDefined.ConversionFunction = Best->Function;
5473 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5474 ICS.UserDefined.EllipsisConversion = false;
5475 assert(ICS.UserDefined.After.ReferenceBinding &&
5477 "Expected a direct reference binding!");
5478 return true;
5479
5480 case OR_Ambiguous:
5481 ICS.setAmbiguous();
5482 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5483 Cand != CandidateSet.end(); ++Cand)
5484 if (Cand->Best)
5485 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5486 return true;
5487
5489 case OR_Deleted:
5490 // There was no suitable conversion, or we found a deleted
5491 // conversion; continue with other checks.
5492 return false;
5493 }
5494
5495 llvm_unreachable("Invalid OverloadResult!");
5496}
5497
5498/// Compute an implicit conversion sequence for reference
5499/// initialization.
5500static ImplicitConversionSequence
5502 SourceLocation DeclLoc,
5503 bool SuppressUserConversions,
5504 bool AllowExplicit) {
5505 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5506
5507 // Most paths end in a failed conversion.
5510
5511 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5512 QualType T2 = Init->getType();
5513
5514 // If the initializer is the address of an overloaded function, try
5515 // to resolve the overloaded function. If all goes well, T2 is the
5516 // type of the resulting function.
5517 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5520 false, Found))
5521 T2 = Fn->getType();
5522 }
5523
5524 // Compute some basic properties of the types and the initializer.
5525 bool isRValRef = DeclType->isRValueReferenceType();
5526 Expr::Classification InitCategory = Init->Classify(S.Context);
5527
5529 Sema::ReferenceCompareResult RefRelationship =
5530 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5531
5532 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5533 ICS.setStandard();
5535 // FIXME: A reference binding can be a function conversion too. We should
5536 // consider that when ordering reference-to-function bindings.
5537 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5539 : (RefConv & Sema::ReferenceConversions::ObjC)
5541 : ICK_Identity;
5543 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5544 // a reference binding that performs a non-top-level qualification
5545 // conversion as a qualification conversion, not as an identity conversion.
5546 ICS.Standard.Third = (RefConv &
5547 Sema::ReferenceConversions::NestedQualification)
5549 : ICK_Identity;
5550 ICS.Standard.setFromType(T2);
5551 ICS.Standard.setToType(0, T2);
5552 ICS.Standard.setToType(1, T1);
5553 ICS.Standard.setToType(2, T1);
5554 ICS.Standard.ReferenceBinding = true;
5555 ICS.Standard.DirectBinding = BindsDirectly;
5556 ICS.Standard.IsLvalueReference = !isRValRef;
5558 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5561 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5562 ICS.Standard.FromBracedInitList = false;
5563 ICS.Standard.CopyConstructor = nullptr;
5565 };
5566
5567 // C++0x [dcl.init.ref]p5:
5568 // A reference to type "cv1 T1" is initialized by an expression
5569 // of type "cv2 T2" as follows:
5570
5571 // -- If reference is an lvalue reference and the initializer expression
5572 if (!isRValRef) {
5573 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5574 // reference-compatible with "cv2 T2," or
5575 //
5576 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5577 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5578 // C++ [over.ics.ref]p1:
5579 // When a parameter of reference type binds directly (8.5.3)
5580 // to an argument expression, the implicit conversion sequence
5581 // is the identity conversion, unless the argument expression
5582 // has a type that is a derived class of the parameter type,
5583 // in which case the implicit conversion sequence is a
5584 // derived-to-base Conversion (13.3.3.1).
5585 SetAsReferenceBinding(/*BindsDirectly=*/true);
5586
5587 // Nothing more to do: the inaccessibility/ambiguity check for
5588 // derived-to-base conversions is suppressed when we're
5589 // computing the implicit conversion sequence (C++
5590 // [over.best.ics]p2).
5591 return ICS;
5592 }
5593
5594 // -- has a class type (i.e., T2 is a class type), where T1 is
5595 // not reference-related to T2, and can be implicitly
5596 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5597 // is reference-compatible with "cv3 T3" 92) (this
5598 // conversion is selected by enumerating the applicable
5599 // conversion functions (13.3.1.6) and choosing the best
5600 // one through overload resolution (13.3)),
5601 if (!SuppressUserConversions && T2->isRecordType() &&
5602 S.isCompleteType(DeclLoc, T2) &&
5603 RefRelationship == Sema::Ref_Incompatible) {
5604 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5605 Init, T2, /*AllowRvalues=*/false,
5606 AllowExplicit))
5607 return ICS;
5608 }
5609 }
5610
5611 // -- Otherwise, the reference shall be an lvalue reference to a
5612 // non-volatile const type (i.e., cv1 shall be const), or the reference
5613 // shall be an rvalue reference.
5614 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5615 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5617 return ICS;
5618 }
5619
5620 // -- If the initializer expression
5621 //
5622 // -- is an xvalue, class prvalue, array prvalue or function
5623 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5624 if (RefRelationship == Sema::Ref_Compatible &&
5625 (InitCategory.isXValue() ||
5626 (InitCategory.isPRValue() &&
5627 (T2->isRecordType() || T2->isArrayType())) ||
5628 (InitCategory.isLValue() && T2->isFunctionType()))) {
5629 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5630 // binding unless we're binding to a class prvalue.
5631 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5632 // allow the use of rvalue references in C++98/03 for the benefit of
5633 // standard library implementors; therefore, we need the xvalue check here.
5634 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5635 !(InitCategory.isPRValue() || T2->isRecordType()));
5636 return ICS;
5637 }
5638
5639 // -- has a class type (i.e., T2 is a class type), where T1 is not
5640 // reference-related to T2, and can be implicitly converted to
5641 // an xvalue, class prvalue, or function lvalue of type
5642 // "cv3 T3", where "cv1 T1" is reference-compatible with
5643 // "cv3 T3",
5644 //
5645 // then the reference is bound to the value of the initializer
5646 // expression in the first case and to the result of the conversion
5647 // in the second case (or, in either case, to an appropriate base
5648 // class subobject).
5649 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5650 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5651 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5652 Init, T2, /*AllowRvalues=*/true,
5653 AllowExplicit)) {
5654 // In the second case, if the reference is an rvalue reference
5655 // and the second standard conversion sequence of the
5656 // user-defined conversion sequence includes an lvalue-to-rvalue
5657 // conversion, the program is ill-formed.
5658 if (ICS.isUserDefined() && isRValRef &&
5661
5662 return ICS;
5663 }
5664
5665 // A temporary of function type cannot be created; don't even try.
5666 if (T1->isFunctionType())
5667 return ICS;
5668
5669 // -- Otherwise, a temporary of type "cv1 T1" is created and
5670 // initialized from the initializer expression using the
5671 // rules for a non-reference copy initialization (8.5). The
5672 // reference is then bound to the temporary. If T1 is
5673 // reference-related to T2, cv1 must be the same
5674 // cv-qualification as, or greater cv-qualification than,
5675 // cv2; otherwise, the program is ill-formed.
5676 if (RefRelationship == Sema::Ref_Related) {
5677 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5678 // we would be reference-compatible or reference-compatible with
5679 // added qualification. But that wasn't the case, so the reference
5680 // initialization fails.
5681 //
5682 // Note that we only want to check address spaces and cvr-qualifiers here.
5683 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5684 Qualifiers T1Quals = T1.getQualifiers();
5685 Qualifiers T2Quals = T2.getQualifiers();
5686 T1Quals.removeObjCGCAttr();
5687 T1Quals.removeObjCLifetime();
5688 T2Quals.removeObjCGCAttr();
5689 T2Quals.removeObjCLifetime();
5690 // MS compiler ignores __unaligned qualifier for references; do the same.
5691 T1Quals.removeUnaligned();
5692 T2Quals.removeUnaligned();
5693 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5694 return ICS;
5695 }
5696
5697 // If at least one of the types is a class type, the types are not
5698 // related, and we aren't allowed any user conversions, the
5699 // reference binding fails. This case is important for breaking
5700 // recursion, since TryImplicitConversion below will attempt to
5701 // create a temporary through the use of a copy constructor.
5702 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5703 (T1->isRecordType() || T2->isRecordType()))
5704 return ICS;
5705
5706 // If T1 is reference-related to T2 and the reference is an rvalue
5707 // reference, the initializer expression shall not be an lvalue.
5708 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5709 Init->Classify(S.Context).isLValue()) {
5711 return ICS;
5712 }
5713
5714 // C++ [over.ics.ref]p2:
5715 // When a parameter of reference type is not bound directly to
5716 // an argument expression, the conversion sequence is the one
5717 // required to convert the argument expression to the
5718 // underlying type of the reference according to
5719 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5720 // to copy-initializing a temporary of the underlying type with
5721 // the argument expression. Any difference in top-level
5722 // cv-qualification is subsumed by the initialization itself
5723 // and does not constitute a conversion.
5724 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5725 AllowedExplicit::None,
5726 /*InOverloadResolution=*/false,
5727 /*CStyle=*/false,
5728 /*AllowObjCWritebackConversion=*/false,
5729 /*AllowObjCConversionOnExplicit=*/false);
5730
5731 // Of course, that's still a reference binding.
5732 if (ICS.isStandard()) {
5733 ICS.Standard.ReferenceBinding = true;
5734 ICS.Standard.IsLvalueReference = !isRValRef;
5735 ICS.Standard.BindsToFunctionLvalue = false;
5736 ICS.Standard.BindsToRvalue = true;
5739 } else if (ICS.isUserDefined()) {
5740 const ReferenceType *LValRefType =
5743
5744 // C++ [over.ics.ref]p3:
5745 // Except for an implicit object parameter, for which see 13.3.1, a
5746 // standard conversion sequence cannot be formed if it requires [...]
5747 // binding an rvalue reference to an lvalue other than a function
5748 // lvalue.
5749 // Note that the function case is not possible here.
5750 if (isRValRef && LValRefType) {
5752 return ICS;
5753 }
5754
5756 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5758 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5762 }
5763
5764 return ICS;
5765}
5766
5767static ImplicitConversionSequence
5768TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5769 bool SuppressUserConversions,
5770 bool InOverloadResolution,
5771 bool AllowObjCWritebackConversion,
5772 bool AllowExplicit = false);
5773
5774/// TryListConversion - Try to copy-initialize a value of type ToType from the
5775/// initializer list From.
5776static ImplicitConversionSequence
5778 bool SuppressUserConversions,
5779 bool InOverloadResolution,
5780 bool AllowObjCWritebackConversion) {
5781 // C++11 [over.ics.list]p1:
5782 // When an argument is an initializer list, it is not an expression and
5783 // special rules apply for converting it to a parameter type.
5784
5786 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5787
5788 // We need a complete type for what follows. With one C++20 exception,
5789 // incomplete types can never be initialized from init lists.
5790 QualType InitTy = ToType;
5791 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5792 if (AT && S.getLangOpts().CPlusPlus20)
5793 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5794 // C++20 allows list initialization of an incomplete array type.
5795 InitTy = IAT->getElementType();
5796 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5797 return Result;
5798
5799 // C++20 [over.ics.list]/2:
5800 // If the initializer list is a designated-initializer-list, a conversion
5801 // is only possible if the parameter has an aggregate type
5802 //
5803 // FIXME: The exception for reference initialization here is not part of the
5804 // language rules, but follow other compilers in adding it as a tentative DR
5805 // resolution.
5806 bool IsDesignatedInit = From->hasDesignatedInit();
5807 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5808 IsDesignatedInit)
5809 return Result;
5810
5811 // Per DR1467 and DR2137:
5812 // If the parameter type is an aggregate class X and the initializer list
5813 // has a single element of type cv U, where U is X or a class derived from
5814 // X, the implicit conversion sequence is the one required to convert the
5815 // element to the parameter type.
5816 //
5817 // Otherwise, if the parameter type is a character array [... ]
5818 // and the initializer list has a single element that is an
5819 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5820 // implicit conversion sequence is the identity conversion.
5821 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5822 if (ToType->isRecordType() && ToType->isAggregateType()) {
5823 QualType InitType = From->getInit(0)->getType();
5824 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5825 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5826 return TryCopyInitialization(S, From->getInit(0), ToType,
5827 SuppressUserConversions,
5828 InOverloadResolution,
5829 AllowObjCWritebackConversion);
5830 }
5831
5832 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5833 InitializedEntity Entity =
5835 /*Consumed=*/false);
5836 if (S.CanPerformCopyInitialization(Entity, From)) {
5837 Result.setStandard();
5838 Result.Standard.setAsIdentityConversion();
5839 Result.Standard.setFromType(ToType);
5840 Result.Standard.setAllToTypes(ToType);
5841 return Result;
5842 }
5843 }
5844 }
5845
5846 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5847 // C++11 [over.ics.list]p2:
5848 // If the parameter type is std::initializer_list<X> or "array of X" and
5849 // all the elements can be implicitly converted to X, the implicit
5850 // conversion sequence is the worst conversion necessary to convert an
5851 // element of the list to X.
5852 //
5853 // C++14 [over.ics.list]p3:
5854 // Otherwise, if the parameter type is "array of N X", if the initializer
5855 // list has exactly N elements or if it has fewer than N elements and X is
5856 // default-constructible, and if all the elements of the initializer list
5857 // can be implicitly converted to X, the implicit conversion sequence is
5858 // the worst conversion necessary to convert an element of the list to X.
5859 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5860 unsigned e = From->getNumInits();
5863 QualType());
5864 QualType ContTy = ToType;
5865 bool IsUnbounded = false;
5866 if (AT) {
5867 InitTy = AT->getElementType();
5868 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5869 if (CT->getSize().ult(e)) {
5870 // Too many inits, fatally bad
5872 ToType);
5873 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5874 return Result;
5875 }
5876 if (CT->getSize().ugt(e)) {
5877 // Need an init from empty {}, is there one?
5878 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5879 From->getEndLoc(), /*isExplicit=*/false);
5880 EmptyList.setType(S.Context.VoidTy);
5881 DfltElt = TryListConversion(
5882 S, &EmptyList, InitTy, SuppressUserConversions,
5883 InOverloadResolution, AllowObjCWritebackConversion);
5884 if (DfltElt.isBad()) {
5885 // No {} init, fatally bad
5887 ToType);
5888 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5889 return Result;
5890 }
5891 }
5892 } else {
5893 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5894 IsUnbounded = true;
5895 if (!e) {
5896 // Cannot convert to zero-sized.
5898 ToType);
5899 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5900 return Result;
5901 }
5902 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5903 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5905 }
5906 }
5907
5908 Result.setStandard();
5909 Result.Standard.setAsIdentityConversion();
5910 Result.Standard.setFromType(InitTy);
5911 Result.Standard.setAllToTypes(InitTy);
5912 for (unsigned i = 0; i < e; ++i) {
5913 Expr *Init = From->getInit(i);
5915 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5916 AllowObjCWritebackConversion);
5917
5918 // Keep the worse conversion seen so far.
5919 // FIXME: Sequences are not totally ordered, so 'worse' can be
5920 // ambiguous. CWG has been informed.
5922 Result) ==
5924 Result = ICS;
5925 // Bail as soon as we find something unconvertible.
5926 if (Result.isBad()) {
5927 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5928 return Result;
5929 }
5930 }
5931 }
5932
5933 // If we needed any implicit {} initialization, compare that now.
5934 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5935 // has been informed that this might not be the best thing.
5936 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5937 S, From->getEndLoc(), DfltElt, Result) ==
5939 Result = DfltElt;
5940 // Record the type being initialized so that we may compare sequences
5941 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5942 return Result;
5943 }
5944
5945 // C++14 [over.ics.list]p4:
5946 // C++11 [over.ics.list]p3:
5947 // Otherwise, if the parameter is a non-aggregate class X and overload
5948 // resolution chooses a single best constructor [...] the implicit
5949 // conversion sequence is a user-defined conversion sequence. If multiple
5950 // constructors are viable but none is better than the others, the
5951 // implicit conversion sequence is a user-defined conversion sequence.
5952 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5953 // This function can deal with initializer lists.
5954 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5955 AllowedExplicit::None,
5956 InOverloadResolution, /*CStyle=*/false,
5957 AllowObjCWritebackConversion,
5958 /*AllowObjCConversionOnExplicit=*/false);
5959 }
5960
5961 // C++14 [over.ics.list]p5:
5962 // C++11 [over.ics.list]p4:
5963 // Otherwise, if the parameter has an aggregate type which can be
5964 // initialized from the initializer list [...] the implicit conversion
5965 // sequence is a user-defined conversion sequence.
5966 if (ToType->isAggregateType()) {
5967 // Type is an aggregate, argument is an init list. At this point it comes
5968 // down to checking whether the initialization works.
5969 // FIXME: Find out whether this parameter is consumed or not.
5970 InitializedEntity Entity =
5972 /*Consumed=*/false);
5974 From)) {
5975 Result.setUserDefined();
5976 Result.UserDefined.Before.setAsIdentityConversion();
5977 // Initializer lists don't have a type.
5978 Result.UserDefined.Before.setFromType(QualType());
5979 Result.UserDefined.Before.setAllToTypes(QualType());
5980
5981 Result.UserDefined.After.setAsIdentityConversion();
5982 Result.UserDefined.After.setFromType(ToType);
5983 Result.UserDefined.After.setAllToTypes(ToType);
5984 Result.UserDefined.ConversionFunction = nullptr;
5985 }
5986 return Result;
5987 }
5988
5989 // C++14 [over.ics.list]p6:
5990 // C++11 [over.ics.list]p5:
5991 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5992 if (ToType->isReferenceType()) {
5993 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5994 // mention initializer lists in any way. So we go by what list-
5995 // initialization would do and try to extrapolate from that.
5996
5997 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5998
5999 // If the initializer list has a single element that is reference-related
6000 // to the parameter type, we initialize the reference from that.
6001 if (From->getNumInits() == 1 && !IsDesignatedInit) {
6002 Expr *Init = From->getInit(0);
6003
6004 QualType T2 = Init->getType();
6005
6006 // If the initializer is the address of an overloaded function, try
6007 // to resolve the overloaded function. If all goes well, T2 is the
6008 // type of the resulting function.
6009 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
6012 Init, ToType, false, Found))
6013 T2 = Fn->getType();
6014 }
6015
6016 // Compute some basic properties of the types and the initializer.
6017 Sema::ReferenceCompareResult RefRelationship =
6018 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
6019
6020 if (RefRelationship >= Sema::Ref_Related) {
6021 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
6022 SuppressUserConversions,
6023 /*AllowExplicit=*/false);
6024 }
6025 }
6026
6027 // Otherwise, we bind the reference to a temporary created from the
6028 // initializer list.
6029 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6030 InOverloadResolution,
6031 AllowObjCWritebackConversion);
6032 if (Result.isFailure())
6033 return Result;
6034 assert(!Result.isEllipsis() &&
6035 "Sub-initialization cannot result in ellipsis conversion.");
6036
6037 // Can we even bind to a temporary?
6038 if (ToType->isRValueReferenceType() ||
6039 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6040 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6041 Result.UserDefined.After;
6042 SCS.ReferenceBinding = true;
6044 SCS.BindsToRvalue = true;
6045 SCS.BindsToFunctionLvalue = false;
6048 SCS.FromBracedInitList = false;
6049
6050 } else
6052 From, ToType);
6053 return Result;
6054 }
6055
6056 // C++14 [over.ics.list]p7:
6057 // C++11 [over.ics.list]p6:
6058 // Otherwise, if the parameter type is not a class:
6059 if (!ToType->isRecordType()) {
6060 // - if the initializer list has one element that is not itself an
6061 // initializer list, the implicit conversion sequence is the one
6062 // required to convert the element to the parameter type.
6063 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6064 // single integer.
6065 unsigned NumInits = From->getNumInits();
6066 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6067 !isa<EmbedExpr>(From->getInit(0))) {
6069 S, From->getInit(0), ToType, SuppressUserConversions,
6070 InOverloadResolution, AllowObjCWritebackConversion);
6071 if (Result.isStandard())
6072 Result.Standard.FromBracedInitList = true;
6073 }
6074 // - if the initializer list has no elements, the implicit conversion
6075 // sequence is the identity conversion.
6076 else if (NumInits == 0) {
6077 Result.setStandard();
6078 Result.Standard.setAsIdentityConversion();
6079 Result.Standard.setFromType(ToType);
6080 Result.Standard.setAllToTypes(ToType);
6081 }
6082 return Result;
6083 }
6084
6085 // C++14 [over.ics.list]p8:
6086 // C++11 [over.ics.list]p7:
6087 // In all cases other than those enumerated above, no conversion is possible
6088 return Result;
6089}
6090
6091/// TryCopyInitialization - Try to copy-initialize a value of type
6092/// ToType from the expression From. Return the implicit conversion
6093/// sequence required to pass this argument, which may be a bad
6094/// conversion sequence (meaning that the argument cannot be passed to
6095/// a parameter of this type). If @p SuppressUserConversions, then we
6096/// do not permit any user-defined conversion sequences.
6097static ImplicitConversionSequence
6099 bool SuppressUserConversions,
6100 bool InOverloadResolution,
6101 bool AllowObjCWritebackConversion,
6102 bool AllowExplicit) {
6103 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6104 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6105 InOverloadResolution,AllowObjCWritebackConversion);
6106
6107 if (ToType->isReferenceType())
6108 return TryReferenceInit(S, From, ToType,
6109 /*FIXME:*/ From->getBeginLoc(),
6110 SuppressUserConversions, AllowExplicit);
6111
6112 return TryImplicitConversion(S, From, ToType,
6113 SuppressUserConversions,
6114 AllowedExplicit::None,
6115 InOverloadResolution,
6116 /*CStyle=*/false,
6117 AllowObjCWritebackConversion,
6118 /*AllowObjCConversionOnExplicit=*/false);
6119}
6120
6121static bool TryCopyInitialization(const CanQualType FromQTy,
6122 const CanQualType ToQTy,
6123 Sema &S,
6124 SourceLocation Loc,
6125 ExprValueKind FromVK) {
6126 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6128 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6129
6130 return !ICS.isBad();
6131}
6132
6133/// TryObjectArgumentInitialization - Try to initialize the object
6134/// parameter of the given member function (@c Method) from the
6135/// expression @p From.
6137 Sema &S, SourceLocation Loc, QualType FromType,
6138 Expr::Classification FromClassification, CXXMethodDecl *Method,
6139 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6140 QualType ExplicitParameterType = QualType(),
6141 bool SuppressUserConversion = false) {
6142
6143 // We need to have an object of class type.
6144 if (const auto *PT = FromType->getAs<PointerType>()) {
6145 FromType = PT->getPointeeType();
6146
6147 // When we had a pointer, it's implicitly dereferenced, so we
6148 // better have an lvalue.
6149 assert(FromClassification.isLValue());
6150 }
6151
6152 auto ValueKindFromClassification = [](Expr::Classification C) {
6153 if (C.isPRValue())
6154 return clang::VK_PRValue;
6155 if (C.isXValue())
6156 return VK_XValue;
6157 return clang::VK_LValue;
6158 };
6159
6160 if (Method->isExplicitObjectMemberFunction()) {
6161 if (ExplicitParameterType.isNull())
6162 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6163 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6164 ValueKindFromClassification(FromClassification));
6166 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6167 /*InOverloadResolution=*/true, false);
6168 if (ICS.isBad())
6169 ICS.Bad.FromExpr = nullptr;
6170 return ICS;
6171 }
6172
6173 assert(FromType->isRecordType());
6174
6175 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6176 // C++98 [class.dtor]p2:
6177 // A destructor can be invoked for a const, volatile or const volatile
6178 // object.
6179 // C++98 [over.match.funcs]p4:
6180 // For static member functions, the implicit object parameter is considered
6181 // to match any object (since if the function is selected, the object is
6182 // discarded).
6183 Qualifiers Quals = Method->getMethodQualifiers();
6184 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6185 Quals.addConst();
6186 Quals.addVolatile();
6187 }
6188
6189 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6190
6191 // Set up the conversion sequence as a "bad" conversion, to allow us
6192 // to exit early.
6194
6195 // C++0x [over.match.funcs]p4:
6196 // For non-static member functions, the type of the implicit object
6197 // parameter is
6198 //
6199 // - "lvalue reference to cv X" for functions declared without a
6200 // ref-qualifier or with the & ref-qualifier
6201 // - "rvalue reference to cv X" for functions declared with the &&
6202 // ref-qualifier
6203 //
6204 // where X is the class of which the function is a member and cv is the
6205 // cv-qualification on the member function declaration.
6206 //
6207 // However, when finding an implicit conversion sequence for the argument, we
6208 // are not allowed to perform user-defined conversions
6209 // (C++ [over.match.funcs]p5). We perform a simplified version of
6210 // reference binding here, that allows class rvalues to bind to
6211 // non-constant references.
6212
6213 // First check the qualifiers.
6214 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6215 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6216 if (ImplicitParamType.getCVRQualifiers() !=
6217 FromTypeCanon.getLocalCVRQualifiers() &&
6218 !ImplicitParamType.isAtLeastAsQualifiedAs(
6219 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6221 FromType, ImplicitParamType);
6222 return ICS;
6223 }
6224
6225 if (FromTypeCanon.hasAddressSpace()) {
6226 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6227 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6228 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6229 S.getASTContext())) {
6231 FromType, ImplicitParamType);
6232 return ICS;
6233 }
6234 }
6235
6236 // Check that we have either the same type or a derived type. It
6237 // affects the conversion rank.
6238 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6239 ImplicitConversionKind SecondKind;
6240 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6241 SecondKind = ICK_Identity;
6242 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6243 SecondKind = ICK_Derived_To_Base;
6244 } else if (!Method->isExplicitObjectMemberFunction()) {
6246 FromType, ImplicitParamType);
6247 return ICS;
6248 }
6249
6250 // Check the ref-qualifier.
6251 switch (Method->getRefQualifier()) {
6252 case RQ_None:
6253 // Do nothing; we don't care about lvalueness or rvalueness.
6254 break;
6255
6256 case RQ_LValue:
6257 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6258 // non-const lvalue reference cannot bind to an rvalue
6260 ImplicitParamType);
6261 return ICS;
6262 }
6263 break;
6264
6265 case RQ_RValue:
6266 if (!FromClassification.isRValue()) {
6267 // rvalue reference cannot bind to an lvalue
6269 ImplicitParamType);
6270 return ICS;
6271 }
6272 break;
6273 }
6274
6275 // Success. Mark this as a reference binding.
6276 ICS.setStandard();
6278 ICS.Standard.Second = SecondKind;
6279 ICS.Standard.setFromType(FromType);
6280 ICS.Standard.setAllToTypes(ImplicitParamType);
6281 ICS.Standard.ReferenceBinding = true;
6282 ICS.Standard.DirectBinding = true;
6283 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6284 ICS.Standard.BindsToFunctionLvalue = false;
6285 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6286 ICS.Standard.FromBracedInitList = false;
6288 = (Method->getRefQualifier() == RQ_None);
6289 return ICS;
6290}
6291
6292/// PerformObjectArgumentInitialization - Perform initialization of
6293/// the implicit object parameter for the given Method with the given
6294/// expression.
6296 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6298 QualType FromRecordType, DestType;
6299 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6300
6301 if (getLangOpts().HLSL &&
6304 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6305 /*BasePath=*/nullptr, VK_PRValue,
6307 }
6308
6309 Expr::Classification FromClassification;
6310 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6311 FromRecordType = PT->getPointeeType();
6312 DestType = Method->getThisType();
6313 FromClassification = Expr::Classification::makeSimpleLValue();
6314 } else {
6315 FromRecordType = From->getType();
6316 DestType = ImplicitParamRecordType;
6317 FromClassification = From->Classify(Context);
6318
6319 // CWG2813 [expr.call]p6:
6320 // If the function is an implicit object member function, the object
6321 // expression of the class member access shall be a glvalue [...]
6322 if (From->isPRValue()) {
6323 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6324 Method->getRefQualifier() !=
6326 }
6327 }
6328
6329 // Note that we always use the true parent context when performing
6330 // the actual argument initialization.
6332 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6333 Method->getParent());
6334 if (ICS.isBad()) {
6335 switch (ICS.Bad.Kind) {
6337 Qualifiers FromQs = FromRecordType.getQualifiers();
6338 Qualifiers ToQs = DestType.getQualifiers();
6339 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6340 if (CVR) {
6341 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6342 << Method->getDeclName() << FromRecordType << (CVR - 1)
6343 << From->getSourceRange();
6344 Diag(Method->getLocation(), diag::note_previous_decl)
6345 << Method->getDeclName();
6346 return ExprError();
6347 }
6348 break;
6349 }
6350
6353 bool IsRValueQualified =
6354 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6355 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6356 << Method->getDeclName() << FromClassification.isRValue()
6357 << IsRValueQualified;
6358 Diag(Method->getLocation(), diag::note_previous_decl)
6359 << Method->getDeclName();
6360 return ExprError();
6361 }
6362
6365 break;
6366
6369 llvm_unreachable("Lists are not objects");
6370 }
6371
6372 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6373 << ImplicitParamRecordType << FromRecordType
6374 << From->getSourceRange();
6375 }
6376
6377 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6378 ExprResult FromRes =
6379 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6380 if (FromRes.isInvalid())
6381 return ExprError();
6382 From = FromRes.get();
6383 }
6384
6385 if (!Context.hasSameType(From->getType(), DestType)) {
6386 CastKind CK;
6387 QualType PteeTy = DestType->getPointeeType();
6388 LangAS DestAS =
6389 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6390 if (FromRecordType.getAddressSpace() != DestAS)
6391 CK = CK_AddressSpaceConversion;
6392 else
6393 CK = CK_NoOp;
6394 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6395 }
6396 return From;
6397}
6398
6399/// TryContextuallyConvertToBool - Attempt to contextually convert the
6400/// expression From to bool (C++0x [conv]p3).
6403 // C++ [dcl.init]/17.8:
6404 // - Otherwise, if the initialization is direct-initialization, the source
6405 // type is std::nullptr_t, and the destination type is bool, the initial
6406 // value of the object being initialized is false.
6407 if (From->getType()->isNullPtrType())
6409 S.Context.BoolTy,
6410 From->isGLValue());
6411
6412 // All other direct-initialization of bool is equivalent to an implicit
6413 // conversion to bool in which explicit conversions are permitted.
6414 return TryImplicitConversion(S, From, S.Context.BoolTy,
6415 /*SuppressUserConversions=*/false,
6416 AllowedExplicit::Conversions,
6417 /*InOverloadResolution=*/false,
6418 /*CStyle=*/false,
6419 /*AllowObjCWritebackConversion=*/false,
6420 /*AllowObjCConversionOnExplicit=*/false);
6421}
6422
6424 if (checkPlaceholderForOverload(*this, From))
6425 return ExprError();
6426 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6427 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6428
6430 if (!ICS.isBad())
6431 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6434 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6435 << From->getType() << From->getSourceRange();
6436 return ExprError();
6437}
6438
6439/// Check that the specified conversion is permitted in a converted constant
6440/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6441/// is acceptable.
6444 // Since we know that the target type is an integral or unscoped enumeration
6445 // type, most conversion kinds are impossible. All possible First and Third
6446 // conversions are fine.
6447 switch (SCS.Second) {
6448 case ICK_Identity:
6450 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6452 return true;
6453
6455 // Conversion from an integral or unscoped enumeration type to bool is
6456 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6457 // conversion, so we allow it in a converted constant expression.
6458 //
6459 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6460 // a lot of popular code. We should at least add a warning for this
6461 // (non-conforming) extension.
6463 SCS.getToType(2)->isBooleanType();
6464
6466 case ICK_Pointer_Member:
6467 // C++1z: null pointer conversions and null member pointer conversions are
6468 // only permitted if the source type is std::nullptr_t.
6469 return SCS.getFromType()->isNullPtrType();
6470
6483 case ICK_Vector_Splat:
6484 case ICK_Complex_Real:
6494 return false;
6495
6500 llvm_unreachable("found a first conversion kind in Second");
6501
6503 case ICK_Qualification:
6504 llvm_unreachable("found a third conversion kind in Second");
6505
6507 break;
6508 }
6509
6510 llvm_unreachable("unknown conversion kind");
6511}
6512
6513/// BuildConvertedConstantExpression - Check that the expression From is a
6514/// converted constant expression of type T, perform the conversion but
6515/// does not evaluate the expression
6517 QualType T, CCEKind CCE,
6518 NamedDecl *Dest,
6519 APValue &PreNarrowingValue) {
6520 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6522 CCE == CCEKind::PackIndex);
6523 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6524 "converted constant expression outside C++11 or TTP matching");
6525
6526 if (checkPlaceholderForOverload(S, From))
6527 return ExprError();
6528
6529 if (From->containsErrors()) {
6530 if (S.Context.hasSameType(From->getType(), T))
6531 return From;
6532
6533 // The expression already has errors, so the correct cast kind can't be
6534 // determined. Use RecoveryExpr to keep the expected type T and mark the
6535 // result as invalid, preventing further cascading errors.
6536 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6537 T);
6538 }
6539
6540 // C++1z [expr.const]p3:
6541 // A converted constant expression of type T is an expression,
6542 // implicitly converted to type T, where the converted
6543 // expression is a constant expression and the implicit conversion
6544 // sequence contains only [... list of conversions ...].
6546 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6548 : TryCopyInitialization(S, From, T,
6549 /*SuppressUserConversions=*/false,
6550 /*InOverloadResolution=*/false,
6551 /*AllowObjCWritebackConversion=*/false,
6552 /*AllowExplicit=*/false);
6553 StandardConversionSequence *SCS = nullptr;
6554 switch (ICS.getKind()) {
6556 SCS = &ICS.Standard;
6557 break;
6559 if (T->isRecordType())
6560 SCS = &ICS.UserDefined.Before;
6561 else
6562 SCS = &ICS.UserDefined.After;
6563 break;
6567 return S.Diag(From->getBeginLoc(),
6568 diag::err_typecheck_converted_constant_expression)
6569 << From->getType() << From->getSourceRange() << T;
6570 return ExprError();
6571
6574 llvm_unreachable("bad conversion in converted constant expression");
6575 }
6576
6577 // Check that we would only use permitted conversions.
6578 if (!CheckConvertedConstantConversions(S, *SCS)) {
6579 return S.Diag(From->getBeginLoc(),
6580 diag::err_typecheck_converted_constant_expression_disallowed)
6581 << From->getType() << From->getSourceRange() << T;
6582 }
6583 // [...] and where the reference binding (if any) binds directly.
6584 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6585 return S.Diag(From->getBeginLoc(),
6586 diag::err_typecheck_converted_constant_expression_indirect)
6587 << From->getType() << From->getSourceRange() << T;
6588 }
6589 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6590 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6591 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6592 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6593 // case explicitly.
6594 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6595 return S.Diag(From->getBeginLoc(),
6596 diag::err_reference_bind_to_bitfield_in_cce)
6597 << From->getSourceRange();
6598 }
6599
6600 // Usually we can simply apply the ImplicitConversionSequence we formed
6601 // earlier, but that's not guaranteed to work when initializing an object of
6602 // class type.
6604 bool IsTemplateArgument =
6606 if (T->isRecordType()) {
6607 assert(IsTemplateArgument &&
6608 "unexpected class type converted constant expr");
6612 SourceLocation(), From);
6613 } else {
6614 Result =
6616 }
6617 if (Result.isInvalid())
6618 return Result;
6619
6620 // C++2a [intro.execution]p5:
6621 // A full-expression is [...] a constant-expression [...]
6622 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6623 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6624 IsTemplateArgument);
6625 if (Result.isInvalid())
6626 return Result;
6627
6628 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6629
6630 // Check for a narrowing implicit conversion.
6631 bool ReturnPreNarrowingValue = false;
6632 QualType PreNarrowingType;
6633 switch (SCS->getNarrowingKind(
6634 S.Context, Result.get(), PreNarrowingValue, PreNarrowingType,
6635 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6637 // Implicit conversion to a narrower type, and the value is not a constant
6638 // expression. We'll diagnose this in a moment.
6639 case NK_Not_Narrowing:
6640 break;
6641
6643 if (CCE == CCEKind::ArrayBound &&
6644 PreNarrowingType->isIntegralOrEnumerationType() &&
6645 PreNarrowingValue.isInt()) {
6646 // Don't diagnose array bound narrowing here; we produce more precise
6647 // errors by allowing the un-narrowed value through.
6648 ReturnPreNarrowingValue = true;
6649 break;
6650 }
6651 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6652 << CCE << /*Constant*/ 1
6653 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6654 // If this is an SFINAE Context, treat the result as invalid so it stops
6655 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6656 // FIXME: Should do this whenever the above diagnostic is an error, but
6657 // without further changes this would degrade some other diagnostics.
6658 if (S.isSFINAEContext())
6659 return ExprError();
6660 break;
6661
6663 // Implicit conversion to a narrower type, but the expression is
6664 // value-dependent so we can't tell whether it's actually narrowing.
6665 // For matching the parameters of a TTP, the conversion is ill-formed
6666 // if it may narrow.
6667 if (CCE != CCEKind::TempArgStrict)
6668 break;
6669 [[fallthrough]];
6670 case NK_Type_Narrowing:
6671 // FIXME: It would be better to diagnose that the expression is not a
6672 // constant expression.
6673 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6674 << CCE << /*Constant*/ 0 << From->getType() << T;
6675 if (S.isSFINAEContext())
6676 return ExprError();
6677 break;
6678 }
6679 if (!ReturnPreNarrowingValue)
6680 PreNarrowingValue = {};
6681
6682 return Result;
6683}
6684
6685/// CheckConvertedConstantExpression - Check that the expression From is a
6686/// converted constant expression of type T, perform the conversion and produce
6687/// the converted expression, per C++11 [expr.const]p3.
6690 CCEKind CCE, bool RequireInt,
6691 NamedDecl *Dest) {
6692
6693 APValue PreNarrowingValue;
6695 PreNarrowingValue);
6696 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6697 Value = APValue();
6698 return Result;
6699 }
6700 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6701 RequireInt, PreNarrowingValue);
6702}
6703
6705 CCEKind CCE,
6706 NamedDecl *Dest) {
6707 APValue PreNarrowingValue;
6708 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6709 PreNarrowingValue);
6710}
6711
6713 APValue &Value, CCEKind CCE,
6714 NamedDecl *Dest) {
6715 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6716 Dest);
6717}
6718
6720 llvm::APSInt &Value,
6721 CCEKind CCE) {
6722 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6723
6724 APValue V;
6725 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6726 /*Dest=*/nullptr);
6727 if (!R.isInvalid() && !R.get()->isValueDependent())
6728 Value = V.getInt();
6729 return R;
6730}
6731
6734 CCEKind CCE, bool RequireInt,
6735 const APValue &PreNarrowingValue) {
6736
6737 ExprResult Result = E;
6738 // Check the expression is a constant expression.
6741 Expr::EvalResult Eval;
6742 Eval.Diag = &Notes;
6743 Eval.ExtendedDiag = &MSWarning;
6744
6745 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6746
6747 ConstantExprKind Kind;
6748 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6749 Kind = ConstantExprKind::ClassTemplateArgument;
6750 else if (CCE == CCEKind::TemplateArg)
6751 Kind = ConstantExprKind::NonClassTemplateArgument;
6752 else
6753 Kind = ConstantExprKind::Normal;
6754
6755 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6756 (RequireInt && !Eval.Val.isInt())) {
6757 // The expression can't be folded, so we can't keep it at this position in
6758 // the AST.
6759 Result = ExprError();
6760 } else {
6761 Value = Eval.Val;
6762 // For -fms-compatibility mode we relax some requirements
6763 // for constant folding in non-SFINAE contexts
6764 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6765 if (Notes.empty() && !CantFold) {
6766 for (auto &Info : MSWarning)
6767 Diag(Info.first, Info.second);
6768 // It's a constant expression.
6769 Expr *E = Result.get();
6770 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6771 // We expect a ConstantExpr to have a value associated with it
6772 // by this point.
6773 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6774 "ConstantExpr has no value associated with it");
6775 (void)CE;
6776 } else {
6778 }
6779 if (!PreNarrowingValue.isAbsent())
6780 Value = std::move(PreNarrowingValue);
6781 return E;
6782 }
6783 }
6784
6785 // It's not a constant expression. Produce an appropriate diagnostic.
6786 if (Notes.size() == 1 &&
6787 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6788 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6789 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6790 diag::note_constexpr_invalid_template_arg) {
6791 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6792 for (unsigned I = 0; I < Notes.size(); ++I)
6793 Diag(Notes[I].first, Notes[I].second);
6794 } else {
6795 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6796 << CCE << E->getSourceRange();
6797 for (unsigned I = 0; I < Notes.size(); ++I)
6798 Diag(Notes[I].first, Notes[I].second);
6799 }
6800 return ExprError();
6801}
6802
6803/// dropPointerConversions - If the given standard conversion sequence
6804/// involves any pointer conversions, remove them. This may change
6805/// the result type of the conversion sequence.
6807 if (SCS.Second == ICK_Pointer_Conversion) {
6808 SCS.Second = ICK_Identity;
6809 SCS.Dimension = ICK_Identity;
6810 SCS.Third = ICK_Identity;
6811 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6812 }
6813}
6814
6815/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6816/// convert the expression From to an Objective-C pointer type.
6817static ImplicitConversionSequence
6819 // Do an implicit conversion to 'id'.
6822 = TryImplicitConversion(S, From, Ty,
6823 // FIXME: Are these flags correct?
6824 /*SuppressUserConversions=*/false,
6825 AllowedExplicit::Conversions,
6826 /*InOverloadResolution=*/false,
6827 /*CStyle=*/false,
6828 /*AllowObjCWritebackConversion=*/false,
6829 /*AllowObjCConversionOnExplicit=*/true);
6830
6831 // Strip off any final conversions to 'id'.
6832 switch (ICS.getKind()) {
6837 break;
6838
6841 break;
6842
6845 break;
6846 }
6847
6848 return ICS;
6849}
6850
6852 if (checkPlaceholderForOverload(*this, From))
6853 return ExprError();
6854
6855 QualType Ty = Context.getObjCIdType();
6858 if (!ICS.isBad())
6859 return PerformImplicitConversion(From, Ty, ICS,
6861 return ExprResult();
6862}
6863
6864static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6865 const Expr *Base = nullptr;
6866 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6867 "expected a member expression");
6868
6869 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6870 M && !M->isImplicitAccess())
6871 Base = M->getBase();
6872 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6873 M && !M->isImplicitAccess())
6874 Base = M->getBase();
6875
6876 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6877
6878 if (T->isPointerType())
6879 T = T->getPointeeType();
6880
6881 return T;
6882}
6883
6885 const FunctionDecl *Fun) {
6886 QualType ObjType = Obj->getType();
6887 if (ObjType->isPointerType()) {
6888 ObjType = ObjType->getPointeeType();
6889 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6891 /*CanOverflow=*/false, FPOptionsOverride());
6892 }
6893 return Obj;
6894}
6895
6903
6905 Expr *Object, MultiExprArg &Args,
6906 SmallVectorImpl<Expr *> &NewArgs) {
6907 assert(Method->isExplicitObjectMemberFunction() &&
6908 "Method is not an explicit member function");
6909 assert(NewArgs.empty() && "NewArgs should be empty");
6910
6911 NewArgs.reserve(Args.size() + 1);
6912 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6913 NewArgs.push_back(This);
6914 NewArgs.append(Args.begin(), Args.end());
6915 Args = NewArgs;
6917 Method, Object->getBeginLoc());
6918}
6919
6920/// Determine whether the provided type is an integral type, or an enumeration
6921/// type of a permitted flavor.
6923 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6924 : T->isIntegralOrUnscopedEnumerationType();
6925}
6926
6927static ExprResult
6930 QualType T, UnresolvedSetImpl &ViableConversions) {
6931
6932 if (Converter.Suppress)
6933 return ExprError();
6934
6935 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6936 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6937 CXXConversionDecl *Conv =
6938 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6940 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6941 }
6942 return From;
6943}
6944
6945static bool
6948 QualType T, bool HadMultipleCandidates,
6949 UnresolvedSetImpl &ExplicitConversions) {
6950 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6951 DeclAccessPair Found = ExplicitConversions[0];
6952 CXXConversionDecl *Conversion =
6953 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6954
6955 // The user probably meant to invoke the given explicit
6956 // conversion; use it.
6957 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6958 std::string TypeStr;
6959 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6960
6961 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6963 "static_cast<" + TypeStr + ">(")
6965 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6966 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6967
6968 // If we aren't in a SFINAE context, build a call to the
6969 // explicit conversion function.
6970 if (SemaRef.isSFINAEContext())
6971 return true;
6972
6973 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6974 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6975 HadMultipleCandidates);
6976 if (Result.isInvalid())
6977 return true;
6978
6979 // Replace the conversion with a RecoveryExpr, so we don't try to
6980 // instantiate it later, but can further diagnose here.
6981 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6982 From, Result.get()->getType());
6983 if (Result.isInvalid())
6984 return true;
6985 From = Result.get();
6986 }
6987 return false;
6988}
6989
6990static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6992 QualType T, bool HadMultipleCandidates,
6994 CXXConversionDecl *Conversion =
6995 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6996 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6997
6998 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6999 if (!Converter.SuppressConversion) {
7000 if (SemaRef.isSFINAEContext())
7001 return true;
7002
7003 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
7004 << From->getSourceRange();
7005 }
7006
7007 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
7008 HadMultipleCandidates);
7009 if (Result.isInvalid())
7010 return true;
7011 // Record usage of conversion in an implicit cast.
7012 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
7013 CK_UserDefinedConversion, Result.get(),
7014 nullptr, Result.get()->getValueKind(),
7015 SemaRef.CurFPFeatureOverrides());
7016 return false;
7017}
7018
7020 Sema &SemaRef, SourceLocation Loc, Expr *From,
7022 if (!Converter.match(From->getType()) && !Converter.Suppress)
7023 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
7024 << From->getSourceRange();
7025
7026 return SemaRef.DefaultLvalueConversion(From);
7027}
7028
7029static void
7031 UnresolvedSetImpl &ViableConversions,
7032 OverloadCandidateSet &CandidateSet) {
7033 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7034 NamedDecl *D = FoundDecl.getDecl();
7035 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7036 if (isa<UsingShadowDecl>(D))
7037 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7038
7039 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7041 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7042 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7043 continue;
7044 }
7046 SemaRef.AddConversionCandidate(
7047 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7048 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7049 }
7050}
7051
7052/// Attempt to convert the given expression to a type which is accepted
7053/// by the given converter.
7054///
7055/// This routine will attempt to convert an expression of class type to a
7056/// type accepted by the specified converter. In C++11 and before, the class
7057/// must have a single non-explicit conversion function converting to a matching
7058/// type. In C++1y, there can be multiple such conversion functions, but only
7059/// one target type.
7060///
7061/// \param Loc The source location of the construct that requires the
7062/// conversion.
7063///
7064/// \param From The expression we're converting from.
7065///
7066/// \param Converter Used to control and diagnose the conversion process.
7067///
7068/// \returns The expression, converted to an integral or enumeration type if
7069/// successful.
7071 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7072 // We can't perform any more checking for type-dependent expressions.
7073 if (From->isTypeDependent())
7074 return From;
7075
7076 // Process placeholders immediately.
7077 if (From->hasPlaceholderType()) {
7078 ExprResult result = CheckPlaceholderExpr(From);
7079 if (result.isInvalid())
7080 return result;
7081 From = result.get();
7082 }
7083
7084 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7085 ExprResult Converted = DefaultLvalueConversion(From);
7086 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7087 From = Converted.isUsable() ? Converted.get() : nullptr;
7088 // If the expression already has a matching type, we're golden.
7089 if (Converter.match(T))
7090 return Converted;
7091
7092 // FIXME: Check for missing '()' if T is a function type?
7093
7094 // We can only perform contextual implicit conversions on objects of class
7095 // type.
7096 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7097 if (!RecordTy || !getLangOpts().CPlusPlus) {
7098 if (!Converter.Suppress)
7099 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7100 return From;
7101 }
7102
7103 // We must have a complete class type.
7104 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7105 ContextualImplicitConverter &Converter;
7106 Expr *From;
7107
7108 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7109 : Converter(Converter), From(From) {}
7110
7111 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7112 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7113 }
7114 } IncompleteDiagnoser(Converter, From);
7115
7116 if (Converter.Suppress ? !isCompleteType(Loc, T)
7117 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7118 return From;
7119
7120 // Look for a conversion to an integral or enumeration type.
7122 ViableConversions; // These are *potentially* viable in C++1y.
7123 UnresolvedSet<4> ExplicitConversions;
7124 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7125 ->getDefinitionOrSelf()
7126 ->getVisibleConversionFunctions();
7127
7128 bool HadMultipleCandidates =
7129 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7130
7131 // To check that there is only one target type, in C++1y:
7132 QualType ToType;
7133 bool HasUniqueTargetType = true;
7134
7135 // Collect explicit or viable (potentially in C++1y) conversions.
7136 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7137 NamedDecl *D = (*I)->getUnderlyingDecl();
7138 CXXConversionDecl *Conversion;
7139 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7140 if (ConvTemplate) {
7142 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7143 else
7144 continue; // C++11 does not consider conversion operator templates(?).
7145 } else
7146 Conversion = cast<CXXConversionDecl>(D);
7147
7148 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7149 "Conversion operator templates are considered potentially "
7150 "viable in C++1y");
7151
7152 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7153 if (Converter.match(CurToType) || ConvTemplate) {
7154
7155 if (Conversion->isExplicit()) {
7156 // FIXME: For C++1y, do we need this restriction?
7157 // cf. diagnoseNoViableConversion()
7158 if (!ConvTemplate)
7159 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7160 } else {
7161 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7162 if (ToType.isNull())
7163 ToType = CurToType.getUnqualifiedType();
7164 else if (HasUniqueTargetType &&
7165 (CurToType.getUnqualifiedType() != ToType))
7166 HasUniqueTargetType = false;
7167 }
7168 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7169 }
7170 }
7171 }
7172
7173 if (getLangOpts().CPlusPlus14) {
7174 // C++1y [conv]p6:
7175 // ... An expression e of class type E appearing in such a context
7176 // is said to be contextually implicitly converted to a specified
7177 // type T and is well-formed if and only if e can be implicitly
7178 // converted to a type T that is determined as follows: E is searched
7179 // for conversion functions whose return type is cv T or reference to
7180 // cv T such that T is allowed by the context. There shall be
7181 // exactly one such T.
7182
7183 // If no unique T is found:
7184 if (ToType.isNull()) {
7185 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7186 HadMultipleCandidates,
7187 ExplicitConversions))
7188 return ExprError();
7189 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7190 }
7191
7192 // If more than one unique Ts are found:
7193 if (!HasUniqueTargetType)
7194 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7195 ViableConversions);
7196
7197 // If one unique T is found:
7198 // First, build a candidate set from the previously recorded
7199 // potentially viable conversions.
7201 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7202 CandidateSet);
7203
7204 // Then, perform overload resolution over the candidate set.
7206 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7207 case OR_Success: {
7208 // Apply this conversion.
7210 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7211 if (recordConversion(*this, Loc, From, Converter, T,
7212 HadMultipleCandidates, Found))
7213 return ExprError();
7214 break;
7215 }
7216 case OR_Ambiguous:
7217 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7218 ViableConversions);
7220 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7221 HadMultipleCandidates,
7222 ExplicitConversions))
7223 return ExprError();
7224 [[fallthrough]];
7225 case OR_Deleted:
7226 // We'll complain below about a non-integral condition type.
7227 break;
7228 }
7229 } else {
7230 switch (ViableConversions.size()) {
7231 case 0: {
7232 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7233 HadMultipleCandidates,
7234 ExplicitConversions))
7235 return ExprError();
7236
7237 // We'll complain below about a non-integral condition type.
7238 break;
7239 }
7240 case 1: {
7241 // Apply this conversion.
7242 DeclAccessPair Found = ViableConversions[0];
7243 if (recordConversion(*this, Loc, From, Converter, T,
7244 HadMultipleCandidates, Found))
7245 return ExprError();
7246 break;
7247 }
7248 default:
7249 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7250 ViableConversions);
7251 }
7252 }
7253
7254 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7255}
7256
7257/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7258/// an acceptable non-member overloaded operator for a call whose
7259/// arguments have types T1 (and, if non-empty, T2). This routine
7260/// implements the check in C++ [over.match.oper]p3b2 concerning
7261/// enumeration types.
7263 FunctionDecl *Fn,
7264 ArrayRef<Expr *> Args) {
7265 QualType T1 = Args[0]->getType();
7266 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7267
7268 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7269 return true;
7270
7271 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7272 return true;
7273
7274 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7275 if (Proto->getNumParams() < 1)
7276 return false;
7277
7278 if (T1->isEnumeralType()) {
7279 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7280 if (Context.hasSameUnqualifiedType(T1, ArgType))
7281 return true;
7282 }
7283
7284 if (Proto->getNumParams() < 2)
7285 return false;
7286
7287 if (!T2.isNull() && T2->isEnumeralType()) {
7288 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7289 if (Context.hasSameUnqualifiedType(T2, ArgType))
7290 return true;
7291 }
7292
7293 return false;
7294}
7295
7298 return false;
7299
7300 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7301 return FD->isTargetMultiVersion();
7302
7303 if (!FD->isMultiVersion())
7304 return false;
7305
7306 // Among multiple target versions consider either the default,
7307 // or the first non-default in the absence of default version.
7308 unsigned SeenAt = 0;
7309 unsigned I = 0;
7310 bool HasDefault = false;
7312 FD, [&](const FunctionDecl *CurFD) {
7313 if (FD == CurFD)
7314 SeenAt = I;
7315 else if (CurFD->isTargetMultiVersionDefault())
7316 HasDefault = true;
7317 ++I;
7318 });
7319 return HasDefault || SeenAt != 0;
7320}
7321
7324 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7325 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7326 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7327 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7328 bool StrictPackMatch) {
7329 const FunctionProtoType *Proto
7330 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7331 assert(Proto && "Functions without a prototype cannot be overloaded");
7332 assert(!Function->getDescribedFunctionTemplate() &&
7333 "Use AddTemplateOverloadCandidate for function templates");
7334
7335 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7337 // If we get here, it's because we're calling a member function
7338 // that is named without a member access expression (e.g.,
7339 // "this->f") that was either written explicitly or created
7340 // implicitly. This can happen with a qualified call to a member
7341 // function, e.g., X::f(). We use an empty type for the implied
7342 // object argument (C++ [over.call.func]p3), and the acting context
7343 // is irrelevant.
7344 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7346 CandidateSet, SuppressUserConversions,
7347 PartialOverloading, EarlyConversions, PO,
7348 StrictPackMatch);
7349 return;
7350 }
7351 // We treat a constructor like a non-member function, since its object
7352 // argument doesn't participate in overload resolution.
7353 }
7354
7355 if (!CandidateSet.isNewCandidate(Function, PO))
7356 return;
7357
7358 // C++11 [class.copy]p11: [DR1402]
7359 // A defaulted move constructor that is defined as deleted is ignored by
7360 // overload resolution.
7361 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7362 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7363 Constructor->isMoveConstructor())
7364 return;
7365
7366 // Overload resolution is always an unevaluated context.
7369
7370 // C++ [over.match.oper]p3:
7371 // if no operand has a class type, only those non-member functions in the
7372 // lookup set that have a first parameter of type T1 or "reference to
7373 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7374 // is a right operand) a second parameter of type T2 or "reference to
7375 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7376 // candidate functions.
7377 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7379 return;
7380
7381 // Add this candidate
7382 OverloadCandidate &Candidate =
7383 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7384 Candidate.FoundDecl = FoundDecl;
7385 Candidate.Function = Function;
7386 Candidate.Viable = true;
7387 Candidate.RewriteKind =
7388 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7389 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7390 Candidate.ExplicitCallArguments = Args.size();
7391 Candidate.StrictPackMatch = StrictPackMatch;
7392
7393 // Explicit functions are not actually candidates at all if we're not
7394 // allowing them in this context, but keep them around so we can point
7395 // to them in diagnostics.
7396 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7397 Candidate.Viable = false;
7398 Candidate.FailureKind = ovl_fail_explicit;
7399 return;
7400 }
7401
7402 // Functions with internal linkage are only viable in the same module unit.
7403 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7404 /// FIXME: Currently, the semantics of linkage in clang is slightly
7405 /// different from the semantics in C++ spec. In C++ spec, only names
7406 /// have linkage. So that all entities of the same should share one
7407 /// linkage. But in clang, different entities of the same could have
7408 /// different linkage.
7409 const NamedDecl *ND = Function;
7410 bool IsImplicitlyInstantiated = false;
7411 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7412 ND = SpecInfo->getTemplate();
7413 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7415 }
7416
7417 /// Don't remove inline functions with internal linkage from the overload
7418 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7419 /// However:
7420 /// - Inline functions with internal linkage are a common pattern in
7421 /// headers to avoid ODR issues.
7422 /// - The global module is meant to be a transition mechanism for C and C++
7423 /// headers, and the current rules as written work against that goal.
7424 const bool IsInlineFunctionInGMF =
7425 Function->isFromGlobalModule() &&
7426 (IsImplicitlyInstantiated || Function->isInlined());
7427
7428 // Don't exclude internal-linkage entities from the current TU's global
7429 // module fragment.
7430 const Module *CurrentModule = getCurrentModule();
7431 const bool IsCurrentUnitGMFDecl =
7432 Function->isFromGlobalModule() && CurrentModule &&
7433 Function->getOwningModule()->getTopLevelModule() ==
7434 CurrentModule->getTopLevelModule();
7435
7436 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7437 !IsCurrentUnitGMFDecl) {
7438 Candidate.Viable = false;
7440 return;
7441 }
7442 }
7443
7445 Candidate.Viable = false;
7447 return;
7448 }
7449
7450 if (Constructor) {
7451 // C++ [class.copy]p3:
7452 // A member function template is never instantiated to perform the copy
7453 // of a class object to an object of its class type.
7454 CanQualType ClassType =
7455 Context.getCanonicalTagType(Constructor->getParent());
7456 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7457 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7458 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7459 ClassType))) {
7460 Candidate.Viable = false;
7462 return;
7463 }
7464
7465 // C++ [over.match.funcs]p8: (proposed DR resolution)
7466 // A constructor inherited from class type C that has a first parameter
7467 // of type "reference to P" (including such a constructor instantiated
7468 // from a template) is excluded from the set of candidate functions when
7469 // constructing an object of type cv D if the argument list has exactly
7470 // one argument and D is reference-related to P and P is reference-related
7471 // to C.
7472 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7473 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7474 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7475 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7476 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7477 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7478 SourceLocation Loc = Args.front()->getExprLoc();
7479 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7480 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7481 Candidate.Viable = false;
7483 return;
7484 }
7485 }
7486
7487 // Check that the constructor is capable of constructing an object in the
7488 // destination address space.
7490 Constructor->getMethodQualifiers().getAddressSpace(),
7491 CandidateSet.getDestAS(), getASTContext())) {
7492 Candidate.Viable = false;
7494 }
7495 }
7496
7497 unsigned NumParams = Proto->getNumParams();
7498
7499 // (C++ 13.3.2p2): A candidate function having fewer than m
7500 // parameters is viable only if it has an ellipsis in its parameter
7501 // list (8.3.5).
7502 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7503 !Proto->isVariadic() &&
7504 shouldEnforceArgLimit(PartialOverloading, Function)) {
7505 Candidate.Viable = false;
7507 return;
7508 }
7509
7510 // (C++ 13.3.2p2): A candidate function having more than m parameters
7511 // is viable only if the (m+1)st parameter has a default argument
7512 // (8.3.6). For the purposes of overload resolution, the
7513 // parameter list is truncated on the right, so that there are
7514 // exactly m parameters.
7515 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7516 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7517 !PartialOverloading) {
7518 // Not enough arguments.
7519 Candidate.Viable = false;
7521 return;
7522 }
7523
7524 // (CUDA B.1): Check for invalid calls between targets.
7525 if (getLangOpts().CUDA) {
7526 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7527 // Skip the check for callers that are implicit members, because in this
7528 // case we may not yet know what the member's target is; the target is
7529 // inferred for the member automatically, based on the bases and fields of
7530 // the class.
7531 if (!(Caller && Caller->isImplicit()) &&
7532 !CUDA().IsAllowedCall(Caller, Function)) {
7533 Candidate.Viable = false;
7534 Candidate.FailureKind = ovl_fail_bad_target;
7535 return;
7536 }
7537 }
7538
7539 if (Function->getTrailingRequiresClause()) {
7540 ConstraintSatisfaction Satisfaction;
7541 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7542 /*ForOverloadResolution*/ true) ||
7543 !Satisfaction.IsSatisfied) {
7544 Candidate.Viable = false;
7546 return;
7547 }
7548 }
7549
7550 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7551 // Determine the implicit conversion sequences for each of the
7552 // arguments.
7553 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7554 unsigned ConvIdx =
7555 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7556 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7557 // We already formed a conversion sequence for this parameter during
7558 // template argument deduction.
7559 } else if (ArgIdx < NumParams) {
7560 // (C++ 13.3.2p3): for F to be a viable function, there shall
7561 // exist for each argument an implicit conversion sequence
7562 // (13.3.3.1) that converts that argument to the corresponding
7563 // parameter of F.
7564 QualType ParamType = Proto->getParamType(ArgIdx);
7565 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7566 if (ParamABI == ParameterABI::HLSLOut ||
7567 ParamABI == ParameterABI::HLSLInOut) {
7568 ParamType = ParamType.getNonReferenceType();
7569 if (ParamABI == ParameterABI::HLSLInOut &&
7570 Args[ArgIdx]->getType().getAddressSpace() ==
7572 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7573 }
7574 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7575 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7576 /*InOverloadResolution=*/true,
7577 /*AllowObjCWritebackConversion=*/
7578 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7579 if (Candidate.Conversions[ConvIdx].isBad()) {
7580 Candidate.Viable = false;
7582 return;
7583 }
7584 } else {
7585 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7586 // argument for which there is no corresponding parameter is
7587 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7588 Candidate.Conversions[ConvIdx].setEllipsis();
7589 }
7590 }
7591
7592 if (EnableIfAttr *FailedAttr =
7593 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7594 Candidate.Viable = false;
7595 Candidate.FailureKind = ovl_fail_enable_if;
7596 Candidate.DeductionFailure.Data = FailedAttr;
7597 return;
7598 }
7599}
7600
7604 if (Methods.size() <= 1)
7605 return nullptr;
7606
7607 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7608 bool Match = true;
7609 ObjCMethodDecl *Method = Methods[b];
7610 unsigned NumNamedArgs = Sel.getNumArgs();
7611 // Method might have more arguments than selector indicates. This is due
7612 // to addition of c-style arguments in method.
7613 if (Method->param_size() > NumNamedArgs)
7614 NumNamedArgs = Method->param_size();
7615 if (Args.size() < NumNamedArgs)
7616 continue;
7617
7618 for (unsigned i = 0; i < NumNamedArgs; i++) {
7619 // We can't do any type-checking on a type-dependent argument.
7620 if (Args[i]->isTypeDependent()) {
7621 Match = false;
7622 break;
7623 }
7624
7625 ParmVarDecl *param = Method->parameters()[i];
7626 Expr *argExpr = Args[i];
7627 assert(argExpr && "SelectBestMethod(): missing expression");
7628
7629 // Strip the unbridged-cast placeholder expression off unless it's
7630 // a consumed argument.
7631 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7632 !param->hasAttr<CFConsumedAttr>())
7633 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7634
7635 // If the parameter is __unknown_anytype, move on to the next method.
7636 if (param->getType() == Context.UnknownAnyTy) {
7637 Match = false;
7638 break;
7639 }
7640
7641 ImplicitConversionSequence ConversionState
7642 = TryCopyInitialization(*this, argExpr, param->getType(),
7643 /*SuppressUserConversions*/false,
7644 /*InOverloadResolution=*/true,
7645 /*AllowObjCWritebackConversion=*/
7646 getLangOpts().ObjCAutoRefCount,
7647 /*AllowExplicit*/false);
7648 // This function looks for a reasonably-exact match, so we consider
7649 // incompatible pointer conversions to be a failure here.
7650 if (ConversionState.isBad() ||
7651 (ConversionState.isStandard() &&
7652 ConversionState.Standard.Second ==
7654 Match = false;
7655 break;
7656 }
7657 }
7658 // Promote additional arguments to variadic methods.
7659 if (Match && Method->isVariadic()) {
7660 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7661 if (Args[i]->isTypeDependent()) {
7662 Match = false;
7663 break;
7664 }
7666 Args[i], VariadicCallType::Method, nullptr);
7667 if (Arg.isInvalid()) {
7668 Match = false;
7669 break;
7670 }
7671 }
7672 } else {
7673 // Check for extra arguments to non-variadic methods.
7674 if (Args.size() != NumNamedArgs)
7675 Match = false;
7676 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7677 // Special case when selectors have no argument. In this case, select
7678 // one with the most general result type of 'id'.
7679 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7680 QualType ReturnT = Methods[b]->getReturnType();
7681 if (ReturnT->isObjCIdType())
7682 return Methods[b];
7683 }
7684 }
7685 }
7686
7687 if (Match)
7688 return Method;
7689 }
7690 return nullptr;
7691}
7692
7694 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7695 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7696 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7697 if (ThisArg) {
7698 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7699 assert(!isa<CXXConstructorDecl>(Method) &&
7700 "Shouldn't have `this` for ctors!");
7701 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7703 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7704 if (R.isInvalid())
7705 return false;
7706 ConvertedThis = R.get();
7707 } else {
7708 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7709 (void)MD;
7710 assert((MissingImplicitThis || MD->isStatic() ||
7712 "Expected `this` for non-ctor instance methods");
7713 }
7714 ConvertedThis = nullptr;
7715 }
7716
7717 // Ignore any variadic arguments. Converting them is pointless, since the
7718 // user can't refer to them in the function condition.
7719 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7720
7721 // Convert the arguments.
7722 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7723 ExprResult R;
7725 S.Context, Function->getParamDecl(I)),
7726 SourceLocation(), Args[I]);
7727
7728 if (R.isInvalid())
7729 return false;
7730
7731 ConvertedArgs.push_back(R.get());
7732 }
7733
7734 if (Trap.hasErrorOccurred())
7735 return false;
7736
7737 // Push default arguments if needed.
7738 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7739 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7740 ParmVarDecl *P = Function->getParamDecl(i);
7741 if (!P->hasDefaultArg())
7742 return false;
7743 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7744 if (R.isInvalid())
7745 return false;
7746 ConvertedArgs.push_back(R.get());
7747 }
7748
7749 if (Trap.hasErrorOccurred())
7750 return false;
7751 }
7752 return true;
7753}
7754
7756 SourceLocation CallLoc,
7757 ArrayRef<Expr *> Args,
7758 bool MissingImplicitThis) {
7759 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7760 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7761 return nullptr;
7762
7763 SFINAETrap Trap(*this);
7764 // Perform the access checking immediately so any access diagnostics are
7765 // caught by the SFINAE trap.
7766 llvm::scope_exit UndelayDiags(
7767 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7768 DelayedDiagnostics.popUndelayed(CurrentState);
7769 });
7770 SmallVector<Expr *, 16> ConvertedArgs;
7771 // FIXME: We should look into making enable_if late-parsed.
7772 Expr *DiscardedThis;
7774 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7775 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7776 return *EnableIfAttrs.begin();
7777
7778 for (auto *EIA : EnableIfAttrs) {
7780 // FIXME: This doesn't consider value-dependent cases, because doing so is
7781 // very difficult. Ideally, we should handle them more gracefully.
7782 if (EIA->getCond()->isValueDependent() ||
7783 !EIA->getCond()->EvaluateWithSubstitution(
7784 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7785 return EIA;
7786
7787 if (!Result.isInt() || !Result.getInt().getBoolValue())
7788 return EIA;
7789 }
7790 return nullptr;
7791}
7792
7793template <typename CheckFn>
7795 bool ArgDependent, SourceLocation Loc,
7796 CheckFn &&IsSuccessful) {
7798 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7799 if (ArgDependent == DIA->getArgDependent())
7800 Attrs.push_back(DIA);
7801 }
7802
7803 // Common case: No diagnose_if attributes, so we can quit early.
7804 if (Attrs.empty())
7805 return false;
7806
7807 auto WarningBegin = std::stable_partition(
7808 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7809 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7810 DIA->getWarningGroup().empty();
7811 });
7812
7813 // Note that diagnose_if attributes are late-parsed, so they appear in the
7814 // correct order (unlike enable_if attributes).
7815 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7816 IsSuccessful);
7817 if (ErrAttr != WarningBegin) {
7818 const DiagnoseIfAttr *DIA = *ErrAttr;
7819 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7820 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7821 << DIA->getParent() << DIA->getCond()->getSourceRange();
7822 return true;
7823 }
7824
7825 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7826 switch (Sev) {
7827 case DiagnoseIfAttr::DS_warning:
7829 case DiagnoseIfAttr::DS_error:
7830 return diag::Severity::Error;
7831 }
7832 llvm_unreachable("Fully covered switch above!");
7833 };
7834
7835 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7836 if (IsSuccessful(DIA)) {
7837 if (DIA->getWarningGroup().empty() &&
7838 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7839 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7840 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7841 << DIA->getParent() << DIA->getCond()->getSourceRange();
7842 } else {
7843 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7844 DIA->getWarningGroup());
7845 assert(DiagGroup);
7846 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7847 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7848 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7849 S.Diag(Loc, DiagID) << DIA->getMessage();
7850 }
7851 }
7852
7853 return false;
7854}
7855
7857 const Expr *ThisArg,
7859 SourceLocation Loc) {
7861 *this, Function, /*ArgDependent=*/true, Loc,
7862 [&](const DiagnoseIfAttr *DIA) {
7864 // It's sane to use the same Args for any redecl of this function, since
7865 // EvaluateWithSubstitution only cares about the position of each
7866 // argument in the arg list, not the ParmVarDecl* it maps to.
7867 if (!DIA->getCond()->EvaluateWithSubstitution(
7868 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7869 return false;
7870 return Result.isInt() && Result.getInt().getBoolValue();
7871 });
7872}
7873
7875 SourceLocation Loc) {
7877 *this, ND, /*ArgDependent=*/false, Loc,
7878 [&](const DiagnoseIfAttr *DIA) {
7879 bool Result;
7880 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7881 Result;
7882 });
7883}
7884
7886 ArrayRef<Expr *> Args,
7887 OverloadCandidateSet &CandidateSet,
7888 TemplateArgumentListInfo *ExplicitTemplateArgs,
7889 bool SuppressUserConversions,
7890 bool PartialOverloading,
7891 bool FirstArgumentIsBase) {
7892 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7893 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7894 ArrayRef<Expr *> FunctionArgs = Args;
7895
7896 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7897 FunctionDecl *FD =
7898 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7899
7900 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7901 QualType ObjectType;
7902 Expr::Classification ObjectClassification;
7903 if (Args.size() > 0) {
7904 if (Expr *E = Args[0]) {
7905 // Use the explicit base to restrict the lookup:
7906 ObjectType = E->getType();
7907 // Pointers in the object arguments are implicitly dereferenced, so we
7908 // always classify them as l-values.
7909 if (!ObjectType.isNull() && ObjectType->isPointerType())
7910 ObjectClassification = Expr::Classification::makeSimpleLValue();
7911 else
7912 ObjectClassification = E->Classify(Context);
7913 } // .. else there is an implicit base.
7914 FunctionArgs = Args.slice(1);
7915 }
7916 if (FunTmpl) {
7918 FunTmpl, F.getPair(),
7920 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7921 FunctionArgs, CandidateSet, SuppressUserConversions,
7922 PartialOverloading);
7923 } else {
7924 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7925 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7926 ObjectClassification, FunctionArgs, CandidateSet,
7927 SuppressUserConversions, PartialOverloading);
7928 }
7929 } else {
7930 // This branch handles both standalone functions and static methods.
7931
7932 // Slice the first argument (which is the base) when we access
7933 // static method as non-static.
7934 if (Args.size() > 0 &&
7935 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7936 !isa<CXXConstructorDecl>(FD)))) {
7937 assert(cast<CXXMethodDecl>(FD)->isStatic());
7938 FunctionArgs = Args.slice(1);
7939 }
7940 if (FunTmpl) {
7941 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7942 ExplicitTemplateArgs, FunctionArgs,
7943 CandidateSet, SuppressUserConversions,
7944 PartialOverloading);
7945 } else {
7946 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7947 SuppressUserConversions, PartialOverloading);
7948 }
7949 }
7950 }
7951}
7952
7954 Expr::Classification ObjectClassification,
7955 ArrayRef<Expr *> Args,
7956 OverloadCandidateSet &CandidateSet,
7957 bool SuppressUserConversions,
7959 NamedDecl *Decl = FoundDecl.getDecl();
7961
7963 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7964
7965 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7966 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7967 "Expected a member function template");
7968 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7969 /*ExplicitArgs*/ nullptr, ObjectType,
7970 ObjectClassification, Args, CandidateSet,
7971 SuppressUserConversions, false, PO);
7972 } else {
7973 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7974 ObjectType, ObjectClassification, Args, CandidateSet,
7975 SuppressUserConversions, false, {}, PO);
7976 }
7977}
7978
7981 CXXRecordDecl *ActingContext, QualType ObjectType,
7982 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7983 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7984 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7985 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7986 const FunctionProtoType *Proto
7987 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7988 assert(Proto && "Methods without a prototype cannot be overloaded");
7990 "Use AddOverloadCandidate for constructors");
7991
7992 if (!CandidateSet.isNewCandidate(Method, PO))
7993 return;
7994
7995 // C++11 [class.copy]p23: [DR1402]
7996 // A defaulted move assignment operator that is defined as deleted is
7997 // ignored by overload resolution.
7998 if (Method->isDefaulted() && Method->isDeleted() &&
7999 Method->isMoveAssignmentOperator())
8000 return;
8001
8002 // Overload resolution is always an unevaluated context.
8005
8006 bool IgnoreExplicitObject =
8007 (Method->isExplicitObjectMemberFunction() &&
8008 CandidateSet.getKind() ==
8010 bool ImplicitObjectMethodTreatedAsStatic =
8011 CandidateSet.getKind() ==
8013 Method->isImplicitObjectMemberFunction();
8014
8015 unsigned ExplicitOffset =
8016 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
8017
8018 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
8019 int(ImplicitObjectMethodTreatedAsStatic);
8020
8021 unsigned ExtraArgs =
8023 ? 0
8024 : 1;
8025
8026 // Add this candidate
8027 OverloadCandidate &Candidate =
8028 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
8029 Candidate.FoundDecl = FoundDecl;
8030 Candidate.Function = Method;
8031 Candidate.RewriteKind =
8032 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
8033 Candidate.TookAddressOfOverload =
8035 Candidate.ExplicitCallArguments = Args.size();
8036 Candidate.StrictPackMatch = StrictPackMatch;
8037
8038 // (C++ 13.3.2p2): A candidate function having fewer than m
8039 // parameters is viable only if it has an ellipsis in its parameter
8040 // list (8.3.5).
8041 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8042 !Proto->isVariadic() &&
8043 shouldEnforceArgLimit(PartialOverloading, Method)) {
8044 Candidate.Viable = false;
8046 return;
8047 }
8048
8049 // (C++ 13.3.2p2): A candidate function having more than m parameters
8050 // is viable only if the (m+1)st parameter has a default argument
8051 // (8.3.6). For the purposes of overload resolution, the
8052 // parameter list is truncated on the right, so that there are
8053 // exactly m parameters.
8054 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8055 ExplicitOffset +
8056 int(ImplicitObjectMethodTreatedAsStatic);
8057
8058 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8059 // Not enough arguments.
8060 Candidate.Viable = false;
8062 return;
8063 }
8064
8065 Candidate.Viable = true;
8066
8067 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8068 if (!IgnoreExplicitObject) {
8069 if (ObjectType.isNull())
8070 Candidate.IgnoreObjectArgument = true;
8071 else if (Method->isStatic()) {
8072 // [over.best.ics.general]p8
8073 // When the parameter is the implicit object parameter of a static member
8074 // function, the implicit conversion sequence is a standard conversion
8075 // sequence that is neither better nor worse than any other standard
8076 // conversion sequence.
8077 //
8078 // This is a rule that was introduced in C++23 to support static lambdas.
8079 // We apply it retroactively because we want to support static lambdas as
8080 // an extension and it doesn't hurt previous code.
8081 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8082 } else {
8083 // Determine the implicit conversion sequence for the object
8084 // parameter.
8085 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8086 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8087 Method, ActingContext, /*InOverloadResolution=*/true);
8088 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8089 Candidate.Viable = false;
8091 return;
8092 }
8093 }
8094 }
8095
8096 // (CUDA B.1): Check for invalid calls between targets.
8097 if (getLangOpts().CUDA)
8098 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8099 Method)) {
8100 Candidate.Viable = false;
8101 Candidate.FailureKind = ovl_fail_bad_target;
8102 return;
8103 }
8104
8105 if (Method->getTrailingRequiresClause()) {
8106 ConstraintSatisfaction Satisfaction;
8107 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8108 /*ForOverloadResolution*/ true) ||
8109 !Satisfaction.IsSatisfied) {
8110 Candidate.Viable = false;
8112 return;
8113 }
8114 }
8115
8116 // Determine the implicit conversion sequences for each of the
8117 // arguments.
8118 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8119 unsigned ConvIdx =
8120 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8121 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8122 // We already formed a conversion sequence for this parameter during
8123 // template argument deduction.
8124 } else if (ArgIdx < NumParams) {
8125 // (C++ 13.3.2p3): for F to be a viable function, there shall
8126 // exist for each argument an implicit conversion sequence
8127 // (13.3.3.1) that converts that argument to the corresponding
8128 // parameter of F.
8129 QualType ParamType;
8130 if (ImplicitObjectMethodTreatedAsStatic) {
8131 ParamType = ArgIdx == 0
8132 ? Method->getFunctionObjectParameterReferenceType()
8133 : Proto->getParamType(ArgIdx - 1);
8134 } else {
8135 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8136 }
8137 Candidate.Conversions[ConvIdx]
8138 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8139 SuppressUserConversions,
8140 /*InOverloadResolution=*/true,
8141 /*AllowObjCWritebackConversion=*/
8142 getLangOpts().ObjCAutoRefCount);
8143 if (Candidate.Conversions[ConvIdx].isBad()) {
8144 Candidate.Viable = false;
8146 return;
8147 }
8148 } else {
8149 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8150 // argument for which there is no corresponding parameter is
8151 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8152 Candidate.Conversions[ConvIdx].setEllipsis();
8153 }
8154 }
8155
8156 if (EnableIfAttr *FailedAttr =
8157 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8158 Candidate.Viable = false;
8159 Candidate.FailureKind = ovl_fail_enable_if;
8160 Candidate.DeductionFailure.Data = FailedAttr;
8161 return;
8162 }
8163
8165 Candidate.Viable = false;
8167 }
8168}
8169
8171 Sema &S, OverloadCandidateSet &CandidateSet,
8172 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8173 CXXRecordDecl *ActingContext,
8174 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8175 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8176 bool SuppressUserConversions, bool PartialOverloading,
8178
8179 // C++ [over.match.funcs]p7:
8180 // In each case where a candidate is a function template, candidate
8181 // function template specializations are generated using template argument
8182 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8183 // candidate functions in the usual way.113) A given name can refer to one
8184 // or more function templates and also to a set of overloaded non-template
8185 // functions. In such a case, the candidate functions generated from each
8186 // function template are combined with the set of non-template candidate
8187 // functions.
8188 TemplateDeductionInfo Info(CandidateSet.getLocation());
8189 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8190 FunctionDecl *Specialization = nullptr;
8191 ConversionSequenceList Conversions;
8193 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8194 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8195 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8196 CandidateSet.getKind() ==
8198 [&](ArrayRef<QualType> ParamTypes,
8199 bool OnlyInitializeNonUserDefinedConversions) {
8200 return S.CheckNonDependentConversions(
8201 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8202 Sema::CheckNonDependentConversionsFlag(
8203 SuppressUserConversions,
8204 OnlyInitializeNonUserDefinedConversions),
8205 ActingContext, ObjectType, ObjectClassification, PO);
8206 });
8208 OverloadCandidate &Candidate =
8209 CandidateSet.addCandidate(Conversions.size(), Conversions);
8210 Candidate.FoundDecl = FoundDecl;
8211 Candidate.Function = Method;
8212 Candidate.Viable = false;
8213 Candidate.RewriteKind =
8214 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8215 Candidate.IsSurrogate = false;
8216 Candidate.TookAddressOfOverload =
8217 CandidateSet.getKind() ==
8219
8220 Candidate.IgnoreObjectArgument =
8221 Method->isStatic() ||
8222 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8223 Candidate.ExplicitCallArguments = Args.size();
8226 else {
8228 Candidate.DeductionFailure =
8230 }
8231 return;
8232 }
8233
8234 // Add the function template specialization produced by template argument
8235 // deduction as a candidate.
8236 assert(Specialization && "Missing member function template specialization?");
8238 "Specialization is not a member function?");
8240 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8241 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8242 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8243}
8244
8246 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8247 CXXRecordDecl *ActingContext,
8248 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8249 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8250 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8251 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8252 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8253 return;
8254
8255 if (ExplicitTemplateArgs ||
8256 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8258 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8259 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8260 SuppressUserConversions, PartialOverloading, PO);
8261 return;
8262 }
8263
8265 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8266 Args, SuppressUserConversions, PartialOverloading, PO);
8267}
8268
8269/// Determine whether a given function template has a simple explicit specifier
8270/// or a non-value-dependent explicit-specification that evaluates to true.
8274
8279
8281 Sema &S, OverloadCandidateSet &CandidateSet,
8283 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8284 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8286 bool AggregateCandidateDeduction) {
8287
8288 // If the function template has a non-dependent explicit specification,
8289 // exclude it now if appropriate; we are not permitted to perform deduction
8290 // and substitution in this case.
8291 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8292 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8293 Candidate.FoundDecl = FoundDecl;
8294 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8295 Candidate.Viable = false;
8296 Candidate.FailureKind = ovl_fail_explicit;
8297 return;
8298 }
8299
8300 // C++ [over.match.funcs]p7:
8301 // In each case where a candidate is a function template, candidate
8302 // function template specializations are generated using template argument
8303 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8304 // candidate functions in the usual way.113) A given name can refer to one
8305 // or more function templates and also to a set of overloaded non-template
8306 // functions. In such a case, the candidate functions generated from each
8307 // function template are combined with the set of non-template candidate
8308 // functions.
8309 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8310 FunctionTemplate->getTemplateDepth());
8311 FunctionDecl *Specialization = nullptr;
8312 ConversionSequenceList Conversions;
8314 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8315 PartialOverloading, AggregateCandidateDeduction,
8316 /*PartialOrdering=*/false,
8317 /*ObjectType=*/QualType(),
8318 /*ObjectClassification=*/Expr::Classification(),
8319 CandidateSet.getKind() ==
8321 [&](ArrayRef<QualType> ParamTypes,
8322 bool OnlyInitializeNonUserDefinedConversions) {
8323 return S.CheckNonDependentConversions(
8324 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8325 Sema::CheckNonDependentConversionsFlag(
8326 SuppressUserConversions,
8327 OnlyInitializeNonUserDefinedConversions),
8328 nullptr, QualType(), {}, PO);
8329 });
8331 OverloadCandidate &Candidate =
8332 CandidateSet.addCandidate(Conversions.size(), Conversions);
8333 Candidate.FoundDecl = FoundDecl;
8334 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8335 Candidate.Viable = false;
8336 Candidate.RewriteKind =
8337 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8338 Candidate.IsSurrogate = false;
8339 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8340 // Ignore the object argument if there is one, since we don't have an object
8341 // type.
8342 Candidate.TookAddressOfOverload =
8343 CandidateSet.getKind() ==
8345
8346 Candidate.IgnoreObjectArgument =
8347 isa<CXXMethodDecl>(Candidate.Function) &&
8348 !cast<CXXMethodDecl>(Candidate.Function)
8349 ->isExplicitObjectMemberFunction() &&
8351
8352 Candidate.ExplicitCallArguments = Args.size();
8355 else {
8357 Candidate.DeductionFailure =
8359 }
8360 return;
8361 }
8362
8363 // Add the function template specialization produced by template argument
8364 // deduction as a candidate.
8365 assert(Specialization && "Missing function template specialization?");
8367 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8368 PartialOverloading, AllowExplicit,
8369 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8370 Info.AggregateDeductionCandidateHasMismatchedArity,
8371 Info.hasStrictPackMatch());
8372}
8373
8376 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8377 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8378 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8379 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8380 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8381 return;
8382
8383 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8384
8385 if (ExplicitTemplateArgs ||
8386 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8387 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8388 DependentExplicitSpecifier)) {
8389
8391 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8392 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8393 IsADLCandidate, PO, AggregateCandidateDeduction);
8394
8395 if (DependentExplicitSpecifier)
8397 return;
8398 }
8399
8400 CandidateSet.AddDeferredTemplateCandidate(
8401 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8402 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8403 AggregateCandidateDeduction);
8404}
8405
8408 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8410 CheckNonDependentConversionsFlag UserConversionFlag,
8411 CXXRecordDecl *ActingContext, QualType ObjectType,
8412 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8413 // FIXME: The cases in which we allow explicit conversions for constructor
8414 // arguments never consider calling a constructor template. It's not clear
8415 // that is correct.
8416 const bool AllowExplicit = false;
8417
8418 bool ForOverloadSetAddressResolution =
8420 auto *FD = FunctionTemplate->getTemplatedDecl();
8421 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8422 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8424 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8425
8426 if (Conversions.empty())
8427 Conversions =
8428 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8429
8430 // Overload resolution is always an unevaluated context.
8433
8434 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8435 // require that, but this check should never result in a hard error, and
8436 // overload resolution is permitted to sidestep instantiations.
8437 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8438 !ObjectType.isNull()) {
8439 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8440 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8441 !ParamTypes[0]->isDependentType()) {
8443 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8444 Method, ActingContext, /*InOverloadResolution=*/true,
8445 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8446 : QualType());
8447 if (Conversions[ConvIdx].isBad())
8448 return true;
8449 }
8450 }
8451
8452 // A speculative workaround for self-dependent constraint bugs that manifest
8453 // after CWG2369.
8454 // FIXME: Add references to the standard once P3606 is adopted.
8455 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8456 QualType ArgType) {
8457 ParamType = ParamType.getNonReferenceType();
8458 ArgType = ArgType.getNonReferenceType();
8459 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8460 if (PointerConv) {
8461 ParamType = ParamType->getPointeeType();
8462 ArgType = ArgType->getPointeeType();
8463 }
8464
8465 if (auto *RD = ParamType->getAsCXXRecordDecl();
8466 RD && RD->hasDefinition() &&
8467 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8468 auto Info = getConstructorInfo(ND);
8469 if (!Info)
8470 return false;
8471 CXXConstructorDecl *Ctor = Info.Constructor;
8472 /// isConvertingConstructor takes copy/move constructors into
8473 /// account!
8474 return !Ctor->isCopyOrMoveConstructor() &&
8476 /*AllowExplicit=*/true);
8477 }))
8478 return true;
8479 if (auto *RD = ArgType->getAsCXXRecordDecl();
8480 RD && RD->hasDefinition() &&
8481 !RD->getVisibleConversionFunctions().empty())
8482 return true;
8483
8484 return false;
8485 };
8486
8487 unsigned Offset =
8488 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8489 : 0;
8490
8491 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8492 I != N; ++I) {
8493 QualType ParamType = ParamTypes[I + Offset];
8494 if (!ParamType->isDependentType()) {
8495 unsigned ConvIdx;
8497 ConvIdx = Args.size() - 1 - I;
8498 assert(Args.size() + ThisConversions == 2 &&
8499 "number of args (including 'this') must be exactly 2 for "
8500 "reversed order");
8501 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8502 // would also be 0. 'this' got ConvIdx = 1 previously.
8503 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8504 } else {
8505 // For members, 'this' got ConvIdx = 0 previously.
8506 ConvIdx = ThisConversions + I;
8507 }
8508 if (Conversions[ConvIdx].isInitialized())
8509 continue;
8510 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8511 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8512 continue;
8514 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8515 /*InOverloadResolution=*/true,
8516 /*AllowObjCWritebackConversion=*/
8517 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8518 if (Conversions[ConvIdx].isBad())
8519 return true;
8520 }
8521 }
8522
8523 return false;
8524}
8525
8526/// Determine whether this is an allowable conversion from the result
8527/// of an explicit conversion operator to the expected type, per C++
8528/// [over.match.conv]p1 and [over.match.ref]p1.
8529///
8530/// \param ConvType The return type of the conversion function.
8531///
8532/// \param ToType The type we are converting to.
8533///
8534/// \param AllowObjCPointerConversion Allow a conversion from one
8535/// Objective-C pointer to another.
8536///
8537/// \returns true if the conversion is allowable, false otherwise.
8539 QualType ConvType, QualType ToType,
8540 bool AllowObjCPointerConversion) {
8541 QualType ToNonRefType = ToType.getNonReferenceType();
8542
8543 // Easy case: the types are the same.
8544 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8545 return true;
8546
8547 // Allow qualification conversions.
8548 bool ObjCLifetimeConversion;
8549 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8550 ObjCLifetimeConversion))
8551 return true;
8552
8553 // If we're not allowed to consider Objective-C pointer conversions,
8554 // we're done.
8555 if (!AllowObjCPointerConversion)
8556 return false;
8557
8558 // Is this an Objective-C pointer conversion?
8559 bool IncompatibleObjC = false;
8560 QualType ConvertedType;
8561 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8562 IncompatibleObjC);
8563}
8564
8566 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8567 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8568 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8569 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8570 assert(!Conversion->getDescribedFunctionTemplate() &&
8571 "Conversion function templates use AddTemplateConversionCandidate");
8572 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8573 if (!CandidateSet.isNewCandidate(Conversion))
8574 return;
8575
8576 // If the conversion function has an undeduced return type, trigger its
8577 // deduction now.
8578 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8579 if (DeduceReturnType(Conversion, From->getExprLoc()))
8580 return;
8581 ConvType = Conversion->getConversionType().getNonReferenceType();
8582 }
8583
8584 // If we don't allow any conversion of the result type, ignore conversion
8585 // functions that don't convert to exactly (possibly cv-qualified) T.
8586 if (!AllowResultConversion &&
8587 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8588 return;
8589
8590 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8591 // operator is only a candidate if its return type is the target type or
8592 // can be converted to the target type with a qualification conversion.
8593 //
8594 // FIXME: Include such functions in the candidate list and explain why we
8595 // can't select them.
8596 if (Conversion->isExplicit() &&
8597 !isAllowableExplicitConversion(*this, ConvType, ToType,
8598 AllowObjCConversionOnExplicit))
8599 return;
8600
8601 // Overload resolution is always an unevaluated context.
8604
8605 // Add this candidate
8606 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8607 Candidate.FoundDecl = FoundDecl;
8608 Candidate.Function = Conversion;
8610 Candidate.FinalConversion.setFromType(ConvType);
8611 Candidate.FinalConversion.setAllToTypes(ToType);
8612 Candidate.HasFinalConversion = true;
8613 Candidate.Viable = true;
8614 Candidate.ExplicitCallArguments = 1;
8615 Candidate.StrictPackMatch = StrictPackMatch;
8616
8617 // Explicit functions are not actually candidates at all if we're not
8618 // allowing them in this context, but keep them around so we can point
8619 // to them in diagnostics.
8620 if (!AllowExplicit && Conversion->isExplicit()) {
8621 Candidate.Viable = false;
8622 Candidate.FailureKind = ovl_fail_explicit;
8623 return;
8624 }
8625
8626 // C++ [over.match.funcs]p4:
8627 // For conversion functions, the function is considered to be a member of
8628 // the class of the implicit implied object argument for the purpose of
8629 // defining the type of the implicit object parameter.
8630 //
8631 // Determine the implicit conversion sequence for the implicit
8632 // object parameter.
8633 QualType ObjectType = From->getType();
8634 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8635 ObjectType = FromPtrType->getPointeeType();
8636 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8637 // C++23 [over.best.ics.general]
8638 // However, if the target is [...]
8639 // - the object parameter of a user-defined conversion function
8640 // [...] user-defined conversion sequences are not considered.
8642 *this, CandidateSet.getLocation(), From->getType(),
8643 From->Classify(Context), Conversion, ConversionContext,
8644 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8645 /*SuppressUserConversion*/ true);
8646
8647 if (Candidate.Conversions[0].isBad()) {
8648 Candidate.Viable = false;
8650 return;
8651 }
8652
8653 if (Conversion->getTrailingRequiresClause()) {
8654 ConstraintSatisfaction Satisfaction;
8655 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8656 !Satisfaction.IsSatisfied) {
8657 Candidate.Viable = false;
8659 return;
8660 }
8661 }
8662
8663 // We won't go through a user-defined type conversion function to convert a
8664 // derived to base as such conversions are given Conversion Rank. They only
8665 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8666 QualType FromCanon
8667 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8668 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8669 if (FromCanon == ToCanon ||
8670 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8671 Candidate.Viable = false;
8673 return;
8674 }
8675
8676 // To determine what the conversion from the result of calling the
8677 // conversion function to the type we're eventually trying to
8678 // convert to (ToType), we need to synthesize a call to the
8679 // conversion function and attempt copy initialization from it. This
8680 // makes sure that we get the right semantics with respect to
8681 // lvalues/rvalues and the type. Fortunately, we can allocate this
8682 // call on the stack and we don't need its arguments to be
8683 // well-formed.
8684 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8685 VK_LValue, From->getBeginLoc());
8687 Context.getPointerType(Conversion->getType()),
8688 CK_FunctionToPointerDecay, &ConversionRef,
8690
8691 QualType ConversionType = Conversion->getConversionType();
8692 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8693 Candidate.Viable = false;
8695 return;
8696 }
8697
8698 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8699
8700 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8701
8702 // Introduce a temporary expression with the right type and value category
8703 // that we can use for deduction purposes.
8704 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8705
8707 TryCopyInitialization(*this, &FakeCall, ToType,
8708 /*SuppressUserConversions=*/true,
8709 /*InOverloadResolution=*/false,
8710 /*AllowObjCWritebackConversion=*/false);
8711
8712 switch (ICS.getKind()) {
8714 Candidate.FinalConversion = ICS.Standard;
8715 Candidate.HasFinalConversion = true;
8716
8717 // C++ [over.ics.user]p3:
8718 // If the user-defined conversion is specified by a specialization of a
8719 // conversion function template, the second standard conversion sequence
8720 // shall have exact match rank.
8721 if (Conversion->getPrimaryTemplate() &&
8723 Candidate.Viable = false;
8725 return;
8726 }
8727
8728 // C++0x [dcl.init.ref]p5:
8729 // In the second case, if the reference is an rvalue reference and
8730 // the second standard conversion sequence of the user-defined
8731 // conversion sequence includes an lvalue-to-rvalue conversion, the
8732 // program is ill-formed.
8733 if (ToType->isRValueReferenceType() &&
8735 Candidate.Viable = false;
8737 return;
8738 }
8739 break;
8740
8742 Candidate.Viable = false;
8744 return;
8745
8746 default:
8747 llvm_unreachable(
8748 "Can only end up with a standard conversion sequence or failure");
8749 }
8750
8751 if (EnableIfAttr *FailedAttr =
8752 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8753 Candidate.Viable = false;
8754 Candidate.FailureKind = ovl_fail_enable_if;
8755 Candidate.DeductionFailure.Data = FailedAttr;
8756 return;
8757 }
8758
8759 if (isNonViableMultiVersionOverload(Conversion)) {
8760 Candidate.Viable = false;
8762 }
8763}
8764
8766 Sema &S, OverloadCandidateSet &CandidateSet,
8768 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8769 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8770 bool AllowResultConversion) {
8771
8772 // If the function template has a non-dependent explicit specification,
8773 // exclude it now if appropriate; we are not permitted to perform deduction
8774 // and substitution in this case.
8775 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8776 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8777 Candidate.FoundDecl = FoundDecl;
8778 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8779 Candidate.Viable = false;
8780 Candidate.FailureKind = ovl_fail_explicit;
8781 return;
8782 }
8783
8784 QualType ObjectType = From->getType();
8785 Expr::Classification ObjectClassification = From->Classify(S.Context);
8786
8787 TemplateDeductionInfo Info(CandidateSet.getLocation());
8790 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8791 Specialization, Info);
8793 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8794 Candidate.FoundDecl = FoundDecl;
8795 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8796 Candidate.Viable = false;
8798 Candidate.ExplicitCallArguments = 1;
8799 Candidate.DeductionFailure =
8801 return;
8802 }
8803
8804 // Add the conversion function template specialization produced by
8805 // template argument deduction as a candidate.
8806 assert(Specialization && "Missing function template specialization?");
8807 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8808 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8809 AllowExplicit, AllowResultConversion,
8810 Info.hasStrictPackMatch());
8811}
8812
8815 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8816 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8817 bool AllowExplicit, bool AllowResultConversion) {
8818 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8819 "Only conversion function templates permitted here");
8820
8821 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8822 return;
8823
8824 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8825 CandidateSet.getKind() ==
8829 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8830 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8831 AllowResultConversion);
8832
8834 return;
8835 }
8836
8838 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8839 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8840}
8841
8843 DeclAccessPair FoundDecl,
8844 CXXRecordDecl *ActingContext,
8845 const FunctionProtoType *Proto,
8846 Expr *Object,
8847 ArrayRef<Expr *> Args,
8848 OverloadCandidateSet& CandidateSet) {
8849 if (!CandidateSet.isNewCandidate(Conversion))
8850 return;
8851
8852 // Overload resolution is always an unevaluated context.
8855
8856 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8857 Candidate.FoundDecl = FoundDecl;
8858 Candidate.Function = nullptr;
8859 Candidate.Surrogate = Conversion;
8860 Candidate.IsSurrogate = true;
8861 Candidate.Viable = true;
8862 Candidate.ExplicitCallArguments = Args.size();
8863
8864 // Determine the implicit conversion sequence for the implicit
8865 // object parameter.
8866 ImplicitConversionSequence ObjectInit;
8867 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8868 ObjectInit = TryCopyInitialization(*this, Object,
8869 Conversion->getParamDecl(0)->getType(),
8870 /*SuppressUserConversions=*/false,
8871 /*InOverloadResolution=*/true, false);
8872 } else {
8874 *this, CandidateSet.getLocation(), Object->getType(),
8875 Object->Classify(Context), Conversion, ActingContext);
8876 }
8877
8878 if (ObjectInit.isBad()) {
8879 Candidate.Viable = false;
8881 Candidate.Conversions[0] = ObjectInit;
8882 return;
8883 }
8884
8885 // The first conversion is actually a user-defined conversion whose
8886 // first conversion is ObjectInit's standard conversion (which is
8887 // effectively a reference binding). Record it as such.
8888 Candidate.Conversions[0].setUserDefined();
8889 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8890 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8891 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8892 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8893 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8894 Candidate.Conversions[0].UserDefined.After
8895 = Candidate.Conversions[0].UserDefined.Before;
8896 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8897
8898 // Find the
8899 unsigned NumParams = Proto->getNumParams();
8900
8901 // (C++ 13.3.2p2): A candidate function having fewer than m
8902 // parameters is viable only if it has an ellipsis in its parameter
8903 // list (8.3.5).
8904 if (Args.size() > NumParams && !Proto->isVariadic()) {
8905 Candidate.Viable = false;
8907 return;
8908 }
8909
8910 // Function types don't have any default arguments, so just check if
8911 // we have enough arguments.
8912 if (Args.size() < NumParams) {
8913 // Not enough arguments.
8914 Candidate.Viable = false;
8916 return;
8917 }
8918
8919 // Determine the implicit conversion sequences for each of the
8920 // arguments.
8921 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8922 if (ArgIdx < NumParams) {
8923 // (C++ 13.3.2p3): for F to be a viable function, there shall
8924 // exist for each argument an implicit conversion sequence
8925 // (13.3.3.1) that converts that argument to the corresponding
8926 // parameter of F.
8927 QualType ParamType = Proto->getParamType(ArgIdx);
8928 Candidate.Conversions[ArgIdx + 1]
8929 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8930 /*SuppressUserConversions=*/false,
8931 /*InOverloadResolution=*/false,
8932 /*AllowObjCWritebackConversion=*/
8933 getLangOpts().ObjCAutoRefCount);
8934 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8935 Candidate.Viable = false;
8937 return;
8938 }
8939 } else {
8940 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8941 // argument for which there is no corresponding parameter is
8942 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8943 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8944 }
8945 }
8946
8947 if (Conversion->getTrailingRequiresClause()) {
8948 ConstraintSatisfaction Satisfaction;
8949 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8950 /*ForOverloadResolution*/ true) ||
8951 !Satisfaction.IsSatisfied) {
8952 Candidate.Viable = false;
8954 return;
8955 }
8956 }
8957
8958 if (EnableIfAttr *FailedAttr =
8959 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8960 Candidate.Viable = false;
8961 Candidate.FailureKind = ovl_fail_enable_if;
8962 Candidate.DeductionFailure.Data = FailedAttr;
8963 return;
8964 }
8965}
8966
8968 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8969 OverloadCandidateSet &CandidateSet,
8970 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8971 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8972 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8973 ArrayRef<Expr *> FunctionArgs = Args;
8974
8975 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8976 FunctionDecl *FD =
8977 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8978
8979 // Don't consider rewritten functions if we're not rewriting.
8980 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8981 continue;
8982
8983 assert(!isa<CXXMethodDecl>(FD) &&
8984 "unqualified operator lookup found a member function");
8985
8986 if (FunTmpl) {
8987 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8988 FunctionArgs, CandidateSet);
8989 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8990
8991 // As template candidates are not deduced immediately,
8992 // persist the array in the overload set.
8994 FunctionArgs[1], FunctionArgs[0]);
8995 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8996 Reversed, CandidateSet, false, false, true,
8997 ADLCallKind::NotADL,
8999 }
9000 } else {
9001 if (ExplicitTemplateArgs)
9002 continue;
9003 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
9004 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
9005 AddOverloadCandidate(FD, F.getPair(),
9006 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
9007 false, false, true, false, ADLCallKind::NotADL, {},
9009 }
9010 }
9011}
9012
9014 SourceLocation OpLoc,
9015 ArrayRef<Expr *> Args,
9016 OverloadCandidateSet &CandidateSet,
9018 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9019
9020 // C++ [over.match.oper]p3:
9021 // For a unary operator @ with an operand of a type whose
9022 // cv-unqualified version is T1, and for a binary operator @ with
9023 // a left operand of a type whose cv-unqualified version is T1 and
9024 // a right operand of a type whose cv-unqualified version is T2,
9025 // three sets of candidate functions, designated member
9026 // candidates, non-member candidates and built-in candidates, are
9027 // constructed as follows:
9028 QualType T1 = Args[0]->getType();
9029
9030 // -- If T1 is a complete class type or a class currently being
9031 // defined, the set of member candidates is the result of the
9032 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9033 // the set of member candidates is empty.
9034 if (T1->isRecordType()) {
9035 bool IsComplete = isCompleteType(OpLoc, T1);
9036 auto *T1RD = T1->getAsCXXRecordDecl();
9037 // Complete the type if it can be completed.
9038 // If the type is neither complete nor being defined, bail out now.
9039 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9040 return;
9041
9042 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9043 LookupQualifiedName(Operators, T1RD);
9044 Operators.suppressAccessDiagnostics();
9045
9046 for (LookupResult::iterator Oper = Operators.begin(),
9047 OperEnd = Operators.end();
9048 Oper != OperEnd; ++Oper) {
9049 if (Oper->getAsFunction() &&
9051 !CandidateSet.getRewriteInfo().shouldAddReversed(
9052 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9053 continue;
9054 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9055 Args[0]->Classify(Context), Args.slice(1),
9056 CandidateSet, /*SuppressUserConversion=*/false, PO);
9057 }
9058 }
9059}
9060
9062 OverloadCandidateSet& CandidateSet,
9063 bool IsAssignmentOperator,
9064 unsigned NumContextualBoolArguments) {
9065 // Overload resolution is always an unevaluated context.
9068
9069 // Add this candidate
9070 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9071 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9072 Candidate.Function = nullptr;
9073 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9074
9075 // Determine the implicit conversion sequences for each of the
9076 // arguments.
9077 Candidate.Viable = true;
9078 Candidate.ExplicitCallArguments = Args.size();
9079 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9080 // C++ [over.match.oper]p4:
9081 // For the built-in assignment operators, conversions of the
9082 // left operand are restricted as follows:
9083 // -- no temporaries are introduced to hold the left operand, and
9084 // -- no user-defined conversions are applied to the left
9085 // operand to achieve a type match with the left-most
9086 // parameter of a built-in candidate.
9087 //
9088 // We block these conversions by turning off user-defined
9089 // conversions, since that is the only way that initialization of
9090 // a reference to a non-class type can occur from something that
9091 // is not of the same type.
9092 if (ArgIdx < NumContextualBoolArguments) {
9093 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9094 "Contextual conversion to bool requires bool type");
9095 Candidate.Conversions[ArgIdx]
9096 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9097 } else {
9098 Candidate.Conversions[ArgIdx]
9099 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9100 ArgIdx == 0 && IsAssignmentOperator,
9101 /*InOverloadResolution=*/false,
9102 /*AllowObjCWritebackConversion=*/
9103 getLangOpts().ObjCAutoRefCount);
9104 }
9105 if (Candidate.Conversions[ArgIdx].isBad()) {
9106 Candidate.Viable = false;
9108 break;
9109 }
9110 }
9111}
9112
9113namespace {
9114
9115/// BuiltinCandidateTypeSet - A set of types that will be used for the
9116/// candidate operator functions for built-in operators (C++
9117/// [over.built]). The types are separated into pointer types and
9118/// enumeration types.
9119class BuiltinCandidateTypeSet {
9120 /// TypeSet - A set of types.
9121 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9122
9123 /// PointerTypes - The set of pointer types that will be used in the
9124 /// built-in candidates.
9125 TypeSet PointerTypes;
9126
9127 /// MemberPointerTypes - The set of member pointer types that will be
9128 /// used in the built-in candidates.
9129 TypeSet MemberPointerTypes;
9130
9131 /// EnumerationTypes - The set of enumeration types that will be
9132 /// used in the built-in candidates.
9133 TypeSet EnumerationTypes;
9134
9135 /// The set of vector types that will be used in the built-in
9136 /// candidates.
9137 TypeSet VectorTypes;
9138
9139 /// The set of matrix types that will be used in the built-in
9140 /// candidates.
9141 TypeSet MatrixTypes;
9142
9143 /// The set of _BitInt types that will be used in the built-in candidates.
9144 TypeSet BitIntTypes;
9145
9146 /// A flag indicating non-record types are viable candidates
9147 bool HasNonRecordTypes;
9148
9149 /// A flag indicating whether either arithmetic or enumeration types
9150 /// were present in the candidate set.
9151 bool HasArithmeticOrEnumeralTypes;
9152
9153 /// A flag indicating whether the nullptr type was present in the
9154 /// candidate set.
9155 bool HasNullPtrType;
9156
9157 /// Sema - The semantic analysis instance where we are building the
9158 /// candidate type set.
9159 Sema &SemaRef;
9160
9161 /// Context - The AST context in which we will build the type sets.
9162 ASTContext &Context;
9163
9164 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9165 const Qualifiers &VisibleQuals);
9166 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9167
9168public:
9169 /// iterator - Iterates through the types that are part of the set.
9170 typedef TypeSet::iterator iterator;
9171
9172 BuiltinCandidateTypeSet(Sema &SemaRef)
9173 : HasNonRecordTypes(false),
9174 HasArithmeticOrEnumeralTypes(false),
9175 HasNullPtrType(false),
9176 SemaRef(SemaRef),
9177 Context(SemaRef.Context) { }
9178
9179 void AddTypesConvertedFrom(QualType Ty,
9180 SourceLocation Loc,
9181 bool AllowUserConversions,
9182 bool AllowExplicitConversions,
9183 const Qualifiers &VisibleTypeConversionsQuals);
9184
9185 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9186 llvm::iterator_range<iterator> member_pointer_types() {
9187 return MemberPointerTypes;
9188 }
9189 llvm::iterator_range<iterator> enumeration_types() {
9190 return EnumerationTypes;
9191 }
9192 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9193 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9194 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9195
9196 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9197 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9198 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9199 bool hasNullPtrType() const { return HasNullPtrType; }
9200};
9201
9202} // end anonymous namespace
9203
9204/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9205/// the set of pointer types along with any more-qualified variants of
9206/// that type. For example, if @p Ty is "int const *", this routine
9207/// will add "int const *", "int const volatile *", "int const
9208/// restrict *", and "int const volatile restrict *" to the set of
9209/// pointer types. Returns true if the add of @p Ty itself succeeded,
9210/// false otherwise.
9211///
9212/// FIXME: what to do about extended qualifiers?
9213bool
9214BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9215 const Qualifiers &VisibleQuals) {
9216
9217 // Insert this type.
9218 if (!PointerTypes.insert(Ty))
9219 return false;
9220
9221 QualType PointeeTy;
9222 const PointerType *PointerTy = Ty->getAs<PointerType>();
9223 bool buildObjCPtr = false;
9224 if (!PointerTy) {
9225 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9226 PointeeTy = PTy->getPointeeType();
9227 buildObjCPtr = true;
9228 } else {
9229 PointeeTy = PointerTy->getPointeeType();
9230 }
9231
9232 // Don't add qualified variants of arrays. For one, they're not allowed
9233 // (the qualifier would sink to the element type), and for another, the
9234 // only overload situation where it matters is subscript or pointer +- int,
9235 // and those shouldn't have qualifier variants anyway.
9236 if (PointeeTy->isArrayType())
9237 return true;
9238
9239 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9240 bool hasVolatile = VisibleQuals.hasVolatile();
9241 bool hasRestrict = VisibleQuals.hasRestrict();
9242
9243 // Iterate through all strict supersets of BaseCVR.
9244 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9245 if ((CVR | BaseCVR) != CVR) continue;
9246 // Skip over volatile if no volatile found anywhere in the types.
9247 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9248
9249 // Skip over restrict if no restrict found anywhere in the types, or if
9250 // the type cannot be restrict-qualified.
9251 if ((CVR & Qualifiers::Restrict) &&
9252 (!hasRestrict ||
9253 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9254 continue;
9255
9256 // Build qualified pointee type.
9257 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9258
9259 // Build qualified pointer type.
9260 QualType QPointerTy;
9261 if (!buildObjCPtr)
9262 QPointerTy = Context.getPointerType(QPointeeTy);
9263 else
9264 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9265
9266 // Insert qualified pointer type.
9267 PointerTypes.insert(QPointerTy);
9268 }
9269
9270 return true;
9271}
9272
9273/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9274/// to the set of pointer types along with any more-qualified variants of
9275/// that type. For example, if @p Ty is "int const *", this routine
9276/// will add "int const *", "int const volatile *", "int const
9277/// restrict *", and "int const volatile restrict *" to the set of
9278/// pointer types. Returns true if the add of @p Ty itself succeeded,
9279/// false otherwise.
9280///
9281/// FIXME: what to do about extended qualifiers?
9282bool
9283BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9284 QualType Ty) {
9285 // Insert this type.
9286 if (!MemberPointerTypes.insert(Ty))
9287 return false;
9288
9289 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9290 assert(PointerTy && "type was not a member pointer type!");
9291
9292 QualType PointeeTy = PointerTy->getPointeeType();
9293 // Don't add qualified variants of arrays. For one, they're not allowed
9294 // (the qualifier would sink to the element type), and for another, the
9295 // only overload situation where it matters is subscript or pointer +- int,
9296 // and those shouldn't have qualifier variants anyway.
9297 if (PointeeTy->isArrayType())
9298 return true;
9299 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9300
9301 // Iterate through all strict supersets of the pointee type's CVR
9302 // qualifiers.
9303 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9304 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9305 if ((CVR | BaseCVR) != CVR) continue;
9306
9307 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9308 MemberPointerTypes.insert(Context.getMemberPointerType(
9309 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9310 }
9311
9312 return true;
9313}
9314
9315/// AddTypesConvertedFrom - Add each of the types to which the type @p
9316/// Ty can be implicit converted to the given set of @p Types. We're
9317/// primarily interested in pointer types and enumeration types. We also
9318/// take member pointer types, for the conditional operator.
9319/// AllowUserConversions is true if we should look at the conversion
9320/// functions of a class type, and AllowExplicitConversions if we
9321/// should also include the explicit conversion functions of a class
9322/// type.
9323void
9324BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9325 SourceLocation Loc,
9326 bool AllowUserConversions,
9327 bool AllowExplicitConversions,
9328 const Qualifiers &VisibleQuals) {
9329 // Only deal with canonical types.
9330 Ty = Context.getCanonicalType(Ty);
9331
9332 // Look through reference types; they aren't part of the type of an
9333 // expression for the purposes of conversions.
9334 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9335 Ty = RefTy->getPointeeType();
9336
9337 // If we're dealing with an array type, decay to the pointer.
9338 if (Ty->isArrayType())
9339 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9340
9341 // Otherwise, we don't care about qualifiers on the type.
9342 Ty = Ty.getLocalUnqualifiedType();
9343
9344 // Flag if we ever add a non-record type.
9345 bool TyIsRec = Ty->isRecordType();
9346 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9347
9348 // Flag if we encounter an arithmetic type.
9349 HasArithmeticOrEnumeralTypes =
9350 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9351
9352 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9353 PointerTypes.insert(Ty);
9354 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9355 // Insert our type, and its more-qualified variants, into the set
9356 // of types.
9357 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9358 return;
9359 } else if (Ty->isMemberPointerType()) {
9360 // Member pointers are far easier, since the pointee can't be converted.
9361 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9362 return;
9363 } else if (Ty->isEnumeralType()) {
9364 HasArithmeticOrEnumeralTypes = true;
9365 EnumerationTypes.insert(Ty);
9366 } else if (Ty->isBitIntType()) {
9367 HasArithmeticOrEnumeralTypes = true;
9368 BitIntTypes.insert(Ty);
9369 } else if (Ty->isVectorType()) {
9370 // We treat vector types as arithmetic types in many contexts as an
9371 // extension.
9372 HasArithmeticOrEnumeralTypes = true;
9373 VectorTypes.insert(Ty);
9374 } else if (Ty->isMatrixType()) {
9375 // Similar to vector types, we treat vector types as arithmetic types in
9376 // many contexts as an extension.
9377 HasArithmeticOrEnumeralTypes = true;
9378 MatrixTypes.insert(Ty);
9379 } else if (Ty->isNullPtrType()) {
9380 HasNullPtrType = true;
9381 } else if (AllowUserConversions && TyIsRec) {
9382 // No conversion functions in incomplete types.
9383 if (!SemaRef.isCompleteType(Loc, Ty))
9384 return;
9385
9386 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9387 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9388 if (isa<UsingShadowDecl>(D))
9389 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9390
9391 // Skip conversion function templates; they don't tell us anything
9392 // about which builtin types we can convert to.
9394 continue;
9395
9396 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9397 if (AllowExplicitConversions || !Conv->isExplicit()) {
9398 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9399 VisibleQuals);
9400 }
9401 }
9402 }
9403}
9404/// Helper function for adjusting address spaces for the pointer or reference
9405/// operands of builtin operators depending on the argument.
9410
9411/// Helper function for AddBuiltinOperatorCandidates() that adds
9412/// the volatile- and non-volatile-qualified assignment operators for the
9413/// given type to the candidate set.
9415 QualType T,
9416 ArrayRef<Expr *> Args,
9417 OverloadCandidateSet &CandidateSet) {
9418 QualType ParamTypes[2];
9419
9420 // T& operator=(T&, T)
9421 ParamTypes[0] = S.Context.getLValueReferenceType(
9423 ParamTypes[1] = T;
9424 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9425 /*IsAssignmentOperator=*/true);
9426
9428 // volatile T& operator=(volatile T&, T)
9429 ParamTypes[0] = S.Context.getLValueReferenceType(
9431 Args[0]));
9432 ParamTypes[1] = T;
9433 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9434 /*IsAssignmentOperator=*/true);
9435 }
9436}
9437
9438/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9439/// if any, found in visible type conversion functions found in ArgExpr's type.
9440static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9441 Qualifiers VRQuals;
9442 CXXRecordDecl *ClassDecl;
9443 if (const MemberPointerType *RHSMPType =
9444 ArgExpr->getType()->getAs<MemberPointerType>())
9445 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9446 else
9447 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9448 if (!ClassDecl) {
9449 // Just to be safe, assume the worst case.
9450 VRQuals.addVolatile();
9451 VRQuals.addRestrict();
9452 return VRQuals;
9453 }
9454 if (!ClassDecl->hasDefinition())
9455 return VRQuals;
9456
9457 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9458 if (isa<UsingShadowDecl>(D))
9459 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9460 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9461 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9462 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9463 CanTy = ResTypeRef->getPointeeType();
9464 // Need to go down the pointer/mempointer chain and add qualifiers
9465 // as see them.
9466 bool done = false;
9467 while (!done) {
9468 if (CanTy.isRestrictQualified())
9469 VRQuals.addRestrict();
9470 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9471 CanTy = ResTypePtr->getPointeeType();
9472 else if (const MemberPointerType *ResTypeMPtr =
9473 CanTy->getAs<MemberPointerType>())
9474 CanTy = ResTypeMPtr->getPointeeType();
9475 else
9476 done = true;
9477 if (CanTy.isVolatileQualified())
9478 VRQuals.addVolatile();
9479 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9480 return VRQuals;
9481 }
9482 }
9483 }
9484 return VRQuals;
9485}
9486
9487// Note: We're currently only handling qualifiers that are meaningful for the
9488// LHS of compound assignment overloading.
9490 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9491 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9492 // _Atomic
9493 if (Available.hasAtomic()) {
9494 Available.removeAtomic();
9495 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9496 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9497 return;
9498 }
9499
9500 // volatile
9501 if (Available.hasVolatile()) {
9502 Available.removeVolatile();
9503 assert(!Applied.hasVolatile());
9504 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9505 Callback);
9506 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9507 return;
9508 }
9509
9510 Callback(Applied);
9511}
9512
9514 QualifiersAndAtomic Quals,
9515 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9517 Callback);
9518}
9519
9521 QualifiersAndAtomic Quals,
9522 Sema &S) {
9523 if (Quals.hasAtomic())
9525 if (Quals.hasVolatile())
9528}
9529
9530namespace {
9531
9532/// Helper class to manage the addition of builtin operator overload
9533/// candidates. It provides shared state and utility methods used throughout
9534/// the process, as well as a helper method to add each group of builtin
9535/// operator overloads from the standard to a candidate set.
9536class BuiltinOperatorOverloadBuilder {
9537 // Common instance state available to all overload candidate addition methods.
9538 Sema &S;
9539 ArrayRef<Expr *> Args;
9540 QualifiersAndAtomic VisibleTypeConversionsQuals;
9541 bool HasArithmeticOrEnumeralCandidateType;
9542 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9543 OverloadCandidateSet &CandidateSet;
9544
9545 static constexpr int ArithmeticTypesCap = 26;
9546 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9547
9548 // Define some indices used to iterate over the arithmetic types in
9549 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9550 // types are that preserved by promotion (C++ [over.built]p2).
9551 unsigned FirstIntegralType,
9552 LastIntegralType;
9553 unsigned FirstPromotedIntegralType,
9554 LastPromotedIntegralType;
9555 unsigned FirstPromotedArithmeticType,
9556 LastPromotedArithmeticType;
9557 unsigned NumArithmeticTypes;
9558
9559 void InitArithmeticTypes() {
9560 // Start of promoted types.
9561 FirstPromotedArithmeticType = 0;
9562 ArithmeticTypes.push_back(S.Context.FloatTy);
9563 ArithmeticTypes.push_back(S.Context.DoubleTy);
9564 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9566 ArithmeticTypes.push_back(S.Context.Float128Ty);
9568 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9569
9570 // Start of integral types.
9571 FirstIntegralType = ArithmeticTypes.size();
9572 FirstPromotedIntegralType = ArithmeticTypes.size();
9573 ArithmeticTypes.push_back(S.Context.IntTy);
9574 ArithmeticTypes.push_back(S.Context.LongTy);
9575 ArithmeticTypes.push_back(S.Context.LongLongTy);
9579 ArithmeticTypes.push_back(S.Context.Int128Ty);
9580 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9581 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9582 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9586 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9587
9588 /// We add candidates for the unique, unqualified _BitInt types present in
9589 /// the candidate type set. The candidate set already handled ensuring the
9590 /// type is unqualified and canonical, but because we're adding from N
9591 /// different sets, we need to do some extra work to unique things. Insert
9592 /// the candidates into a unique set, then move from that set into the list
9593 /// of arithmetic types.
9594 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9595 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9596 for (QualType BitTy : Candidate.bitint_types())
9597 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9598 }
9599 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9600 LastPromotedIntegralType = ArithmeticTypes.size();
9601 LastPromotedArithmeticType = ArithmeticTypes.size();
9602 // End of promoted types.
9603
9604 ArithmeticTypes.push_back(S.Context.BoolTy);
9605 ArithmeticTypes.push_back(S.Context.CharTy);
9606 ArithmeticTypes.push_back(S.Context.WCharTy);
9607 if (S.Context.getLangOpts().Char8)
9608 ArithmeticTypes.push_back(S.Context.Char8Ty);
9609 ArithmeticTypes.push_back(S.Context.Char16Ty);
9610 ArithmeticTypes.push_back(S.Context.Char32Ty);
9611 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9612 ArithmeticTypes.push_back(S.Context.ShortTy);
9613 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9614 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9615 LastIntegralType = ArithmeticTypes.size();
9616 NumArithmeticTypes = ArithmeticTypes.size();
9617 // End of integral types.
9618 // FIXME: What about complex? What about half?
9619
9620 // We don't know for sure how many bit-precise candidates were involved, so
9621 // we subtract those from the total when testing whether we're under the
9622 // cap or not.
9623 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9624 ArithmeticTypesCap &&
9625 "Enough inline storage for all arithmetic types.");
9626 }
9627
9628 /// Helper method to factor out the common pattern of adding overloads
9629 /// for '++' and '--' builtin operators.
9630 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9631 bool HasVolatile,
9632 bool HasRestrict) {
9633 QualType ParamTypes[2] = {
9634 S.Context.getLValueReferenceType(CandidateTy),
9635 S.Context.IntTy
9636 };
9637
9638 // Non-volatile version.
9639 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9640
9641 // Use a heuristic to reduce number of builtin candidates in the set:
9642 // add volatile version only if there are conversions to a volatile type.
9643 if (HasVolatile) {
9644 ParamTypes[0] =
9646 S.Context.getVolatileType(CandidateTy));
9647 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9648 }
9649
9650 // Add restrict version only if there are conversions to a restrict type
9651 // and our candidate type is a non-restrict-qualified pointer.
9652 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9653 !CandidateTy.isRestrictQualified()) {
9654 ParamTypes[0]
9657 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9658
9659 if (HasVolatile) {
9660 ParamTypes[0]
9662 S.Context.getCVRQualifiedType(CandidateTy,
9665 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9666 }
9667 }
9668
9669 }
9670
9671 /// Helper to add an overload candidate for a binary builtin with types \p L
9672 /// and \p R.
9673 void AddCandidate(QualType L, QualType R) {
9674 QualType LandR[2] = {L, R};
9675 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9676 }
9677
9678public:
9679 BuiltinOperatorOverloadBuilder(
9680 Sema &S, ArrayRef<Expr *> Args,
9681 QualifiersAndAtomic VisibleTypeConversionsQuals,
9682 bool HasArithmeticOrEnumeralCandidateType,
9683 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9684 OverloadCandidateSet &CandidateSet)
9685 : S(S), Args(Args),
9686 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9687 HasArithmeticOrEnumeralCandidateType(
9688 HasArithmeticOrEnumeralCandidateType),
9689 CandidateTypes(CandidateTypes),
9690 CandidateSet(CandidateSet) {
9691
9692 InitArithmeticTypes();
9693 }
9694
9695 // Increment is deprecated for bool since C++17.
9696 //
9697 // C++ [over.built]p3:
9698 //
9699 // For every pair (T, VQ), where T is an arithmetic type other
9700 // than bool, and VQ is either volatile or empty, there exist
9701 // candidate operator functions of the form
9702 //
9703 // VQ T& operator++(VQ T&);
9704 // T operator++(VQ T&, int);
9705 //
9706 // C++ [over.built]p4:
9707 //
9708 // For every pair (T, VQ), where T is an arithmetic type other
9709 // than bool, and VQ is either volatile or empty, there exist
9710 // candidate operator functions of the form
9711 //
9712 // VQ T& operator--(VQ T&);
9713 // T operator--(VQ T&, int);
9714 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9715 if (!HasArithmeticOrEnumeralCandidateType)
9716 return;
9717
9718 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9719 const auto TypeOfT = ArithmeticTypes[Arith];
9720 if (TypeOfT == S.Context.BoolTy) {
9721 if (Op == OO_MinusMinus)
9722 continue;
9723 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9724 continue;
9725 }
9726 addPlusPlusMinusMinusStyleOverloads(
9727 TypeOfT,
9728 VisibleTypeConversionsQuals.hasVolatile(),
9729 VisibleTypeConversionsQuals.hasRestrict());
9730 }
9731 }
9732
9733 // C++ [over.built]p5:
9734 //
9735 // For every pair (T, VQ), where T is a cv-qualified or
9736 // cv-unqualified object type, and VQ is either volatile or
9737 // empty, there exist candidate operator functions of the form
9738 //
9739 // T*VQ& operator++(T*VQ&);
9740 // T*VQ& operator--(T*VQ&);
9741 // T* operator++(T*VQ&, int);
9742 // T* operator--(T*VQ&, int);
9743 void addPlusPlusMinusMinusPointerOverloads() {
9744 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9745 // Skip pointer types that aren't pointers to object types.
9746 if (!PtrTy->getPointeeType()->isObjectType())
9747 continue;
9748
9749 addPlusPlusMinusMinusStyleOverloads(
9750 PtrTy,
9751 (!PtrTy.isVolatileQualified() &&
9752 VisibleTypeConversionsQuals.hasVolatile()),
9753 (!PtrTy.isRestrictQualified() &&
9754 VisibleTypeConversionsQuals.hasRestrict()));
9755 }
9756 }
9757
9758 // C++ [over.built]p6:
9759 // For every cv-qualified or cv-unqualified object type T, there
9760 // exist candidate operator functions of the form
9761 //
9762 // T& operator*(T*);
9763 //
9764 // C++ [over.built]p7:
9765 // For every function type T that does not have cv-qualifiers or a
9766 // ref-qualifier, there exist candidate operator functions of the form
9767 // T& operator*(T*);
9768 void addUnaryStarPointerOverloads() {
9769 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9770 QualType PointeeTy = ParamTy->getPointeeType();
9771 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9772 continue;
9773
9774 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9775 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9776 continue;
9777
9778 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9779 }
9780 }
9781
9782 // C++ [over.built]p9:
9783 // For every promoted arithmetic type T, there exist candidate
9784 // operator functions of the form
9785 //
9786 // T operator+(T);
9787 // T operator-(T);
9788 void addUnaryPlusOrMinusArithmeticOverloads() {
9789 if (!HasArithmeticOrEnumeralCandidateType)
9790 return;
9791
9792 for (unsigned Arith = FirstPromotedArithmeticType;
9793 Arith < LastPromotedArithmeticType; ++Arith) {
9794 QualType ArithTy = ArithmeticTypes[Arith];
9795 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9796 }
9797
9798 // Extension: We also add these operators for vector types.
9799 for (QualType VecTy : CandidateTypes[0].vector_types())
9800 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9801 }
9802
9803 // C++ [over.built]p8:
9804 // For every type T, there exist candidate operator functions of
9805 // the form
9806 //
9807 // T* operator+(T*);
9808 void addUnaryPlusPointerOverloads() {
9809 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9810 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9811 }
9812
9813 // C++ [over.built]p10:
9814 // For every promoted integral type T, there exist candidate
9815 // operator functions of the form
9816 //
9817 // T operator~(T);
9818 void addUnaryTildePromotedIntegralOverloads() {
9819 if (!HasArithmeticOrEnumeralCandidateType)
9820 return;
9821
9822 for (unsigned Int = FirstPromotedIntegralType;
9823 Int < LastPromotedIntegralType; ++Int) {
9824 QualType IntTy = ArithmeticTypes[Int];
9825 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9826 }
9827
9828 // Extension: We also add this operator for vector types.
9829 for (QualType VecTy : CandidateTypes[0].vector_types())
9830 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9831 }
9832
9833 // C++ [over.match.oper]p16:
9834 // For every pointer to member type T or type std::nullptr_t, there
9835 // exist candidate operator functions of the form
9836 //
9837 // bool operator==(T,T);
9838 // bool operator!=(T,T);
9839 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9840 /// Set of (canonical) types that we've already handled.
9841 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9842
9843 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9844 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9845 // Don't add the same builtin candidate twice.
9846 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9847 continue;
9848
9849 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9850 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9851 }
9852
9853 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9855 if (AddedTypes.insert(NullPtrTy).second) {
9856 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9857 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9858 }
9859 }
9860 }
9861 }
9862
9863 // C++ [over.built]p15:
9864 //
9865 // For every T, where T is an enumeration type or a pointer type,
9866 // there exist candidate operator functions of the form
9867 //
9868 // bool operator<(T, T);
9869 // bool operator>(T, T);
9870 // bool operator<=(T, T);
9871 // bool operator>=(T, T);
9872 // bool operator==(T, T);
9873 // bool operator!=(T, T);
9874 // R operator<=>(T, T)
9875 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9876 // C++ [over.match.oper]p3:
9877 // [...]the built-in candidates include all of the candidate operator
9878 // functions defined in 13.6 that, compared to the given operator, [...]
9879 // do not have the same parameter-type-list as any non-template non-member
9880 // candidate.
9881 //
9882 // Note that in practice, this only affects enumeration types because there
9883 // aren't any built-in candidates of record type, and a user-defined operator
9884 // must have an operand of record or enumeration type. Also, the only other
9885 // overloaded operator with enumeration arguments, operator=,
9886 // cannot be overloaded for enumeration types, so this is the only place
9887 // where we must suppress candidates like this.
9888 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9889 UserDefinedBinaryOperators;
9890
9891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9892 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9893 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9894 CEnd = CandidateSet.end();
9895 C != CEnd; ++C) {
9896 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9897 continue;
9898
9899 if (C->Function->isFunctionTemplateSpecialization())
9900 continue;
9901
9902 // We interpret "same parameter-type-list" as applying to the
9903 // "synthesized candidate, with the order of the two parameters
9904 // reversed", not to the original function.
9905 bool Reversed = C->isReversed();
9906 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9907 ->getType()
9908 .getUnqualifiedType();
9909 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9910 ->getType()
9911 .getUnqualifiedType();
9912
9913 // Skip if either parameter isn't of enumeral type.
9914 if (!FirstParamType->isEnumeralType() ||
9915 !SecondParamType->isEnumeralType())
9916 continue;
9917
9918 // Add this operator to the set of known user-defined operators.
9919 UserDefinedBinaryOperators.insert(
9920 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9921 S.Context.getCanonicalType(SecondParamType)));
9922 }
9923 }
9924 }
9925
9926 /// Set of (canonical) types that we've already handled.
9927 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9928
9929 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9930 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9931 // Don't add the same builtin candidate twice.
9932 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9933 continue;
9934 if (IsSpaceship && PtrTy->isFunctionPointerType())
9935 continue;
9936
9937 QualType ParamTypes[2] = {PtrTy, PtrTy};
9938 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9939 }
9940 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9941 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9942
9943 // Don't add the same builtin candidate twice, or if a user defined
9944 // candidate exists.
9945 if (!AddedTypes.insert(CanonType).second ||
9946 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9947 CanonType)))
9948 continue;
9949 QualType ParamTypes[2] = {EnumTy, EnumTy};
9950 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9951 }
9952 }
9953 }
9954
9955 // C++ [over.built]p13:
9956 //
9957 // For every cv-qualified or cv-unqualified object type T
9958 // there exist candidate operator functions of the form
9959 //
9960 // T* operator+(T*, ptrdiff_t);
9961 // T& operator[](T*, ptrdiff_t); [BELOW]
9962 // T* operator-(T*, ptrdiff_t);
9963 // T* operator+(ptrdiff_t, T*);
9964 // T& operator[](ptrdiff_t, T*); [BELOW]
9965 //
9966 // C++ [over.built]p14:
9967 //
9968 // For every T, where T is a pointer to object type, there
9969 // exist candidate operator functions of the form
9970 //
9971 // ptrdiff_t operator-(T, T);
9972 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9973 /// Set of (canonical) types that we've already handled.
9974 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9975
9976 for (int Arg = 0; Arg < 2; ++Arg) {
9977 QualType AsymmetricParamTypes[2] = {
9980 };
9981 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9982 QualType PointeeTy = PtrTy->getPointeeType();
9983 if (!PointeeTy->isObjectType())
9984 continue;
9985
9986 AsymmetricParamTypes[Arg] = PtrTy;
9987 if (Arg == 0 || Op == OO_Plus) {
9988 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9989 // T* operator+(ptrdiff_t, T*);
9990 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9991 }
9992 if (Op == OO_Minus) {
9993 // ptrdiff_t operator-(T, T);
9994 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9995 continue;
9996
9997 QualType ParamTypes[2] = {PtrTy, PtrTy};
9998 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9999 }
10000 }
10001 }
10002 }
10003
10004 // C++ [over.built]p12:
10005 //
10006 // For every pair of promoted arithmetic types L and R, there
10007 // exist candidate operator functions of the form
10008 //
10009 // LR operator*(L, R);
10010 // LR operator/(L, R);
10011 // LR operator+(L, R);
10012 // LR operator-(L, R);
10013 // bool operator<(L, R);
10014 // bool operator>(L, R);
10015 // bool operator<=(L, R);
10016 // bool operator>=(L, R);
10017 // bool operator==(L, R);
10018 // bool operator!=(L, R);
10019 //
10020 // where LR is the result of the usual arithmetic conversions
10021 // between types L and R.
10022 //
10023 // C++ [over.built]p24:
10024 //
10025 // For every pair of promoted arithmetic types L and R, there exist
10026 // candidate operator functions of the form
10027 //
10028 // LR operator?(bool, L, R);
10029 //
10030 // where LR is the result of the usual arithmetic conversions
10031 // between types L and R.
10032 // Our candidates ignore the first parameter.
10033 void addGenericBinaryArithmeticOverloads() {
10034 if (!HasArithmeticOrEnumeralCandidateType)
10035 return;
10036
10037 for (unsigned Left = FirstPromotedArithmeticType;
10038 Left < LastPromotedArithmeticType; ++Left) {
10039 for (unsigned Right = FirstPromotedArithmeticType;
10040 Right < LastPromotedArithmeticType; ++Right) {
10041 QualType LandR[2] = { ArithmeticTypes[Left],
10042 ArithmeticTypes[Right] };
10043 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10044 }
10045 }
10046
10047 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10048 // conditional operator for vector types.
10049 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10050 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10051 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10052 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10053 }
10054 }
10055
10056 /// Add binary operator overloads for each candidate matrix type M1, M2:
10057 /// * (M1, M1) -> M1
10058 /// * (M1, M1.getElementType()) -> M1
10059 /// * (M2.getElementType(), M2) -> M2
10060 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10061 void addMatrixBinaryArithmeticOverloads() {
10062 if (!HasArithmeticOrEnumeralCandidateType)
10063 return;
10064
10065 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10066 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10067 AddCandidate(M1, M1);
10068 }
10069
10070 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10071 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10072 if (!CandidateTypes[0].containsMatrixType(M2))
10073 AddCandidate(M2, M2);
10074 }
10075 }
10076
10077 // C++2a [over.built]p14:
10078 //
10079 // For every integral type T there exists a candidate operator function
10080 // of the form
10081 //
10082 // std::strong_ordering operator<=>(T, T)
10083 //
10084 // C++2a [over.built]p15:
10085 //
10086 // For every pair of floating-point types L and R, there exists a candidate
10087 // operator function of the form
10088 //
10089 // std::partial_ordering operator<=>(L, R);
10090 //
10091 // FIXME: The current specification for integral types doesn't play nice with
10092 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10093 // comparisons. Under the current spec this can lead to ambiguity during
10094 // overload resolution. For example:
10095 //
10096 // enum A : int {a};
10097 // auto x = (a <=> (long)42);
10098 //
10099 // error: call is ambiguous for arguments 'A' and 'long'.
10100 // note: candidate operator<=>(int, int)
10101 // note: candidate operator<=>(long, long)
10102 //
10103 // To avoid this error, this function deviates from the specification and adds
10104 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10105 // arithmetic types (the same as the generic relational overloads).
10106 //
10107 // For now this function acts as a placeholder.
10108 void addThreeWayArithmeticOverloads() {
10109 addGenericBinaryArithmeticOverloads();
10110 }
10111
10112 // C++ [over.built]p17:
10113 //
10114 // For every pair of promoted integral types L and R, there
10115 // exist candidate operator functions of the form
10116 //
10117 // LR operator%(L, R);
10118 // LR operator&(L, R);
10119 // LR operator^(L, R);
10120 // LR operator|(L, R);
10121 // L operator<<(L, R);
10122 // L operator>>(L, R);
10123 //
10124 // where LR is the result of the usual arithmetic conversions
10125 // between types L and R.
10126 void addBinaryBitwiseArithmeticOverloads() {
10127 if (!HasArithmeticOrEnumeralCandidateType)
10128 return;
10129
10130 for (unsigned Left = FirstPromotedIntegralType;
10131 Left < LastPromotedIntegralType; ++Left) {
10132 for (unsigned Right = FirstPromotedIntegralType;
10133 Right < LastPromotedIntegralType; ++Right) {
10134 QualType LandR[2] = { ArithmeticTypes[Left],
10135 ArithmeticTypes[Right] };
10136 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10137 }
10138 }
10139 }
10140
10141 // C++ [over.built]p20:
10142 //
10143 // For every pair (T, VQ), where T is an enumeration or
10144 // pointer to member type and VQ is either volatile or
10145 // empty, there exist candidate operator functions of the form
10146 //
10147 // VQ T& operator=(VQ T&, T);
10148 void addAssignmentMemberPointerOrEnumeralOverloads() {
10149 /// Set of (canonical) types that we've already handled.
10150 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10151
10152 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10153 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10154 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10155 continue;
10156
10157 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10158 }
10159
10160 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10161 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10162 continue;
10163
10164 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10165 }
10166 }
10167 }
10168
10169 // C++ [over.built]p19:
10170 //
10171 // For every pair (T, VQ), where T is any type and VQ is either
10172 // volatile or empty, there exist candidate operator functions
10173 // of the form
10174 //
10175 // T*VQ& operator=(T*VQ&, T*);
10176 //
10177 // C++ [over.built]p21:
10178 //
10179 // For every pair (T, VQ), where T is a cv-qualified or
10180 // cv-unqualified object type and VQ is either volatile or
10181 // empty, there exist candidate operator functions of the form
10182 //
10183 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10184 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10185 void addAssignmentPointerOverloads(bool isEqualOp) {
10186 /// Set of (canonical) types that we've already handled.
10187 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10188
10189 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10190 // If this is operator=, keep track of the builtin candidates we added.
10191 if (isEqualOp)
10192 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10193 else if (!PtrTy->getPointeeType()->isObjectType())
10194 continue;
10195
10196 // non-volatile version
10197 QualType ParamTypes[2] = {
10199 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10200 };
10201 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10202 /*IsAssignmentOperator=*/ isEqualOp);
10203
10204 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10205 VisibleTypeConversionsQuals.hasVolatile();
10206 if (NeedVolatile) {
10207 // volatile version
10208 ParamTypes[0] =
10210 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10211 /*IsAssignmentOperator=*/isEqualOp);
10212 }
10213
10214 if (!PtrTy.isRestrictQualified() &&
10215 VisibleTypeConversionsQuals.hasRestrict()) {
10216 // restrict version
10217 ParamTypes[0] =
10219 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10220 /*IsAssignmentOperator=*/isEqualOp);
10221
10222 if (NeedVolatile) {
10223 // volatile restrict version
10224 ParamTypes[0] =
10227 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10228 /*IsAssignmentOperator=*/isEqualOp);
10229 }
10230 }
10231 }
10232
10233 if (isEqualOp) {
10234 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10235 // Make sure we don't add the same candidate twice.
10236 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10237 continue;
10238
10239 QualType ParamTypes[2] = {
10241 PtrTy,
10242 };
10243
10244 // non-volatile version
10245 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10246 /*IsAssignmentOperator=*/true);
10247
10248 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10249 VisibleTypeConversionsQuals.hasVolatile();
10250 if (NeedVolatile) {
10251 // volatile version
10252 ParamTypes[0] = S.Context.getLValueReferenceType(
10253 S.Context.getVolatileType(PtrTy));
10254 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10255 /*IsAssignmentOperator=*/true);
10256 }
10257
10258 if (!PtrTy.isRestrictQualified() &&
10259 VisibleTypeConversionsQuals.hasRestrict()) {
10260 // restrict version
10261 ParamTypes[0] = S.Context.getLValueReferenceType(
10262 S.Context.getRestrictType(PtrTy));
10263 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10264 /*IsAssignmentOperator=*/true);
10265
10266 if (NeedVolatile) {
10267 // volatile restrict version
10268 ParamTypes[0] =
10271 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10272 /*IsAssignmentOperator=*/true);
10273 }
10274 }
10275 }
10276 }
10277 }
10278
10279 // C++ [over.built]p18:
10280 //
10281 // For every triple (L, VQ, R), where L is an arithmetic type,
10282 // VQ is either volatile or empty, and R is a promoted
10283 // arithmetic type, there exist candidate operator functions of
10284 // the form
10285 //
10286 // VQ L& operator=(VQ L&, R);
10287 // VQ L& operator*=(VQ L&, R);
10288 // VQ L& operator/=(VQ L&, R);
10289 // VQ L& operator+=(VQ L&, R);
10290 // VQ L& operator-=(VQ L&, R);
10291 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10292 if (!HasArithmeticOrEnumeralCandidateType)
10293 return;
10294
10295 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10296 for (unsigned Right = FirstPromotedArithmeticType;
10297 Right < LastPromotedArithmeticType; ++Right) {
10298 QualType ParamTypes[2];
10299 ParamTypes[1] = ArithmeticTypes[Right];
10301 S, ArithmeticTypes[Left], Args[0]);
10302
10304 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10305 ParamTypes[0] =
10306 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10307 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10308 /*IsAssignmentOperator=*/isEqualOp);
10309 });
10310 }
10311 }
10312
10313 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10314 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10315 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10316 QualType ParamTypes[2];
10317 ParamTypes[1] = Vec2Ty;
10318 // Add this built-in operator as a candidate (VQ is empty).
10319 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10320 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10321 /*IsAssignmentOperator=*/isEqualOp);
10322
10323 // Add this built-in operator as a candidate (VQ is 'volatile').
10324 if (VisibleTypeConversionsQuals.hasVolatile()) {
10325 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10326 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10327 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10328 /*IsAssignmentOperator=*/isEqualOp);
10329 }
10330 }
10331 }
10332
10333 // C++ [over.built]p22:
10334 //
10335 // For every triple (L, VQ, R), where L is an integral type, VQ
10336 // is either volatile or empty, and R is a promoted integral
10337 // type, there exist candidate operator functions of the form
10338 //
10339 // VQ L& operator%=(VQ L&, R);
10340 // VQ L& operator<<=(VQ L&, R);
10341 // VQ L& operator>>=(VQ L&, R);
10342 // VQ L& operator&=(VQ L&, R);
10343 // VQ L& operator^=(VQ L&, R);
10344 // VQ L& operator|=(VQ L&, R);
10345 void addAssignmentIntegralOverloads() {
10346 if (!HasArithmeticOrEnumeralCandidateType)
10347 return;
10348
10349 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10350 for (unsigned Right = FirstPromotedIntegralType;
10351 Right < LastPromotedIntegralType; ++Right) {
10352 QualType ParamTypes[2];
10353 ParamTypes[1] = ArithmeticTypes[Right];
10355 S, ArithmeticTypes[Left], Args[0]);
10356
10358 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10359 ParamTypes[0] =
10360 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10361 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10362 });
10363 }
10364 }
10365 }
10366
10367 // C++ [over.operator]p23:
10368 //
10369 // There also exist candidate operator functions of the form
10370 //
10371 // bool operator!(bool);
10372 // bool operator&&(bool, bool);
10373 // bool operator||(bool, bool);
10374 void addExclaimOverload() {
10375 QualType ParamTy = S.Context.BoolTy;
10376 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10377 /*IsAssignmentOperator=*/false,
10378 /*NumContextualBoolArguments=*/1);
10379 }
10380 void addAmpAmpOrPipePipeOverload() {
10381 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10382 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10383 /*IsAssignmentOperator=*/false,
10384 /*NumContextualBoolArguments=*/2);
10385 }
10386
10387 // C++ [over.built]p13:
10388 //
10389 // For every cv-qualified or cv-unqualified object type T there
10390 // exist candidate operator functions of the form
10391 //
10392 // T* operator+(T*, ptrdiff_t); [ABOVE]
10393 // T& operator[](T*, ptrdiff_t);
10394 // T* operator-(T*, ptrdiff_t); [ABOVE]
10395 // T* operator+(ptrdiff_t, T*); [ABOVE]
10396 // T& operator[](ptrdiff_t, T*);
10397 void addSubscriptOverloads() {
10398 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10399 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10400 QualType PointeeType = PtrTy->getPointeeType();
10401 if (!PointeeType->isObjectType())
10402 continue;
10403
10404 // T& operator[](T*, ptrdiff_t)
10405 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10406 }
10407
10408 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10409 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10410 QualType PointeeType = PtrTy->getPointeeType();
10411 if (!PointeeType->isObjectType())
10412 continue;
10413
10414 // T& operator[](ptrdiff_t, T*)
10415 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10416 }
10417 }
10418
10419 // C++ [over.built]p11:
10420 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10421 // C1 is the same type as C2 or is a derived class of C2, T is an object
10422 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10423 // there exist candidate operator functions of the form
10424 //
10425 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10426 //
10427 // where CV12 is the union of CV1 and CV2.
10428 void addArrowStarOverloads() {
10429 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10430 QualType C1Ty = PtrTy;
10431 QualType C1;
10432 QualifierCollector Q1;
10433 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10434 if (!isa<RecordType>(C1))
10435 continue;
10436 // heuristic to reduce number of builtin candidates in the set.
10437 // Add volatile/restrict version only if there are conversions to a
10438 // volatile/restrict type.
10439 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10440 continue;
10441 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10442 continue;
10443 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10444 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10445 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10446 *D2 = mptr->getMostRecentCXXRecordDecl();
10447 if (!declaresSameEntity(D1, D2) &&
10448 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10449 break;
10450 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10451 // build CV12 T&
10452 QualType T = mptr->getPointeeType();
10453 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10454 T.isVolatileQualified())
10455 continue;
10456 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10457 T.isRestrictQualified())
10458 continue;
10459 T = Q1.apply(S.Context, T);
10460 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10461 }
10462 }
10463 }
10464
10465 // Note that we don't consider the first argument, since it has been
10466 // contextually converted to bool long ago. The candidates below are
10467 // therefore added as binary.
10468 //
10469 // C++ [over.built]p25:
10470 // For every type T, where T is a pointer, pointer-to-member, or scoped
10471 // enumeration type, there exist candidate operator functions of the form
10472 //
10473 // T operator?(bool, T, T);
10474 //
10475 void addConditionalOperatorOverloads() {
10476 /// Set of (canonical) types that we've already handled.
10477 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10478
10479 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10480 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10481 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10482 continue;
10483
10484 QualType ParamTypes[2] = {PtrTy, PtrTy};
10485 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10486 }
10487
10488 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10489 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10490 continue;
10491
10492 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10493 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10494 }
10495
10496 if (S.getLangOpts().CPlusPlus11) {
10497 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10498 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10499 continue;
10500
10501 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10502 continue;
10503
10504 QualType ParamTypes[2] = {EnumTy, EnumTy};
10505 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10506 }
10507 }
10508 }
10509 }
10510};
10511
10512} // end anonymous namespace
10513
10515 SourceLocation OpLoc,
10516 ArrayRef<Expr *> Args,
10517 OverloadCandidateSet &CandidateSet) {
10518 // Find all of the types that the arguments can convert to, but only
10519 // if the operator we're looking at has built-in operator candidates
10520 // that make use of these types. Also record whether we encounter non-record
10521 // candidate types or either arithmetic or enumeral candidate types.
10522 QualifiersAndAtomic VisibleTypeConversionsQuals;
10523 VisibleTypeConversionsQuals.addConst();
10524 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10525 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10526 if (Args[ArgIdx]->getType()->isAtomicType())
10527 VisibleTypeConversionsQuals.addAtomic();
10528 }
10529
10530 bool HasNonRecordCandidateType = false;
10531 bool HasArithmeticOrEnumeralCandidateType = false;
10533 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10534 CandidateTypes.emplace_back(*this);
10535 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10536 OpLoc,
10537 true,
10538 (Op == OO_Exclaim ||
10539 Op == OO_AmpAmp ||
10540 Op == OO_PipePipe),
10541 VisibleTypeConversionsQuals);
10542 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10543 CandidateTypes[ArgIdx].hasNonRecordTypes();
10544 HasArithmeticOrEnumeralCandidateType =
10545 HasArithmeticOrEnumeralCandidateType ||
10546 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10547 }
10548
10549 // Exit early when no non-record types have been added to the candidate set
10550 // for any of the arguments to the operator.
10551 //
10552 // We can't exit early for !, ||, or &&, since there we have always have
10553 // 'bool' overloads.
10554 if (!HasNonRecordCandidateType &&
10555 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10556 return;
10557
10558 // Setup an object to manage the common state for building overloads.
10559 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10560 VisibleTypeConversionsQuals,
10561 HasArithmeticOrEnumeralCandidateType,
10562 CandidateTypes, CandidateSet);
10563
10564 // Dispatch over the operation to add in only those overloads which apply.
10565 switch (Op) {
10566 case OO_None:
10568 llvm_unreachable("Expected an overloaded operator");
10569
10570 case OO_New:
10571 case OO_Delete:
10572 case OO_Array_New:
10573 case OO_Array_Delete:
10574 case OO_Call:
10575 llvm_unreachable(
10576 "Special operators don't use AddBuiltinOperatorCandidates");
10577
10578 case OO_Comma:
10579 case OO_Arrow:
10580 case OO_Coawait:
10581 // C++ [over.match.oper]p3:
10582 // -- For the operator ',', the unary operator '&', the
10583 // operator '->', or the operator 'co_await', the
10584 // built-in candidates set is empty.
10585 break;
10586
10587 case OO_Plus: // '+' is either unary or binary
10588 if (Args.size() == 1)
10589 OpBuilder.addUnaryPlusPointerOverloads();
10590 [[fallthrough]];
10591
10592 case OO_Minus: // '-' is either unary or binary
10593 if (Args.size() == 1) {
10594 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10595 } else {
10596 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10597 OpBuilder.addGenericBinaryArithmeticOverloads();
10598 OpBuilder.addMatrixBinaryArithmeticOverloads();
10599 }
10600 break;
10601
10602 case OO_Star: // '*' is either unary or binary
10603 if (Args.size() == 1)
10604 OpBuilder.addUnaryStarPointerOverloads();
10605 else {
10606 OpBuilder.addGenericBinaryArithmeticOverloads();
10607 OpBuilder.addMatrixBinaryArithmeticOverloads();
10608 }
10609 break;
10610
10611 case OO_Slash:
10612 OpBuilder.addGenericBinaryArithmeticOverloads();
10613 break;
10614
10615 case OO_PlusPlus:
10616 case OO_MinusMinus:
10617 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10618 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10619 break;
10620
10621 case OO_EqualEqual:
10622 case OO_ExclaimEqual:
10623 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10624 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10625 OpBuilder.addGenericBinaryArithmeticOverloads();
10626 break;
10627
10628 case OO_Less:
10629 case OO_Greater:
10630 case OO_LessEqual:
10631 case OO_GreaterEqual:
10632 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10633 OpBuilder.addGenericBinaryArithmeticOverloads();
10634 break;
10635
10636 case OO_Spaceship:
10637 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10638 OpBuilder.addThreeWayArithmeticOverloads();
10639 break;
10640
10641 case OO_Percent:
10642 case OO_Caret:
10643 case OO_Pipe:
10644 case OO_LessLess:
10645 case OO_GreaterGreater:
10646 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10647 break;
10648
10649 case OO_Amp: // '&' is either unary or binary
10650 if (Args.size() == 1)
10651 // C++ [over.match.oper]p3:
10652 // -- For the operator ',', the unary operator '&', or the
10653 // operator '->', the built-in candidates set is empty.
10654 break;
10655
10656 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10657 break;
10658
10659 case OO_Tilde:
10660 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10661 break;
10662
10663 case OO_Equal:
10664 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10665 [[fallthrough]];
10666
10667 case OO_PlusEqual:
10668 case OO_MinusEqual:
10669 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10670 [[fallthrough]];
10671
10672 case OO_StarEqual:
10673 case OO_SlashEqual:
10674 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10675 break;
10676
10677 case OO_PercentEqual:
10678 case OO_LessLessEqual:
10679 case OO_GreaterGreaterEqual:
10680 case OO_AmpEqual:
10681 case OO_CaretEqual:
10682 case OO_PipeEqual:
10683 OpBuilder.addAssignmentIntegralOverloads();
10684 break;
10685
10686 case OO_Exclaim:
10687 OpBuilder.addExclaimOverload();
10688 break;
10689
10690 case OO_AmpAmp:
10691 case OO_PipePipe:
10692 OpBuilder.addAmpAmpOrPipePipeOverload();
10693 break;
10694
10695 case OO_Subscript:
10696 if (Args.size() == 2)
10697 OpBuilder.addSubscriptOverloads();
10698 break;
10699
10700 case OO_ArrowStar:
10701 OpBuilder.addArrowStarOverloads();
10702 break;
10703
10704 case OO_Conditional:
10705 OpBuilder.addConditionalOperatorOverloads();
10706 OpBuilder.addGenericBinaryArithmeticOverloads();
10707 break;
10708 }
10709}
10710
10711void
10713 SourceLocation Loc,
10714 ArrayRef<Expr *> Args,
10715 TemplateArgumentListInfo *ExplicitTemplateArgs,
10716 OverloadCandidateSet& CandidateSet,
10717 bool PartialOverloading) {
10718 ADLResult Fns;
10719
10720 // FIXME: This approach for uniquing ADL results (and removing
10721 // redundant candidates from the set) relies on pointer-equality,
10722 // which means we need to key off the canonical decl. However,
10723 // always going back to the canonical decl might not get us the
10724 // right set of default arguments. What default arguments are
10725 // we supposed to consider on ADL candidates, anyway?
10726
10727 // FIXME: Pass in the explicit template arguments?
10728 ArgumentDependentLookup(Name, Loc, Args, Fns);
10729
10730 ArrayRef<Expr *> ReversedArgs;
10731
10732 // Erase all of the candidates we already knew about.
10733 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10734 CandEnd = CandidateSet.end();
10735 Cand != CandEnd; ++Cand)
10736 if (Cand->Function) {
10737 FunctionDecl *Fn = Cand->Function;
10738 Fns.erase(Fn);
10739 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10740 Fns.erase(FunTmpl);
10741 }
10742
10743 // For each of the ADL candidates we found, add it to the overload
10744 // set.
10745 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10747
10748 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10749 if (ExplicitTemplateArgs)
10750 continue;
10751
10753 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10754 PartialOverloading, /*AllowExplicit=*/true,
10755 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10756 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10758 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10759 /*SuppressUserConversions=*/false, PartialOverloading,
10760 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10761 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10762 }
10763 } else {
10764 auto *FTD = cast<FunctionTemplateDecl>(*I);
10766 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10767 /*SuppressUserConversions=*/false, PartialOverloading,
10768 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10769 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10770 *this, Args, FTD->getTemplatedDecl())) {
10771
10772 // As template candidates are not deduced immediately,
10773 // persist the array in the overload set.
10774 if (ReversedArgs.empty())
10775 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10776
10778 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10779 /*SuppressUserConversions=*/false, PartialOverloading,
10780 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10782 }
10783 }
10784 }
10785}
10786
10787namespace {
10788enum class Comparison { Equal, Better, Worse };
10789}
10790
10791/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10792/// overload resolution.
10793///
10794/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10795/// Cand1's first N enable_if attributes have precisely the same conditions as
10796/// Cand2's first N enable_if attributes (where N = the number of enable_if
10797/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10798///
10799/// Note that you can have a pair of candidates such that Cand1's enable_if
10800/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10801/// worse than Cand1's.
10802static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10803 const FunctionDecl *Cand2) {
10804 // Common case: One (or both) decls don't have enable_if attrs.
10805 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10806 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10807 if (!Cand1Attr || !Cand2Attr) {
10808 if (Cand1Attr == Cand2Attr)
10809 return Comparison::Equal;
10810 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10811 }
10812
10813 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10814 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10815
10816 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10817 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10818 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10819 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10820
10821 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10822 // has fewer enable_if attributes than Cand2, and vice versa.
10823 if (!Cand1A)
10824 return Comparison::Worse;
10825 if (!Cand2A)
10826 return Comparison::Better;
10827
10828 Cand1ID.clear();
10829 Cand2ID.clear();
10830
10831 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10832 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10833 if (Cand1ID != Cand2ID)
10834 return Comparison::Worse;
10835 }
10836
10837 return Comparison::Equal;
10838}
10839
10840static Comparison
10842 const OverloadCandidate &Cand2) {
10843 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10844 !Cand2.Function->isMultiVersion())
10845 return Comparison::Equal;
10846
10847 // If both are invalid, they are equal. If one of them is invalid, the other
10848 // is better.
10849 if (Cand1.Function->isInvalidDecl()) {
10850 if (Cand2.Function->isInvalidDecl())
10851 return Comparison::Equal;
10852 return Comparison::Worse;
10853 }
10854 if (Cand2.Function->isInvalidDecl())
10855 return Comparison::Better;
10856
10857 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10858 // cpu_dispatch, else arbitrarily based on the identifiers.
10859 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10860 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10861 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10862 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10863
10864 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10865 return Comparison::Equal;
10866
10867 if (Cand1CPUDisp && !Cand2CPUDisp)
10868 return Comparison::Better;
10869 if (Cand2CPUDisp && !Cand1CPUDisp)
10870 return Comparison::Worse;
10871
10872 if (Cand1CPUSpec && Cand2CPUSpec) {
10873 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10874 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10875 ? Comparison::Better
10876 : Comparison::Worse;
10877
10878 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10879 FirstDiff = std::mismatch(
10880 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10881 Cand2CPUSpec->cpus_begin(),
10882 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10883 return LHS->getName() == RHS->getName();
10884 });
10885
10886 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10887 "Two different cpu-specific versions should not have the same "
10888 "identifier list, otherwise they'd be the same decl!");
10889 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10890 ? Comparison::Better
10891 : Comparison::Worse;
10892 }
10893 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10894}
10895
10896/// Compute the type of the implicit object parameter for the given function,
10897/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10898/// null QualType if there is a 'matches anything' implicit object parameter.
10899static std::optional<QualType>
10902 return std::nullopt;
10903
10904 auto *M = cast<CXXMethodDecl>(F);
10905 // Static member functions' object parameters match all types.
10906 if (M->isStatic())
10907 return QualType();
10908 return M->getFunctionObjectParameterReferenceType();
10909}
10910
10911// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10912// represent the same entity.
10913static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10914 const FunctionDecl *F2) {
10915 if (declaresSameEntity(F1, F2))
10916 return true;
10917 auto PT1 = F1->getPrimaryTemplate();
10918 auto PT2 = F2->getPrimaryTemplate();
10919 if (PT1 && PT2) {
10920 if (declaresSameEntity(PT1, PT2) ||
10921 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10922 PT2->getInstantiatedFromMemberTemplate()))
10923 return true;
10924 }
10925 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10926 // different functions with same params). Consider removing this (as no test
10927 // fail w/o it).
10928 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10929 if (First) {
10930 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10931 return *T;
10932 }
10933 assert(I < F->getNumParams());
10934 return F->getParamDecl(I++)->getType();
10935 };
10936
10937 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10938 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10939
10940 if (F1NumParams != F2NumParams)
10941 return false;
10942
10943 unsigned I1 = 0, I2 = 0;
10944 for (unsigned I = 0; I != F1NumParams; ++I) {
10945 QualType T1 = NextParam(F1, I1, I == 0);
10946 QualType T2 = NextParam(F2, I2, I == 0);
10947 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10948 if (!Context.hasSameUnqualifiedType(T1, T2))
10949 return false;
10950 }
10951 return true;
10952}
10953
10954/// We're allowed to use constraints partial ordering only if the candidates
10955/// have the same parameter types:
10956/// [over.match.best.general]p2.6
10957/// F1 and F2 are non-template functions with the same
10958/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10960 FunctionDecl *Fn2,
10961 bool IsFn1Reversed,
10962 bool IsFn2Reversed) {
10963 assert(Fn1 && Fn2);
10964 if (Fn1->isVariadic() != Fn2->isVariadic())
10965 return false;
10966
10967 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10968 IsFn1Reversed ^ IsFn2Reversed))
10969 return false;
10970
10971 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10972 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10973 if (Mem1 && Mem2) {
10974 // if they are member functions, both are direct members of the same class,
10975 // and
10976 if (Mem1->getParent() != Mem2->getParent())
10977 return false;
10978 // if both are non-static member functions, they have the same types for
10979 // their object parameters
10980 if (Mem1->isInstance() && Mem2->isInstance() &&
10982 Mem1->getFunctionObjectParameterReferenceType(),
10983 Mem2->getFunctionObjectParameterReferenceType()))
10984 return false;
10985 }
10986 return true;
10987}
10988
10989static FunctionDecl *
10991 bool IsFn1Reversed, bool IsFn2Reversed) {
10992 if (!Fn1 || !Fn2)
10993 return nullptr;
10994
10995 // C++ [temp.constr.order]:
10996 // A non-template function F1 is more partial-ordering-constrained than a
10997 // non-template function F2 if:
10998 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10999 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
11000
11001 if (Cand1IsSpecialization || Cand2IsSpecialization)
11002 return nullptr;
11003
11004 // - they have the same non-object-parameter-type-lists, and [...]
11005 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
11006 IsFn2Reversed))
11007 return nullptr;
11008
11009 // - the declaration of F1 is more constrained than the declaration of F2.
11010 return S.getMoreConstrainedFunction(Fn1, Fn2);
11011}
11012
11013/// isBetterOverloadCandidate - Determines whether the first overload
11014/// candidate is a better candidate than the second (C++ 13.3.3p1).
11016 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
11018 bool PartialOverloading) {
11019 // Define viable functions to be better candidates than non-viable
11020 // functions.
11021 if (!Cand2.Viable)
11022 return Cand1.Viable;
11023 else if (!Cand1.Viable)
11024 return false;
11025
11026 // [CUDA] A function with 'never' preference is marked not viable, therefore
11027 // is never shown up here. The worst preference shown up here is 'wrong side',
11028 // e.g. an H function called by a HD function in device compilation. This is
11029 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11030 // function which is called only by an H function. A deferred diagnostic will
11031 // be triggered if it is emitted. However a wrong-sided function is still
11032 // a viable candidate here.
11033 //
11034 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11035 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11036 // can be emitted, Cand1 is not better than Cand2. This rule should have
11037 // precedence over other rules.
11038 //
11039 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11040 // other rules should be used to determine which is better. This is because
11041 // host/device based overloading resolution is mostly for determining
11042 // viability of a function. If two functions are both viable, other factors
11043 // should take precedence in preference, e.g. the standard-defined preferences
11044 // like argument conversion ranks or enable_if partial-ordering. The
11045 // preference for pass-object-size parameters is probably most similar to a
11046 // type-based-overloading decision and so should take priority.
11047 //
11048 // If other rules cannot determine which is better, CUDA preference will be
11049 // used again to determine which is better.
11050 //
11051 // TODO: Currently IdentifyPreference does not return correct values
11052 // for functions called in global variable initializers due to missing
11053 // correct context about device/host. Therefore we can only enforce this
11054 // rule when there is a caller. We should enforce this rule for functions
11055 // in global variable initializers once proper context is added.
11056 //
11057 // TODO: We can only enable the hostness based overloading resolution when
11058 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11059 // overloading resolution diagnostics.
11060 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11061 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11062 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11063 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11064 bool IsCand1ImplicitHD =
11066 bool IsCand2ImplicitHD =
11068 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11069 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11070 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11071 // The implicit HD function may be a function in a system header which
11072 // is forced by pragma. In device compilation, if we prefer HD candidates
11073 // over wrong-sided candidates, overloading resolution may change, which
11074 // may result in non-deferrable diagnostics. As a workaround, we let
11075 // implicit HD candidates take equal preference as wrong-sided candidates.
11076 // This will preserve the overloading resolution.
11077 // TODO: We still need special handling of implicit HD functions since
11078 // they may incur other diagnostics to be deferred. We should make all
11079 // host/device related diagnostics deferrable and remove special handling
11080 // of implicit HD functions.
11081 auto EmitThreshold =
11082 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11083 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11086 auto Cand1Emittable = P1 > EmitThreshold;
11087 auto Cand2Emittable = P2 > EmitThreshold;
11088 if (Cand1Emittable && !Cand2Emittable)
11089 return true;
11090 if (!Cand1Emittable && Cand2Emittable)
11091 return false;
11092 }
11093 }
11094
11095 // C++ [over.match.best]p1: (Changed in C++23)
11096 //
11097 // -- if F is a static member function, ICS1(F) is defined such
11098 // that ICS1(F) is neither better nor worse than ICS1(G) for
11099 // any function G, and, symmetrically, ICS1(G) is neither
11100 // better nor worse than ICS1(F).
11101 unsigned StartArg = 0;
11102 if (!Cand1.TookAddressOfOverload &&
11104 StartArg = 1;
11105
11106 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11107 // We don't allow incompatible pointer conversions in C++.
11108 if (!S.getLangOpts().CPlusPlus)
11109 return ICS.isStandard() &&
11110 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11111
11112 // The only ill-formed conversion we allow in C++ is the string literal to
11113 // char* conversion, which is only considered ill-formed after C++11.
11114 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11116 };
11117
11118 // Define functions that don't require ill-formed conversions for a given
11119 // argument to be better candidates than functions that do.
11120 unsigned NumArgs = Cand1.Conversions.size();
11121 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11122 bool HasBetterConversion = false;
11123 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11124 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11125 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11126 if (Cand1Bad != Cand2Bad) {
11127 if (Cand1Bad)
11128 return false;
11129 HasBetterConversion = true;
11130 }
11131 }
11132
11133 if (HasBetterConversion)
11134 return true;
11135
11136 // C++ [over.match.best]p1:
11137 // A viable function F1 is defined to be a better function than another
11138 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11139 // conversion sequence than ICSi(F2), and then...
11140 bool HasWorseConversion = false;
11141 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11143 Cand1.Conversions[ArgIdx],
11144 Cand2.Conversions[ArgIdx])) {
11146 // Cand1 has a better conversion sequence.
11147 HasBetterConversion = true;
11148 break;
11149
11151 if (Cand1.Function && Cand2.Function &&
11152 Cand1.isReversed() != Cand2.isReversed() &&
11153 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11154 // Work around large-scale breakage caused by considering reversed
11155 // forms of operator== in C++20:
11156 //
11157 // When comparing a function against a reversed function, if we have a
11158 // better conversion for one argument and a worse conversion for the
11159 // other, the implicit conversion sequences are treated as being equally
11160 // good.
11161 //
11162 // This prevents a comparison function from being considered ambiguous
11163 // with a reversed form that is written in the same way.
11164 //
11165 // We diagnose this as an extension from CreateOverloadedBinOp.
11166 HasWorseConversion = true;
11167 break;
11168 }
11169
11170 // Cand1 can't be better than Cand2.
11171 return false;
11172
11174 // Do nothing.
11175 break;
11176 }
11177 }
11178
11179 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11180 // ICSj(F2), or, if not that,
11181 if (HasBetterConversion && !HasWorseConversion)
11182 return true;
11183
11184 // -- the context is an initialization by user-defined conversion
11185 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11186 // from the return type of F1 to the destination type (i.e.,
11187 // the type of the entity being initialized) is a better
11188 // conversion sequence than the standard conversion sequence
11189 // from the return type of F2 to the destination type.
11191 Cand1.Function && Cand2.Function &&
11194
11195 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11196 // First check whether we prefer one of the conversion functions over the
11197 // other. This only distinguishes the results in non-standard, extension
11198 // cases such as the conversion from a lambda closure type to a function
11199 // pointer or block.
11204 Cand1.FinalConversion,
11205 Cand2.FinalConversion);
11206
11209
11210 // FIXME: Compare kind of reference binding if conversion functions
11211 // convert to a reference type used in direct reference binding, per
11212 // C++14 [over.match.best]p1 section 2 bullet 3.
11213 }
11214
11215 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11216 // as combined with the resolution to CWG issue 243.
11217 //
11218 // When the context is initialization by constructor ([over.match.ctor] or
11219 // either phase of [over.match.list]), a constructor is preferred over
11220 // a conversion function.
11221 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11222 Cand1.Function && Cand2.Function &&
11225 return isa<CXXConstructorDecl>(Cand1.Function);
11226
11227 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11228 return Cand2.StrictPackMatch;
11229
11230 // -- F1 is a non-template function and F2 is a function template
11231 // specialization, or, if not that,
11232 bool Cand1IsSpecialization = Cand1.Function &&
11234 bool Cand2IsSpecialization = Cand2.Function &&
11236 if (Cand1IsSpecialization != Cand2IsSpecialization)
11237 return Cand2IsSpecialization;
11238
11239 // -- F1 and F2 are function template specializations, and the function
11240 // template for F1 is more specialized than the template for F2
11241 // according to the partial ordering rules described in 14.5.5.2, or,
11242 // if not that,
11243 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11244 const auto *Obj1Context =
11245 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11246 const auto *Obj2Context =
11247 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11248 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11250 Cand2.Function->getPrimaryTemplate(), Loc,
11252 : TPOC_Call,
11254 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11255 : QualType{},
11256 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11257 : QualType{},
11258 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11259 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11260 }
11261 }
11262
11263 // -— F1 and F2 are non-template functions and F1 is more
11264 // partial-ordering-constrained than F2 [...],
11266 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11267 Cand2.isReversed());
11268 F && F == Cand1.Function)
11269 return true;
11270
11271 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11272 // class B of D, and for all arguments the corresponding parameters of
11273 // F1 and F2 have the same type.
11274 // FIXME: Implement the "all parameters have the same type" check.
11275 bool Cand1IsInherited =
11276 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11277 bool Cand2IsInherited =
11278 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11279 if (Cand1IsInherited != Cand2IsInherited)
11280 return Cand2IsInherited;
11281 else if (Cand1IsInherited) {
11282 assert(Cand2IsInherited);
11283 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11284 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11285 if (Cand1Class->isDerivedFrom(Cand2Class))
11286 return true;
11287 if (Cand2Class->isDerivedFrom(Cand1Class))
11288 return false;
11289 // Inherited from sibling base classes: still ambiguous.
11290 }
11291
11292 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11293 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11294 // with reversed order of parameters and F1 is not
11295 //
11296 // We rank reversed + different operator as worse than just reversed, but
11297 // that comparison can never happen, because we only consider reversing for
11298 // the maximally-rewritten operator (== or <=>).
11299 if (Cand1.RewriteKind != Cand2.RewriteKind)
11300 return Cand1.RewriteKind < Cand2.RewriteKind;
11301
11302 // Check C++17 tie-breakers for deduction guides.
11303 {
11304 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11305 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11306 if (Guide1 && Guide2) {
11307 // -- F1 is generated from a deduction-guide and F2 is not
11308 if (Guide1->isImplicit() != Guide2->isImplicit())
11309 return Guide2->isImplicit();
11310
11311 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11312 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11313 return true;
11314 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11315 return false;
11316
11317 // --F1 is generated from a non-template constructor and F2 is generated
11318 // from a constructor template
11319 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11320 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11321 if (Constructor1 && Constructor2) {
11322 bool isC1Templated = Constructor1->getTemplatedKind() !=
11324 bool isC2Templated = Constructor2->getTemplatedKind() !=
11326 if (isC1Templated != isC2Templated)
11327 return isC2Templated;
11328 }
11329 }
11330 }
11331
11332 // Check for enable_if value-based overload resolution.
11333 if (Cand1.Function && Cand2.Function) {
11335 if (Cmp != Comparison::Equal)
11336 return Cmp == Comparison::Better;
11337 }
11338
11339 bool HasPS1 = Cand1.Function != nullptr &&
11341 bool HasPS2 = Cand2.Function != nullptr &&
11343 if (HasPS1 != HasPS2 && HasPS1)
11344 return true;
11345
11346 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11347 if (MV == Comparison::Better)
11348 return true;
11349 if (MV == Comparison::Worse)
11350 return false;
11351
11352 // If other rules cannot determine which is better, CUDA preference is used
11353 // to determine which is better.
11354 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11355 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11356 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11357 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11358 }
11359
11360 // General member function overloading is handled above, so this only handles
11361 // constructors with address spaces.
11362 // This only handles address spaces since C++ has no other
11363 // qualifier that can be used with constructors.
11364 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11365 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11366 if (CD1 && CD2) {
11367 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11368 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11369 if (AS1 != AS2) {
11371 return true;
11373 return false;
11374 }
11375 }
11376
11377 return false;
11378}
11379
11380/// Determine whether two declarations are "equivalent" for the purposes of
11381/// name lookup and overload resolution. This applies when the same internal/no
11382/// linkage entity is defined by two modules (probably by textually including
11383/// the same header). In such a case, we don't consider the declarations to
11384/// declare the same entity, but we also don't want lookups with both
11385/// declarations visible to be ambiguous in some cases (this happens when using
11386/// a modularized libstdc++).
11388 const NamedDecl *B) {
11389 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11390 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11391 if (!VA || !VB)
11392 return false;
11393
11394 // The declarations must be declaring the same name as an internal linkage
11395 // entity in different modules.
11396 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11397 VB->getDeclContext()->getRedeclContext()) ||
11398 getOwningModule(VA) == getOwningModule(VB) ||
11399 VA->isExternallyVisible() || VB->isExternallyVisible())
11400 return false;
11401
11402 // Check that the declarations appear to be equivalent.
11403 //
11404 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11405 // For constants and functions, we should check the initializer or body is
11406 // the same. For non-constant variables, we shouldn't allow it at all.
11407 if (Context.hasSameType(VA->getType(), VB->getType()))
11408 return true;
11409
11410 // Enum constants within unnamed enumerations will have different types, but
11411 // may still be similar enough to be interchangeable for our purposes.
11412 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11413 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11414 // Only handle anonymous enums. If the enumerations were named and
11415 // equivalent, they would have been merged to the same type.
11416 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11417 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11418 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11419 !Context.hasSameType(EnumA->getIntegerType(),
11420 EnumB->getIntegerType()))
11421 return false;
11422 // Allow this only if the value is the same for both enumerators.
11423 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11424 }
11425 }
11426
11427 // Nothing else is sufficiently similar.
11428 return false;
11429}
11430
11433 assert(D && "Unknown declaration");
11434 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11435
11436 Module *M = getOwningModule(D);
11437 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11438 << !M << (M ? M->getFullModuleName() : "");
11439
11440 for (auto *E : Equiv) {
11441 Module *M = getOwningModule(E);
11442 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11443 << !M << (M ? M->getFullModuleName() : "");
11444 }
11445}
11446
11449 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11451 static_cast<CNSInfo *>(DeductionFailure.Data)
11452 ->Satisfaction.ContainsErrors;
11453}
11454
11457 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11458 bool PartialOverloading, bool AllowExplicit,
11460 bool AggregateCandidateDeduction) {
11461
11462 auto *C =
11463 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11464
11467 /*AllowObjCConversionOnExplicit=*/false,
11468 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11469 PartialOverloading, AggregateCandidateDeduction},
11471 FoundDecl,
11472 Args,
11473 IsADLCandidate,
11474 PO};
11475
11476 HasDeferredTemplateConstructors |=
11477 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11478}
11479
11481 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11482 CXXRecordDecl *ActingContext, QualType ObjectType,
11483 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11484 bool SuppressUserConversions, bool PartialOverloading,
11486
11487 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11488
11489 auto *C =
11490 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11491
11494 /*AllowObjCConversionOnExplicit=*/false,
11495 /*AllowResultConversion=*/false,
11496 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11497 /*AggregateCandidateDeduction=*/false},
11498 MethodTmpl,
11499 FoundDecl,
11500 Args,
11501 ActingContext,
11502 ObjectClassification,
11503 ObjectType,
11504 PO};
11505}
11506
11509 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11510 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11511 bool AllowResultConversion) {
11512
11513 auto *C =
11514 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11515
11518 AllowObjCConversionOnExplicit, AllowResultConversion,
11519 /*AllowExplicit=*/false,
11520 /*SuppressUserConversions=*/false,
11521 /*PartialOverloading*/ false,
11522 /*AggregateCandidateDeduction=*/false},
11524 FoundDecl,
11525 ActingContext,
11526 From,
11527 ToType};
11528}
11529
11530static void
11533
11535 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11536 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11537 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11538}
11539
11540static void
11544 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11545 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11546 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11547 C.AggregateCandidateDeduction);
11548}
11549
11550static void
11554 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11555 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11556 C.AllowResultConversion);
11557}
11558
11560 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11561 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11562 while (Cand) {
11563 switch (Cand->Kind) {
11566 S, *this,
11567 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11568 break;
11571 S, *this,
11572 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11573 break;
11576 S, *this,
11577 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11578 break;
11579 }
11580 Cand = Cand->Next;
11581 }
11582 FirstDeferredCandidate = nullptr;
11583 DeferredCandidatesCount = 0;
11584}
11585
11587OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11588 Best->Best = true;
11589 if (Best->Function && Best->Function->isDeleted())
11590 return OR_Deleted;
11591 return OR_Success;
11592}
11593
11594void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11596 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11597 // are accepted by both clang and NVCC. However, during a particular
11598 // compilation mode only one call variant is viable. We need to
11599 // exclude non-viable overload candidates from consideration based
11600 // only on their host/device attributes. Specifically, if one
11601 // candidate call is WrongSide and the other is SameSide, we ignore
11602 // the WrongSide candidate.
11603 // We only need to remove wrong-sided candidates here if
11604 // -fgpu-exclude-wrong-side-overloads is off. When
11605 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11606 // uniformly in isBetterOverloadCandidate.
11607 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11608 return;
11609 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11610
11611 bool ContainsSameSideCandidate =
11612 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11613 // Check viable function only.
11614 return Cand->Viable && Cand->Function &&
11615 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11617 });
11618
11619 if (!ContainsSameSideCandidate)
11620 return;
11621
11622 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11623 // Check viable function only to avoid unnecessary data copying/moving.
11624 return Cand->Viable && Cand->Function &&
11625 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11627 };
11628 llvm::erase_if(Candidates, IsWrongSideCandidate);
11629}
11630
11631/// Computes the best viable function (C++ 13.3.3)
11632/// within an overload candidate set.
11633///
11634/// \param Loc The location of the function name (or operator symbol) for
11635/// which overload resolution occurs.
11636///
11637/// \param Best If overload resolution was successful or found a deleted
11638/// function, \p Best points to the candidate function found.
11639///
11640/// \returns The result of overload resolution.
11642 SourceLocation Loc,
11643 iterator &Best) {
11644
11646 DeferredCandidatesCount == 0) &&
11647 "Unexpected deferred template candidates");
11648
11649 bool TwoPhaseResolution =
11650 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11651
11652 if (TwoPhaseResolution) {
11653 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11654 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11655 if (!(HasDeferredTemplateConstructors &&
11656 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11657 return Res;
11658 }
11659 }
11660
11662 return BestViableFunctionImpl(S, Loc, Best);
11663}
11664
11665OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11667
11669 Candidates.reserve(this->Candidates.size());
11670 std::transform(this->Candidates.begin(), this->Candidates.end(),
11671 std::back_inserter(Candidates),
11672 [](OverloadCandidate &Cand) { return &Cand; });
11673
11674 if (S.getLangOpts().CUDA)
11675 CudaExcludeWrongSideCandidates(S, Candidates);
11676
11677 Best = end();
11678 for (auto *Cand : Candidates) {
11679 Cand->Best = false;
11680 if (Cand->Viable) {
11681 if (Best == end() ||
11682 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11683 Best = Cand;
11684 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11685 // This candidate has constraint that we were unable to evaluate because
11686 // it referenced an expression that contained an error. Rather than fall
11687 // back onto a potentially unintended candidate (made worse by
11688 // subsuming constraints), treat this as 'no viable candidate'.
11689 Best = end();
11690 return OR_No_Viable_Function;
11691 }
11692 }
11693
11694 // If we didn't find any viable functions, abort.
11695 if (Best == end())
11696 return OR_No_Viable_Function;
11697
11698 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11699 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11700 PendingBest.push_back(&*Best);
11701 Best->Best = true;
11702
11703 // Make sure that this function is better than every other viable
11704 // function. If not, we have an ambiguity.
11705 while (!PendingBest.empty()) {
11706 auto *Curr = PendingBest.pop_back_val();
11707 for (auto *Cand : Candidates) {
11708 if (Cand->Viable && !Cand->Best &&
11709 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11710 PendingBest.push_back(Cand);
11711 Cand->Best = true;
11712
11714 Curr->Function))
11715 EquivalentCands.push_back(Cand->Function);
11716 else
11717 Best = end();
11718 }
11719 }
11720 }
11721
11722 if (Best == end())
11723 return OR_Ambiguous;
11724
11725 OverloadingResult R = ResultForBestCandidate(Best);
11726
11727 if (!EquivalentCands.empty())
11729 EquivalentCands);
11730 return R;
11731}
11732
11733namespace {
11734
11735enum OverloadCandidateKind {
11736 oc_function,
11737 oc_method,
11738 oc_reversed_binary_operator,
11739 oc_constructor,
11740 oc_implicit_default_constructor,
11741 oc_implicit_copy_constructor,
11742 oc_implicit_move_constructor,
11743 oc_implicit_copy_assignment,
11744 oc_implicit_move_assignment,
11745 oc_implicit_equality_comparison,
11746 oc_inherited_constructor
11747};
11748
11749enum OverloadCandidateSelect {
11750 ocs_non_template,
11751 ocs_template,
11752 ocs_described_template,
11753};
11754
11755static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11756ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11757 const FunctionDecl *Fn,
11759 std::string &Description) {
11760
11761 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11762 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11763 isTemplate = true;
11764 Description = S.getTemplateArgumentBindingsText(
11765 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11766 }
11767
11768 OverloadCandidateSelect Select = [&]() {
11769 if (!Description.empty())
11770 return ocs_described_template;
11771 return isTemplate ? ocs_template : ocs_non_template;
11772 }();
11773
11774 OverloadCandidateKind Kind = [&]() {
11775 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11776 return oc_implicit_equality_comparison;
11777
11778 if (CRK & CRK_Reversed)
11779 return oc_reversed_binary_operator;
11780
11781 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11782 if (!Ctor->isImplicit()) {
11784 return oc_inherited_constructor;
11785 else
11786 return oc_constructor;
11787 }
11788
11789 if (Ctor->isDefaultConstructor())
11790 return oc_implicit_default_constructor;
11791
11792 if (Ctor->isMoveConstructor())
11793 return oc_implicit_move_constructor;
11794
11795 assert(Ctor->isCopyConstructor() &&
11796 "unexpected sort of implicit constructor");
11797 return oc_implicit_copy_constructor;
11798 }
11799
11800 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11801 // This actually gets spelled 'candidate function' for now, but
11802 // it doesn't hurt to split it out.
11803 if (!Meth->isImplicit())
11804 return oc_method;
11805
11806 if (Meth->isMoveAssignmentOperator())
11807 return oc_implicit_move_assignment;
11808
11809 if (Meth->isCopyAssignmentOperator())
11810 return oc_implicit_copy_assignment;
11811
11812 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11813 return oc_method;
11814 }
11815
11816 return oc_function;
11817 }();
11818
11819 return std::make_pair(Kind, Select);
11820}
11821
11822void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11823 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11824 // set.
11825 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11826 S.Diag(FoundDecl->getLocation(),
11827 diag::note_ovl_candidate_inherited_constructor)
11828 << Shadow->getNominatedBaseClass();
11829}
11830
11831} // end anonymous namespace
11832
11834 const FunctionDecl *FD) {
11835 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11836 bool AlwaysTrue;
11837 if (EnableIf->getCond()->isValueDependent() ||
11838 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11839 return false;
11840 if (!AlwaysTrue)
11841 return false;
11842 }
11843 return true;
11844}
11845
11846/// Returns true if we can take the address of the function.
11847///
11848/// \param Complain - If true, we'll emit a diagnostic
11849/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11850/// we in overload resolution?
11851/// \param Loc - The location of the statement we're complaining about. Ignored
11852/// if we're not complaining, or if we're in overload resolution.
11854 bool Complain,
11855 bool InOverloadResolution,
11856 SourceLocation Loc) {
11857 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11858 if (Complain) {
11859 if (InOverloadResolution)
11860 S.Diag(FD->getBeginLoc(),
11861 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11862 else
11863 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11864 }
11865 return false;
11866 }
11867
11868 if (FD->getTrailingRequiresClause()) {
11869 ConstraintSatisfaction Satisfaction;
11870 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11871 return false;
11872 if (!Satisfaction.IsSatisfied) {
11873 if (Complain) {
11874 if (InOverloadResolution) {
11875 SmallString<128> TemplateArgString;
11876 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11877 TemplateArgString += " ";
11878 TemplateArgString += S.getTemplateArgumentBindingsText(
11879 FunTmpl->getTemplateParameters(),
11881 }
11882
11883 S.Diag(FD->getBeginLoc(),
11884 diag::note_ovl_candidate_unsatisfied_constraints)
11885 << TemplateArgString;
11886 } else
11887 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11888 << FD;
11889 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11890 }
11891 return false;
11892 }
11893 }
11894
11895 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11896 return P->hasAttr<PassObjectSizeAttr>();
11897 });
11898 if (I == FD->param_end())
11899 return true;
11900
11901 if (Complain) {
11902 // Add one to ParamNo because it's user-facing
11903 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11904 if (InOverloadResolution)
11905 S.Diag(FD->getLocation(),
11906 diag::note_ovl_candidate_has_pass_object_size_params)
11907 << ParamNo;
11908 else
11909 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11910 << FD << ParamNo;
11911 }
11912 return false;
11913}
11914
11916 const FunctionDecl *FD) {
11917 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11918 /*InOverloadResolution=*/true,
11919 /*Loc=*/SourceLocation());
11920}
11921
11923 bool Complain,
11924 SourceLocation Loc) {
11925 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11926 /*InOverloadResolution=*/false,
11927 Loc);
11928}
11929
11930// Don't print candidates other than the one that matches the calling
11931// convention of the call operator, since that is guaranteed to exist.
11933 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11934
11935 if (!ConvD)
11936 return false;
11937 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11938 if (!RD->isLambda())
11939 return false;
11940
11941 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11942 CallingConv CallOpCC =
11943 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11944 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11945 CallingConv ConvToCC =
11946 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11947
11948 return ConvToCC != CallOpCC;
11949}
11950
11951// Notes the location of an overload candidate.
11953 OverloadCandidateRewriteKind RewriteKind,
11954 QualType DestType, bool TakingAddress) {
11955 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11956 return;
11957 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11958 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11959 return;
11960 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11961 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11962 return;
11964 return;
11965
11966 std::string FnDesc;
11967 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11968 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11969 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11970 << (unsigned)KSPair.first << (unsigned)KSPair.second
11971 << Fn << FnDesc;
11972
11973 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11974 Diag(Fn->getLocation(), PD);
11975 MaybeEmitInheritedConstructorNote(*this, Found);
11976}
11977
11978static void
11980 // Perhaps the ambiguity was caused by two atomic constraints that are
11981 // 'identical' but not equivalent:
11982 //
11983 // void foo() requires (sizeof(T) > 4) { } // #1
11984 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11985 //
11986 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11987 // #2 to subsume #1, but these constraint are not considered equivalent
11988 // according to the subsumption rules because they are not the same
11989 // source-level construct. This behavior is quite confusing and we should try
11990 // to help the user figure out what happened.
11991
11992 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11993 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11994 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11995 if (!I->Function)
11996 continue;
11998 if (auto *Template = I->Function->getPrimaryTemplate())
11999 Template->getAssociatedConstraints(AC);
12000 else
12001 I->Function->getAssociatedConstraints(AC);
12002 if (AC.empty())
12003 continue;
12004 if (FirstCand == nullptr) {
12005 FirstCand = I->Function;
12006 FirstAC = AC;
12007 } else if (SecondCand == nullptr) {
12008 SecondCand = I->Function;
12009 SecondAC = AC;
12010 } else {
12011 // We have more than one pair of constrained functions - this check is
12012 // expensive and we'd rather not try to diagnose it.
12013 return;
12014 }
12015 }
12016 if (!SecondCand)
12017 return;
12018 // The diagnostic can only happen if there are associated constraints on
12019 // both sides (there needs to be some identical atomic constraint).
12020 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
12021 SecondCand, SecondAC))
12022 // Just show the user one diagnostic, they'll probably figure it out
12023 // from here.
12024 return;
12025}
12026
12027// Notes the location of all overload candidates designated through
12028// OverloadedExpr
12029void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12030 bool TakingAddress) {
12031 assert(OverloadedExpr->getType() == Context.OverloadTy);
12032
12033 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
12034 OverloadExpr *OvlExpr = Ovl.Expression;
12035
12036 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12037 IEnd = OvlExpr->decls_end();
12038 I != IEnd; ++I) {
12039 if (FunctionTemplateDecl *FunTmpl =
12040 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12041 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12042 TakingAddress);
12043 } else if (FunctionDecl *Fun
12044 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12045 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12046 }
12047 }
12048}
12049
12050/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12051/// "lead" diagnostic; it will be given two arguments, the source and
12052/// target types of the conversion.
12054 Sema &S,
12055 SourceLocation CaretLoc,
12056 const PartialDiagnostic &PDiag) const {
12057 S.Diag(CaretLoc, PDiag)
12058 << Ambiguous.getFromType() << Ambiguous.getToType();
12059 unsigned CandsShown = 0;
12061 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12062 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12063 break;
12064 ++CandsShown;
12065 S.NoteOverloadCandidate(I->first, I->second);
12066 }
12067 S.Diags.overloadCandidatesShown(CandsShown);
12068 if (I != E)
12069 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12070}
12071
12073 unsigned I, bool TakingCandidateAddress) {
12074 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12075 assert(Conv.isBad());
12076 assert(Cand->Function && "for now, candidate must be a function");
12077 FunctionDecl *Fn = Cand->Function;
12078
12079 // There's a conversion slot for the object argument if this is a
12080 // non-constructor method. Note that 'I' corresponds the
12081 // conversion-slot index.
12082 bool isObjectArgument = false;
12083 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12085 if (I == 0)
12086 isObjectArgument = true;
12087 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12088 I--;
12089 }
12090
12091 std::string FnDesc;
12092 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12093 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12094 FnDesc);
12095
12096 Expr *FromExpr = Conv.Bad.FromExpr;
12097 QualType FromTy = Conv.Bad.getFromType();
12098 QualType ToTy = Conv.Bad.getToType();
12099 SourceRange ToParamRange;
12100
12101 // FIXME: In presence of parameter packs we can't determine parameter range
12102 // reliably, as we don't have access to instantiation.
12103 bool HasParamPack =
12104 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12105 return Parm->isParameterPack();
12106 });
12107 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12108 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12109
12110 if (FromTy == S.Context.OverloadTy) {
12111 assert(FromExpr && "overload set argument came from implicit argument?");
12112 Expr *E = FromExpr->IgnoreParens();
12113 if (isa<UnaryOperator>(E))
12114 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12115 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12116
12117 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12118 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12119 << ToParamRange << ToTy << Name << I + 1;
12120 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12121 return;
12122 }
12123
12124 // Do some hand-waving analysis to see if the non-viability is due
12125 // to a qualifier mismatch.
12126 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12127 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12128 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12129 CToTy = RT->getPointeeType();
12130 else {
12131 // TODO: detect and diagnose the full richness of const mismatches.
12132 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12133 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12134 CFromTy = FromPT->getPointeeType();
12135 CToTy = ToPT->getPointeeType();
12136 }
12137 }
12138
12139 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12140 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12141 Qualifiers FromQs = CFromTy.getQualifiers();
12142 Qualifiers ToQs = CToTy.getQualifiers();
12143
12144 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12145 if (isObjectArgument)
12146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12147 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12148 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12149 else
12150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12151 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12152 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12153 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12154 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12155 return;
12156 }
12157
12158 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12159 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12160 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12161 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12162 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12163 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12164 return;
12165 }
12166
12167 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12169 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12170 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12171 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12172 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12173 return;
12174 }
12175
12176 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12178 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12179 << FromTy << !!FromQs.getPointerAuth()
12180 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12181 << ToQs.getPointerAuth().getAsString() << I + 1
12182 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12183 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12184 return;
12185 }
12186
12187 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12188 assert(CVR && "expected qualifiers mismatch");
12189
12190 if (isObjectArgument) {
12191 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12192 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12193 << FromTy << (CVR - 1);
12194 } else {
12195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12196 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12197 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12198 }
12199 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12200 return;
12201 }
12202
12205 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12206 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12207 << (unsigned)isObjectArgument << I + 1
12209 << ToParamRange;
12210 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12211 return;
12212 }
12213
12214 // Special diagnostic for failure to convert an initializer list, since
12215 // telling the user that it has type void is not useful.
12216 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12218 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12219 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12222 ? 2
12223 : 0);
12224 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12225 return;
12226 }
12227
12228 // Diagnose references or pointers to incomplete types differently,
12229 // since it's far from impossible that the incompleteness triggered
12230 // the failure.
12231 QualType TempFromTy = FromTy.getNonReferenceType();
12232 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12233 TempFromTy = PTy->getPointeeType();
12234 if (TempFromTy->isIncompleteType()) {
12235 // Emit the generic diagnostic and, optionally, add the hints to it.
12236 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12237 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12238 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12239 << (unsigned)(Cand->Fix.Kind);
12240
12241 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12242 return;
12243 }
12244
12245 // Diagnose base -> derived pointer conversions.
12246 unsigned BaseToDerivedConversion = 0;
12247 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12248 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12249 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12250 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12251 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12252 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12253 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12254 FromPtrTy->getPointeeType()))
12255 BaseToDerivedConversion = 1;
12256 }
12257 } else if (const ObjCObjectPointerType *FromPtrTy
12258 = FromTy->getAs<ObjCObjectPointerType>()) {
12259 if (const ObjCObjectPointerType *ToPtrTy
12260 = ToTy->getAs<ObjCObjectPointerType>())
12261 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12262 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12263 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12264 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12265 FromIface->isSuperClassOf(ToIface))
12266 BaseToDerivedConversion = 2;
12267 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12268 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12269 S.getASTContext()) &&
12270 !FromTy->isIncompleteType() &&
12271 !ToRefTy->getPointeeType()->isIncompleteType() &&
12272 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12273 BaseToDerivedConversion = 3;
12274 }
12275 }
12276
12277 if (BaseToDerivedConversion) {
12278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12279 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12280 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12281 << I + 1;
12282 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12283 return;
12284 }
12285
12286 if (isa<ObjCObjectPointerType>(CFromTy) &&
12287 isa<PointerType>(CToTy)) {
12288 Qualifiers FromQs = CFromTy.getQualifiers();
12289 Qualifiers ToQs = CToTy.getQualifiers();
12290 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12292 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12293 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12294 << I + 1;
12295 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12296 return;
12297 }
12298 }
12299
12300 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12301 return;
12302
12303 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12304 // although this is almost always an error and we advise against it.
12305 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12306 ToTy == S.Context.getLogicalOperationType()) {
12307 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12308 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12309 << Conv.Bad.FromExpr << ToTy;
12310 return;
12311 }
12312
12313 // Emit the generic diagnostic and, optionally, add the hints to it.
12314 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12315 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12316 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12317 << (unsigned)(Cand->Fix.Kind);
12318
12319 // Check that location of Fn is not in system header.
12320 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12321 // If we can fix the conversion, suggest the FixIts.
12322 for (const FixItHint &HI : Cand->Fix.Hints)
12323 FDiag << HI;
12324 }
12325
12326 S.Diag(Fn->getLocation(), FDiag);
12327
12328 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12329}
12330
12331/// Additional arity mismatch diagnosis specific to a function overload
12332/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12333/// over a candidate in any candidate set.
12335 unsigned NumArgs, bool IsAddressOf = false) {
12336 assert(Cand->Function && "Candidate is required to be a function.");
12337 FunctionDecl *Fn = Cand->Function;
12338 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12339 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12340
12341 // With invalid overloaded operators, it's possible that we think we
12342 // have an arity mismatch when in fact it looks like we have the
12343 // right number of arguments, because only overloaded operators have
12344 // the weird behavior of overloading member and non-member functions.
12345 // Just don't report anything.
12346 if (Fn->isInvalidDecl() &&
12347 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12348 return true;
12349
12350 if (NumArgs < MinParams) {
12351 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12353 Cand->DeductionFailure.getResult() ==
12355 } else {
12356 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12358 Cand->DeductionFailure.getResult() ==
12360 }
12361
12362 return false;
12363}
12364
12365/// General arity mismatch diagnosis over a candidate in a candidate set.
12367 unsigned NumFormalArgs,
12368 bool IsAddressOf = false) {
12369 assert(isa<FunctionDecl>(D) &&
12370 "The templated declaration should at least be a function"
12371 " when diagnosing bad template argument deduction due to too many"
12372 " or too few arguments");
12373
12375
12376 // TODO: treat calls to a missing default constructor as a special case
12377 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12378 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12379 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12380
12381 // at least / at most / exactly
12382 bool HasExplicitObjectParam =
12383 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12384
12385 unsigned ParamCount =
12386 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12387 unsigned mode, modeCount;
12388
12389 if (NumFormalArgs < MinParams) {
12390 if (MinParams != ParamCount || FnTy->isVariadic() ||
12391 FnTy->isTemplateVariadic())
12392 mode = 0; // "at least"
12393 else
12394 mode = 2; // "exactly"
12395 modeCount = MinParams;
12396 } else {
12397 if (MinParams != ParamCount)
12398 mode = 1; // "at most"
12399 else
12400 mode = 2; // "exactly"
12401 modeCount = ParamCount;
12402 }
12403
12404 std::string Description;
12405 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12406 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12407
12408 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12409 if (modeCount == 1 && !IsAddressOf &&
12410 FirstNonObjectParamIdx < Fn->getNumParams() &&
12411 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12412 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12413 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12414 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12415 << NumFormalArgs << HasExplicitObjectParam
12416 << Fn->getParametersSourceRange();
12417 else
12418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12419 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12420 << Description << mode << modeCount << NumFormalArgs
12421 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12422
12423 MaybeEmitInheritedConstructorNote(S, Found);
12424}
12425
12426/// Arity mismatch diagnosis specific to a function overload candidate.
12428 unsigned NumFormalArgs) {
12429 assert(Cand->Function && "Candidate must be a function");
12430 FunctionDecl *Fn = Cand->Function;
12431 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12432 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12433 Cand->TookAddressOfOverload);
12434}
12435
12437 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12438 return TD;
12439 llvm_unreachable("Unsupported: Getting the described template declaration"
12440 " for bad deduction diagnosis");
12441}
12442
12443/// Diagnose a failed template-argument deduction.
12444static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12445 DeductionFailureInfo &DeductionFailure,
12446 unsigned NumArgs, bool TakingCandidateAddress,
12447 TemplateSpecCandidateSetKind CandidateSetKind =
12449 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12450 NamedDecl *ParamD = dyn_cast_if_present<TemplateTypeParmDecl *>(Param);
12451 if (!ParamD)
12452 ParamD = dyn_cast_if_present<NonTypeTemplateParmDecl *>(Param);
12453 if (!ParamD)
12454 ParamD = dyn_cast_if_present<TemplateTemplateParmDecl *>(Param);
12455 switch (DeductionFailure.getResult()) {
12457 llvm_unreachable(
12458 "TemplateDeductionResult::Success while diagnosing bad deduction");
12460 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12461 "while diagnosing bad deduction");
12464 return;
12465
12467 assert(ParamD && "no parameter found for incomplete deduction result");
12468 S.Diag(Templated->getLocation(),
12469 diag::note_ovl_candidate_incomplete_deduction)
12470 << ParamD->getDeclName();
12471 MaybeEmitInheritedConstructorNote(S, Found);
12472 return;
12473 }
12474
12476 assert(ParamD && "no parameter found for incomplete deduction result");
12477 S.Diag(Templated->getLocation(),
12478 diag::note_ovl_candidate_incomplete_deduction_pack)
12479 << ParamD->getDeclName()
12480 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12481 << *DeductionFailure.getFirstArg();
12482 MaybeEmitInheritedConstructorNote(S, Found);
12483 return;
12484 }
12485
12487 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12489
12490 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12491
12492 // Param will have been canonicalized, but it should just be a
12493 // qualified version of ParamD, so move the qualifiers to that.
12495 Qs.strip(Param);
12496 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12497 assert(S.Context.hasSameType(Param, NonCanonParam));
12498
12499 // Arg has also been canonicalized, but there's nothing we can do
12500 // about that. It also doesn't matter as much, because it won't
12501 // have any template parameters in it (because deduction isn't
12502 // done on dependent types).
12503 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12504
12505 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12506 << ParamD->getDeclName() << Arg << NonCanonParam;
12507 MaybeEmitInheritedConstructorNote(S, Found);
12508 return;
12509 }
12510
12512 assert(ParamD && "no parameter found for inconsistent deduction result");
12513 int which = 0;
12514 if (isa<TemplateTypeParmDecl>(ParamD))
12515 which = 0;
12516 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12517 // Deduction might have failed because we deduced arguments of two
12518 // different types for a non-type template parameter.
12519 // FIXME: Use a different TDK value for this.
12520 QualType T1 =
12521 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12522 QualType T2 =
12523 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12524 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12525 S.Diag(Templated->getLocation(),
12526 diag::note_ovl_candidate_inconsistent_deduction_types)
12527 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12528 << *DeductionFailure.getSecondArg() << T2;
12529 MaybeEmitInheritedConstructorNote(S, Found);
12530 return;
12531 }
12532
12533 which = 1;
12534 } else {
12535 which = 2;
12536 }
12537
12538 // Tweak the diagnostic if the problem is that we deduced packs of
12539 // different arities. We'll print the actual packs anyway in case that
12540 // includes additional useful information.
12541 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12542 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12543 DeductionFailure.getFirstArg()->pack_size() !=
12544 DeductionFailure.getSecondArg()->pack_size()) {
12545 which = 3;
12546 }
12547
12548 S.Diag(Templated->getLocation(),
12549 diag::note_ovl_candidate_inconsistent_deduction)
12550 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12551 << *DeductionFailure.getSecondArg();
12552 MaybeEmitInheritedConstructorNote(S, Found);
12553 return;
12554 }
12555
12557 assert(ParamD && "no parameter found for invalid explicit arguments");
12558
12559 auto Diag = S.Diag(Templated->getLocation(),
12560 diag::note_ovl_candidate_explicit_arg_mismatch);
12561 if (ParamD->getDeclName())
12562 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12563 else
12564 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12565 << (getDepthAndIndex(ParamD).second + 1);
12566 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12567 SmallString<128> DiagContent;
12568 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12569 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12570 } else {
12571 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12572 }
12573
12574 MaybeEmitInheritedConstructorNote(S, Found);
12575 return;
12576 }
12578 // Format the template argument list into the argument string.
12579 SmallString<128> TemplateArgString;
12580 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12581 TemplateArgString = " ";
12582 TemplateArgString += S.getTemplateArgumentBindingsText(
12583 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12584 if (TemplateArgString.size() == 1)
12585 TemplateArgString.clear();
12586 S.Diag(Templated->getLocation(),
12587 diag::note_ovl_candidate_unsatisfied_constraints)
12588 << TemplateArgString;
12589
12591 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12592 return;
12593 }
12596 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12597 return;
12598
12600 S.Diag(Templated->getLocation(),
12601 diag::note_ovl_candidate_instantiation_depth);
12602 MaybeEmitInheritedConstructorNote(S, Found);
12603 return;
12604
12606 // Format the template argument list into the argument string.
12607 SmallString<128> TemplateArgString;
12608 if (TemplateArgumentList *Args =
12609 DeductionFailure.getTemplateArgumentList()) {
12610 TemplateArgString = " ";
12611 TemplateArgString += S.getTemplateArgumentBindingsText(
12612 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12613 if (TemplateArgString.size() == 1)
12614 TemplateArgString.clear();
12615 }
12616
12617 // If this candidate was disabled by enable_if, say so.
12618 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12619 if (PDiag && PDiag->second.getDiagID() ==
12620 diag::err_typename_nested_not_found_enable_if) {
12621 // FIXME: Use the source range of the condition, and the fully-qualified
12622 // name of the enable_if template. These are both present in PDiag.
12623 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12624 << "'enable_if'" << TemplateArgString;
12625 return;
12626 }
12627
12628 // We found a specific requirement that disabled the enable_if.
12629 if (PDiag && PDiag->second.getDiagID() ==
12630 diag::err_typename_nested_not_found_requirement) {
12631 S.Diag(Templated->getLocation(),
12632 diag::note_ovl_candidate_disabled_by_requirement)
12633 << PDiag->second.getStringArg(0) << TemplateArgString;
12634 return;
12635 }
12636
12637 // Format the SFINAE diagnostic into the argument string.
12638 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12639 // formatted message in another diagnostic.
12640 SmallString<128> SFINAEArgString;
12641 SourceRange R;
12642 if (PDiag) {
12643 SFINAEArgString = ": ";
12644 R = SourceRange(PDiag->first, PDiag->first);
12645 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12646 }
12647
12648 S.Diag(Templated->getLocation(),
12649 diag::note_ovl_candidate_substitution_failure)
12650 << TemplateArgString << SFINAEArgString << R;
12651 MaybeEmitInheritedConstructorNote(S, Found);
12652 return;
12653 }
12654
12657 // Format the template argument list into the argument string.
12658 SmallString<128> TemplateArgString;
12659 if (TemplateArgumentList *Args =
12660 DeductionFailure.getTemplateArgumentList()) {
12661 TemplateArgString = " ";
12662 TemplateArgString += S.getTemplateArgumentBindingsText(
12663 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12664 if (TemplateArgString.size() == 1)
12665 TemplateArgString.clear();
12666 }
12667
12668 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12669 << (*DeductionFailure.getCallArgIndex() + 1)
12670 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12671 << TemplateArgString
12672 << (DeductionFailure.getResult() ==
12674 break;
12675 }
12676
12678 // FIXME: Provide a source location to indicate what we couldn't match.
12679 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12680 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12681 if (FirstTA.getKind() == TemplateArgument::Template &&
12682 SecondTA.getKind() == TemplateArgument::Template) {
12683 TemplateName FirstTN = FirstTA.getAsTemplate();
12684 TemplateName SecondTN = SecondTA.getAsTemplate();
12685 if (FirstTN.getKind() == TemplateName::Template &&
12686 SecondTN.getKind() == TemplateName::Template) {
12687 if (FirstTN.getAsTemplateDecl()->getName() ==
12688 SecondTN.getAsTemplateDecl()->getName()) {
12689 // FIXME: This fixes a bad diagnostic where both templates are named
12690 // the same. This particular case is a bit difficult since:
12691 // 1) It is passed as a string to the diagnostic printer.
12692 // 2) The diagnostic printer only attempts to find a better
12693 // name for types, not decls.
12694 // Ideally, this should folded into the diagnostic printer.
12695 S.Diag(Templated->getLocation(),
12696 CandidateSetKind ==
12698 ? diag::note_friend_template_non_deduced_mismatch_qualified
12699 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12700 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12701 return;
12702 }
12703 }
12704 }
12705
12706 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12708 return;
12709
12710 // FIXME: For generic lambda parameters, check if the function is a lambda
12711 // call operator, and if so, emit a prettier and more informative
12712 // diagnostic that mentions 'auto' and lambda in addition to
12713 // (or instead of?) the canonical template type parameters.
12714 S.Diag(Templated->getLocation(),
12716 ? diag::note_friend_template_non_deduced_mismatch
12717 : diag::note_ovl_candidate_non_deduced_mismatch)
12718 << FirstTA << SecondTA;
12719 return;
12720 }
12721 // TODO: diagnose these individually, then kill off
12722 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12724 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12725 MaybeEmitInheritedConstructorNote(S, Found);
12726 return;
12728 S.Diag(Templated->getLocation(),
12729 diag::note_cuda_ovl_candidate_target_mismatch);
12730 return;
12731 }
12732}
12733
12734/// Diagnose a failed template-argument deduction, for function calls.
12736 unsigned NumArgs,
12737 bool TakingCandidateAddress) {
12738 assert(Cand->Function && "Candidate must be a function");
12739 FunctionDecl *Fn = Cand->Function;
12743 if (CheckArityMismatch(S, Cand, NumArgs))
12744 return;
12745 }
12746 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12747 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12748}
12749
12750/// CUDA: diagnose an invalid call across targets.
12752 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12753 assert(Cand->Function && "Candidate must be a Function.");
12754 FunctionDecl *Callee = Cand->Function;
12755
12756 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12757 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12758
12759 std::string FnDesc;
12760 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12761 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12762 Cand->getRewriteKind(), FnDesc);
12763
12764 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12765 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12766 << FnDesc /* Ignored */
12767 << CalleeTarget << CallerTarget;
12768
12769 // This could be an implicit constructor for which we could not infer the
12770 // target due to a collsion. Diagnose that case.
12771 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12772 if (Meth != nullptr && Meth->isImplicit()) {
12773 CXXRecordDecl *ParentClass = Meth->getParent();
12775
12776 switch (FnKindPair.first) {
12777 default:
12778 return;
12779 case oc_implicit_default_constructor:
12781 break;
12782 case oc_implicit_copy_constructor:
12784 break;
12785 case oc_implicit_move_constructor:
12787 break;
12788 case oc_implicit_copy_assignment:
12790 break;
12791 case oc_implicit_move_assignment:
12793 break;
12794 };
12795
12796 bool ConstRHS = false;
12797 if (Meth->getNumParams()) {
12798 if (const ReferenceType *RT =
12799 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12800 ConstRHS = RT->getPointeeType().isConstQualified();
12801 }
12802 }
12803
12804 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12805 /* ConstRHS */ ConstRHS,
12806 /* Diagnose */ true);
12807 }
12808}
12809
12811 assert(Cand->Function && "Candidate must be a function");
12812 FunctionDecl *Callee = Cand->Function;
12813 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12814
12815 S.Diag(Callee->getLocation(),
12816 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12817 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12818}
12819
12821 assert(Cand->Function && "Candidate must be a function");
12822 FunctionDecl *Fn = Cand->Function;
12824 assert(ES.isExplicit() && "not an explicit candidate");
12825
12826 unsigned Kind;
12827 switch (Fn->getDeclKind()) {
12828 case Decl::Kind::CXXConstructor:
12829 Kind = 0;
12830 break;
12831 case Decl::Kind::CXXConversion:
12832 Kind = 1;
12833 break;
12834 case Decl::Kind::CXXDeductionGuide:
12835 Kind = Fn->isImplicit() ? 0 : 2;
12836 break;
12837 default:
12838 llvm_unreachable("invalid Decl");
12839 }
12840
12841 // Note the location of the first (in-class) declaration; a redeclaration
12842 // (particularly an out-of-class definition) will typically lack the
12843 // 'explicit' specifier.
12844 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12845 FunctionDecl *First = Fn->getFirstDecl();
12846 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12847 First = Pattern->getFirstDecl();
12848
12849 S.Diag(First->getLocation(),
12850 diag::note_ovl_candidate_explicit)
12851 << Kind << (ES.getExpr() ? 1 : 0)
12852 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12853}
12854
12856 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12857 if (!DG)
12858 return;
12859 TemplateDecl *OriginTemplate =
12861 // We want to always print synthesized deduction guides for type aliases.
12862 // They would retain the explicit bit of the corresponding constructor.
12863 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12864 return;
12865 std::string FunctionProto;
12866 llvm::raw_string_ostream OS(FunctionProto);
12867 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12868 if (!Template) {
12869 // This also could be an instantiation. Find out the primary template.
12870 FunctionDecl *Pattern =
12871 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12872 if (!Pattern) {
12873 // The implicit deduction guide is built on an explicit non-template
12874 // deduction guide. Currently, this might be the case only for type
12875 // aliases.
12876 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12877 // gets merged.
12878 assert(OriginTemplate->isTypeAlias() &&
12879 "Non-template implicit deduction guides are only possible for "
12880 "type aliases");
12881 DG->print(OS);
12882 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12883 << FunctionProto;
12884 return;
12885 }
12887 assert(Template && "Cannot find the associated function template of "
12888 "CXXDeductionGuideDecl?");
12889 }
12890 Template->print(OS);
12891 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12892 << FunctionProto;
12893}
12894
12895/// Generates a 'note' diagnostic for an overload candidate. We've
12896/// already generated a primary error at the call site.
12897///
12898/// It really does need to be a single diagnostic with its caret
12899/// pointed at the candidate declaration. Yes, this creates some
12900/// major challenges of technical writing. Yes, this makes pointing
12901/// out problems with specific arguments quite awkward. It's still
12902/// better than generating twenty screens of text for every failed
12903/// overload.
12904///
12905/// It would be great to be able to express per-candidate problems
12906/// more richly for those diagnostic clients that cared, but we'd
12907/// still have to be just as careful with the default diagnostics.
12908/// \param CtorDestAS Addr space of object being constructed (for ctor
12909/// candidates only).
12911 unsigned NumArgs,
12912 bool TakingCandidateAddress,
12913 LangAS CtorDestAS = LangAS::Default) {
12914 assert(Cand->Function && "Candidate must be a function");
12915 FunctionDecl *Fn = Cand->Function;
12917 return;
12918
12919 // There is no physical candidate declaration to point to for OpenCL builtins.
12920 // Except for failed conversions, the notes are identical for each candidate,
12921 // so do not generate such notes.
12922 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12924 return;
12925
12926 // Skip implicit member functions when trying to resolve
12927 // the address of a an overload set for a function pointer.
12928 if (Cand->TookAddressOfOverload &&
12929 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12930 return;
12931
12932 // Note deleted candidates, but only if they're viable.
12933 if (Cand->Viable) {
12934 if (Fn->isDeleted()) {
12935 std::string FnDesc;
12936 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12937 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12938 Cand->getRewriteKind(), FnDesc);
12939
12940 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12941 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12942 << (Fn->isDeleted()
12943 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12944 : 0);
12945 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12946 return;
12947 }
12948
12949 // We don't really have anything else to say about viable candidates.
12950 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12951 return;
12952 }
12953
12954 // If this is a synthesized deduction guide we're deducing against, add a note
12955 // for it. These deduction guides are not explicitly spelled in the source
12956 // code, so simply printing a deduction failure note mentioning synthesized
12957 // template parameters or pointing to the header of the surrounding RecordDecl
12958 // would be confusing.
12959 //
12960 // We prefer adding such notes at the end of the deduction failure because
12961 // duplicate code snippets appearing in the diagnostic would likely become
12962 // noisy.
12963 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12964
12965 switch (Cand->FailureKind) {
12968 return DiagnoseArityMismatch(S, Cand, NumArgs);
12969
12971 return DiagnoseBadDeduction(S, Cand, NumArgs,
12972 TakingCandidateAddress);
12973
12975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12976 << (Fn->getPrimaryTemplate() ? 1 : 0);
12977 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12978 return;
12979 }
12980
12982 Qualifiers QualsForPrinting;
12983 QualsForPrinting.setAddressSpace(CtorDestAS);
12984 S.Diag(Fn->getLocation(),
12985 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12986 << QualsForPrinting;
12987 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12988 return;
12989 }
12990
12994 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12995
12997 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12998 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12999 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
13000 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
13001
13002 // FIXME: this currently happens when we're called from SemaInit
13003 // when user-conversion overload fails. Figure out how to handle
13004 // those conditions and diagnose them well.
13005 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
13006 }
13007
13009 return DiagnoseBadTarget(S, Cand);
13010
13011 case ovl_fail_enable_if:
13012 return DiagnoseFailedEnableIfAttr(S, Cand);
13013
13014 case ovl_fail_explicit:
13015 return DiagnoseFailedExplicitSpec(S, Cand);
13016
13018 // It's generally not interesting to note copy/move constructors here.
13019 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
13020 return;
13021 S.Diag(Fn->getLocation(),
13022 diag::note_ovl_candidate_inherited_constructor_slice)
13023 << (Fn->getPrimaryTemplate() ? 1 : 0)
13024 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
13025 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13026 return;
13027
13029 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
13030 (void)Available;
13031 assert(!Available);
13032 break;
13033 }
13035 // Do nothing, these should simply be ignored.
13036 break;
13037
13039 std::string FnDesc;
13040 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13041 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13042 Cand->getRewriteKind(), FnDesc);
13043
13044 S.Diag(Fn->getLocation(),
13045 diag::note_ovl_candidate_constraints_not_satisfied)
13046 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13047 << FnDesc /* Ignored */;
13048 ConstraintSatisfaction Satisfaction;
13049 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13050 /*ForOverloadResolution=*/true))
13051 break;
13052 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13053 }
13054 }
13055}
13056
13059 return;
13060
13061 // Desugar the type of the surrogate down to a function type,
13062 // retaining as many typedefs as possible while still showing
13063 // the function type (and, therefore, its parameter types).
13064 QualType FnType = Cand->Surrogate->getConversionType();
13065 bool isLValueReference = false;
13066 bool isRValueReference = false;
13067 bool isPointer = false;
13068 if (const LValueReferenceType *FnTypeRef =
13069 FnType->getAs<LValueReferenceType>()) {
13070 FnType = FnTypeRef->getPointeeType();
13071 isLValueReference = true;
13072 } else if (const RValueReferenceType *FnTypeRef =
13073 FnType->getAs<RValueReferenceType>()) {
13074 FnType = FnTypeRef->getPointeeType();
13075 isRValueReference = true;
13076 }
13077 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13078 FnType = FnTypePtr->getPointeeType();
13079 isPointer = true;
13080 }
13081 // Desugar down to a function type.
13082 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13083 // Reconstruct the pointer/reference as appropriate.
13084 if (isPointer) FnType = S.Context.getPointerType(FnType);
13085 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13086 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13087
13088 if (!Cand->Viable &&
13090 S.Diag(Cand->Surrogate->getLocation(),
13091 diag::note_ovl_surrogate_constraints_not_satisfied)
13092 << Cand->Surrogate;
13093 ConstraintSatisfaction Satisfaction;
13094 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13095 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13096 } else {
13097 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13098 << FnType;
13099 }
13100}
13101
13102static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13103 SourceLocation OpLoc,
13104 OverloadCandidate *Cand) {
13105 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13106 std::string TypeStr("operator");
13107 TypeStr += Opc;
13108 TypeStr += "(";
13109 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13110 if (Cand->Conversions.size() == 1) {
13111 TypeStr += ")";
13112 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13113 } else {
13114 TypeStr += ", ";
13115 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13116 TypeStr += ")";
13117 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13118 }
13119}
13120
13122 OverloadCandidate *Cand) {
13123 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13124 if (ICS.isBad()) break; // all meaningless after first invalid
13125 if (!ICS.isAmbiguous()) continue;
13126
13128 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13129 }
13130}
13131
13133 if (Cand->Function)
13134 return Cand->Function->getLocation();
13135 if (Cand->IsSurrogate)
13136 return Cand->Surrogate->getLocation();
13137 return SourceLocation();
13138}
13139
13140static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13141 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13145 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13146
13150 return 1;
13151
13154 return 2;
13155
13163 return 3;
13164
13166 return 4;
13167
13169 return 5;
13170
13173 return 6;
13174 }
13175 llvm_unreachable("Unhandled deduction result");
13176}
13177
13178namespace {
13179
13180struct CompareOverloadCandidatesForDisplay {
13181 Sema &S;
13182 SourceLocation Loc;
13183 size_t NumArgs;
13185
13186 CompareOverloadCandidatesForDisplay(
13187 Sema &S, SourceLocation Loc, size_t NArgs,
13189 : S(S), NumArgs(NArgs), CSK(CSK) {}
13190
13191 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13192 // If there are too many or too few arguments, that's the high-order bit we
13193 // want to sort by, even if the immediate failure kind was something else.
13194 if (C->FailureKind == ovl_fail_too_many_arguments ||
13195 C->FailureKind == ovl_fail_too_few_arguments)
13196 return static_cast<OverloadFailureKind>(C->FailureKind);
13197
13198 if (C->Function) {
13199 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13201 if (NumArgs < C->Function->getMinRequiredArguments())
13203 }
13204
13205 return static_cast<OverloadFailureKind>(C->FailureKind);
13206 }
13207
13208 bool operator()(const OverloadCandidate *L,
13209 const OverloadCandidate *R) {
13210 // Fast-path this check.
13211 if (L == R) return false;
13212
13213 // Order first by viability.
13214 if (L->Viable) {
13215 if (!R->Viable) return true;
13216
13217 if (int Ord = CompareConversions(*L, *R))
13218 return Ord < 0;
13219 // Use other tie breakers.
13220 } else if (R->Viable)
13221 return false;
13222
13223 assert(L->Viable == R->Viable);
13224
13225 // Criteria by which we can sort non-viable candidates:
13226 if (!L->Viable) {
13227 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13228 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13229
13230 // 1. Arity mismatches come after other candidates.
13231 if (LFailureKind == ovl_fail_too_many_arguments ||
13232 LFailureKind == ovl_fail_too_few_arguments) {
13233 if (RFailureKind == ovl_fail_too_many_arguments ||
13234 RFailureKind == ovl_fail_too_few_arguments) {
13235 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13236 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13237 if (LDist == RDist) {
13238 if (LFailureKind == RFailureKind)
13239 // Sort non-surrogates before surrogates.
13240 return !L->IsSurrogate && R->IsSurrogate;
13241 // Sort candidates requiring fewer parameters than there were
13242 // arguments given after candidates requiring more parameters
13243 // than there were arguments given.
13244 return LFailureKind == ovl_fail_too_many_arguments;
13245 }
13246 return LDist < RDist;
13247 }
13248 return false;
13249 }
13250 if (RFailureKind == ovl_fail_too_many_arguments ||
13251 RFailureKind == ovl_fail_too_few_arguments)
13252 return true;
13253
13254 // 2. Bad conversions come first and are ordered by the number
13255 // of bad conversions and quality of good conversions.
13256 if (LFailureKind == ovl_fail_bad_conversion) {
13257 if (RFailureKind != ovl_fail_bad_conversion)
13258 return true;
13259
13260 // The conversion that can be fixed with a smaller number of changes,
13261 // comes first.
13262 unsigned numLFixes = L->Fix.NumConversionsFixed;
13263 unsigned numRFixes = R->Fix.NumConversionsFixed;
13264 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13265 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13266 if (numLFixes != numRFixes) {
13267 return numLFixes < numRFixes;
13268 }
13269
13270 // If there's any ordering between the defined conversions...
13271 if (int Ord = CompareConversions(*L, *R))
13272 return Ord < 0;
13273 } else if (RFailureKind == ovl_fail_bad_conversion)
13274 return false;
13275
13276 if (LFailureKind == ovl_fail_bad_deduction) {
13277 if (RFailureKind != ovl_fail_bad_deduction)
13278 return true;
13279
13280 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13281 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13282 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13283 if (LRank != RRank)
13284 return LRank < RRank;
13285 }
13286 } else if (RFailureKind == ovl_fail_bad_deduction)
13287 return false;
13288
13289 // TODO: others?
13290 }
13291
13292 // Sort everything else by location.
13293 SourceLocation LLoc = GetLocationForCandidate(L);
13294 SourceLocation RLoc = GetLocationForCandidate(R);
13295
13296 // Put candidates without locations (e.g. builtins) at the end.
13297 if (LLoc.isValid() && RLoc.isValid())
13298 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13299 if (LLoc.isValid() && !RLoc.isValid())
13300 return true;
13301 if (RLoc.isValid() && !LLoc.isValid())
13302 return false;
13303 assert(!LLoc.isValid() && !RLoc.isValid());
13304 // For builtins and other functions without locations, fallback to the order
13305 // in which they were added into the candidate set.
13306 return L < R;
13307 }
13308
13309private:
13310 struct ConversionSignals {
13311 unsigned KindRank = 0;
13313
13314 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13315 ConversionSignals Sig;
13316 Sig.KindRank = Seq.getKindRank();
13317 if (Seq.isStandard())
13318 Sig.Rank = Seq.Standard.getRank();
13319 else if (Seq.isUserDefined())
13320 Sig.Rank = Seq.UserDefined.After.getRank();
13321 // We intend StaticObjectArgumentConversion to compare the same as
13322 // StandardConversion with ICR_ExactMatch rank.
13323 return Sig;
13324 }
13325
13326 static ConversionSignals ForObjectArgument() {
13327 // We intend StaticObjectArgumentConversion to compare the same as
13328 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13329 return {};
13330 }
13331 };
13332
13333 // Returns -1 if conversions in L are considered better.
13334 // 0 if they are considered indistinguishable.
13335 // 1 if conversions in R are better.
13336 int CompareConversions(const OverloadCandidate &L,
13337 const OverloadCandidate &R) {
13338 // We cannot use `isBetterOverloadCandidate` because it is defined
13339 // according to the C++ standard and provides a partial order, but we need
13340 // a total order as this function is used in sort.
13341 assert(L.Conversions.size() == R.Conversions.size());
13342 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13343 auto LS = L.IgnoreObjectArgument && I == 0
13344 ? ConversionSignals::ForObjectArgument()
13345 : ConversionSignals::ForSequence(L.Conversions[I]);
13346 auto RS = R.IgnoreObjectArgument
13347 ? ConversionSignals::ForObjectArgument()
13348 : ConversionSignals::ForSequence(R.Conversions[I]);
13349 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13350 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13351 ? -1
13352 : 1;
13353 }
13354 // FIXME: find a way to compare templates for being more or less
13355 // specialized that provides a strict weak ordering.
13356 return 0;
13357 }
13358};
13359}
13360
13361/// CompleteNonViableCandidate - Normally, overload resolution only
13362/// computes up to the first bad conversion. Produces the FixIt set if
13363/// possible.
13364static void
13366 ArrayRef<Expr *> Args,
13368 assert(!Cand->Viable);
13369
13370 // Don't do anything on failures other than bad conversion.
13372 return;
13373
13374 // We only want the FixIts if all the arguments can be corrected.
13375 bool Unfixable = false;
13376 // Use a implicit copy initialization to check conversion fixes.
13378
13379 // Attempt to fix the bad conversion.
13380 unsigned ConvCount = Cand->Conversions.size();
13381 for (unsigned ConvIdx =
13382 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13383 : 0);
13384 /**/; ++ConvIdx) {
13385 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13386 if (Cand->Conversions[ConvIdx].isInitialized() &&
13387 Cand->Conversions[ConvIdx].isBad()) {
13388 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13389 break;
13390 }
13391 }
13392
13393 // FIXME: this should probably be preserved from the overload
13394 // operation somehow.
13395 bool SuppressUserConversions = false;
13396
13397 unsigned ConvIdx = 0;
13398 unsigned ArgIdx = 0;
13399 ArrayRef<QualType> ParamTypes;
13400 bool Reversed = Cand->isReversed();
13401
13402 if (Cand->IsSurrogate) {
13403 QualType ConvType
13405 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13406 ConvType = ConvPtrType->getPointeeType();
13407 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13408 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13409 ConvIdx = 1;
13410 } else if (Cand->Function) {
13411 ParamTypes =
13412 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13413 if (isa<CXXMethodDecl>(Cand->Function) &&
13416 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13417 ConvIdx = 1;
13419 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13421 OO_Subscript)
13422 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13423 ArgIdx = 1;
13424 }
13425 } else {
13426 // Builtin operator.
13427 assert(ConvCount <= 3);
13428 ParamTypes = Cand->BuiltinParamTypes;
13429 }
13430
13431 // Fill in the rest of the conversions.
13432 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13433 ConvIdx != ConvCount && ArgIdx < Args.size();
13434 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13435 if (Cand->Conversions[ConvIdx].isInitialized()) {
13436 // We've already checked this conversion.
13437 } else if (ParamIdx < ParamTypes.size()) {
13438 if (ParamTypes[ParamIdx]->isDependentType())
13439 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13440 Args[ArgIdx]->getType());
13441 else {
13442 Cand->Conversions[ConvIdx] =
13443 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13444 SuppressUserConversions,
13445 /*InOverloadResolution=*/true,
13446 /*AllowObjCWritebackConversion=*/
13447 S.getLangOpts().ObjCAutoRefCount);
13448 // Store the FixIt in the candidate if it exists.
13449 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13450 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13451 }
13452 } else
13453 Cand->Conversions[ConvIdx].setEllipsis();
13454 }
13455}
13456
13459 SourceLocation OpLoc,
13460 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13461
13463
13464 // Sort the candidates by viability and position. Sorting directly would
13465 // be prohibitive, so we make a set of pointers and sort those.
13467 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13468 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13469 Cand != LastCand; ++Cand) {
13470 if (!Filter(*Cand))
13471 continue;
13472 switch (OCD) {
13473 case OCD_AllCandidates:
13474 if (!Cand->Viable) {
13475 if (!Cand->Function && !Cand->IsSurrogate) {
13476 // This a non-viable builtin candidate. We do not, in general,
13477 // want to list every possible builtin candidate.
13478 continue;
13479 }
13480 CompleteNonViableCandidate(S, Cand, Args, Kind);
13481 }
13482 break;
13483
13485 if (!Cand->Viable)
13486 continue;
13487 break;
13488
13490 if (!Cand->Best)
13491 continue;
13492 break;
13493 }
13494
13495 Cands.push_back(Cand);
13496 }
13497
13498 llvm::stable_sort(
13499 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13500
13501 return Cands;
13502}
13503
13505 SourceLocation OpLoc) {
13506 bool DeferHint = false;
13507 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13508 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13509 // host device candidates.
13510 auto WrongSidedCands =
13511 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13512 return (Cand.Viable == false &&
13514 (Cand.Function &&
13515 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13516 Cand.Function->template hasAttr<CUDADeviceAttr>());
13517 });
13518 DeferHint = !WrongSidedCands.empty();
13519 }
13520 return DeferHint;
13521}
13522
13523/// When overload resolution fails, prints diagnostic messages containing the
13524/// candidates in the candidate set.
13527 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13528 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13529
13530 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13531
13532 {
13533 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13534 S.Diag(PD.first, PD.second);
13535 }
13536
13537 // In WebAssembly we don't want to emit further diagnostics if a table is
13538 // passed as an argument to a function.
13539 bool NoteCands = true;
13540 for (const Expr *Arg : Args) {
13541 if (Arg->getType()->isWebAssemblyTableType())
13542 NoteCands = false;
13543 }
13544
13545 if (NoteCands)
13546 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13547
13548 if (OCD == OCD_AmbiguousCandidates)
13550 {Candidates.begin(), Candidates.end()});
13551}
13552
13555 StringRef Opc, SourceLocation OpLoc) {
13556 bool ReportedAmbiguousConversions = false;
13557
13558 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13559 unsigned CandsShown = 0;
13560 auto I = Cands.begin(), E = Cands.end();
13561 for (; I != E; ++I) {
13562 OverloadCandidate *Cand = *I;
13563
13564 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13565 ShowOverloads == Ovl_Best) {
13566 break;
13567 }
13568 ++CandsShown;
13569
13570 if (Cand->Function)
13571 NoteFunctionCandidate(S, Cand, Args.size(),
13572 Kind == CSK_AddressOfOverloadSet, DestAS);
13573 else if (Cand->IsSurrogate)
13574 NoteSurrogateCandidate(S, Cand);
13575 else {
13576 assert(Cand->Viable &&
13577 "Non-viable built-in candidates are not added to Cands.");
13578 // Generally we only see ambiguities including viable builtin
13579 // operators if overload resolution got screwed up by an
13580 // ambiguous user-defined conversion.
13581 //
13582 // FIXME: It's quite possible for different conversions to see
13583 // different ambiguities, though.
13584 if (!ReportedAmbiguousConversions) {
13585 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13586 ReportedAmbiguousConversions = true;
13587 }
13588
13589 // If this is a viable builtin, print it.
13590 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13591 }
13592 }
13593
13594 // Inform S.Diags that we've shown an overload set with N elements. This may
13595 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13596 S.Diags.overloadCandidatesShown(CandsShown);
13597
13598 if (I != E) {
13599 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13600 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13601 }
13602}
13603
13605 const Sema &S) const {
13606 if (S.getLangOpts().CUDA) {
13607 auto *Caller = S.getCurFunctionDecl(true);
13608 // Overloading based on __host__ and __device__ attributes takes
13609 // higher priority, HD functions may favor template candidates even when a
13610 // non-template candidate would be a perfect match.
13611 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13612 Caller->hasAttr<CUDADeviceAttr>())
13613 return false;
13614 }
13615
13616 return
13617 // For user defined conversion we need to check against different
13618 // combination of CV qualifiers and look at any explicit specifier, so
13619 // always deduce template candidates.
13621 // When doing code completion, we want to see all the
13622 // viable candidates.
13623 && Kind != CSK_CodeCompletion;
13624}
13625
13626static SourceLocation
13628 return Cand->Specialization ? Cand->Specialization->getLocation()
13629 : SourceLocation();
13630}
13631
13632namespace {
13633struct CompareTemplateSpecCandidatesForDisplay {
13634 Sema &S;
13635 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13636
13637 bool operator()(const TemplateSpecCandidate *L,
13638 const TemplateSpecCandidate *R) {
13639 // Fast-path this check.
13640 if (L == R)
13641 return false;
13642
13643 // Assuming that both candidates are not matches...
13644
13645 // Sort by the ranking of deduction failures.
13646 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13648 RankDeductionFailure(R->DeductionFailure);
13649
13650 // Sort everything else by location.
13651 SourceLocation LLoc = GetLocationForCandidate(L);
13652 SourceLocation RLoc = GetLocationForCandidate(R);
13653
13654 // Put candidates without locations (e.g. builtins) at the end.
13655 if (LLoc.isInvalid())
13656 return false;
13657 if (RLoc.isInvalid())
13658 return true;
13659
13660 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13661 }
13662};
13663}
13664
13665/// Diagnose a template argument deduction failure.
13666/// We are treating these failures as overload failures due to bad
13667/// deductions.
13669 Sema &S, bool ForTakingAddress,
13670 TemplateSpecCandidateSetKind CandidateSetKind) {
13672 DeductionFailure, /*NumArgs=*/0, ForTakingAddress,
13673 CandidateSetKind);
13674}
13675
13676void TemplateSpecCandidateSet::destroyCandidates() {
13677 for (iterator i = begin(), e = end(); i != e; ++i) {
13678 i->DeductionFailure.Destroy();
13679 }
13680}
13681
13683 destroyCandidates();
13684 Candidates.clear();
13685}
13686
13687/// NoteCandidates - When no template specialization match is found, prints
13688/// diagnostic messages containing the non-matching specializations that form
13689/// the candidate set.
13690/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13691/// OCD == OCD_AllCandidates and Cand->Viable == false.
13693 // Sort the candidates by position (assuming no candidate is a match).
13694 // Sorting directly would be prohibitive, so we make a set of pointers
13695 // and sort those.
13697 Cands.reserve(size());
13698 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13699 if (Cand->Specialization)
13700 Cands.push_back(Cand);
13701 // Otherwise, this is a non-matching builtin candidate. We do not,
13702 // in general, want to list every possible builtin candidate.
13703 }
13704
13705 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13706
13707 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13708 // for generalization purposes (?).
13709 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13710
13712 unsigned CandsShown = 0;
13713 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13714 TemplateSpecCandidate *Cand = *I;
13715
13716 // Set an arbitrary limit on the number of candidates we'll spam
13717 // the user with. FIXME: This limit should depend on details of the
13718 // candidate list.
13719 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13720 break;
13721 ++CandsShown;
13722
13723 assert(Cand->Specialization &&
13724 "Non-matching built-in candidates are not added to Cands.");
13725 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13726 }
13727
13728 if (I != E)
13729 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13730}
13731
13732// [PossiblyAFunctionType] --> [Return]
13733// NonFunctionType --> NonFunctionType
13734// R (A) --> R(A)
13735// R (*)(A) --> R (A)
13736// R (&)(A) --> R (A)
13737// R (S::*)(A) --> R (A)
13739 QualType Ret = PossiblyAFunctionType;
13740 if (const PointerType *ToTypePtr =
13741 PossiblyAFunctionType->getAs<PointerType>())
13742 Ret = ToTypePtr->getPointeeType();
13743 else if (const ReferenceType *ToTypeRef =
13744 PossiblyAFunctionType->getAs<ReferenceType>())
13745 Ret = ToTypeRef->getPointeeType();
13746 else if (const MemberPointerType *MemTypePtr =
13747 PossiblyAFunctionType->getAs<MemberPointerType>())
13748 Ret = MemTypePtr->getPointeeType();
13749 Ret =
13750 Context.getCanonicalType(Ret).getUnqualifiedType();
13751 return Ret;
13752}
13753
13755 bool Complain = true) {
13756 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13757 S.DeduceReturnType(FD, Loc, Complain))
13758 return true;
13759
13760 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13761 if (S.getLangOpts().CPlusPlus17 &&
13762 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13763 !S.ResolveExceptionSpec(Loc, FPT))
13764 return true;
13765
13766 return false;
13767}
13768
13769namespace {
13770// A helper class to help with address of function resolution
13771// - allows us to avoid passing around all those ugly parameters
13772class AddressOfFunctionResolver {
13773 Sema& S;
13774 Expr* SourceExpr;
13775 const QualType& TargetType;
13776 QualType TargetFunctionType; // Extracted function type from target type
13777
13778 bool Complain;
13779 //DeclAccessPair& ResultFunctionAccessPair;
13780 ASTContext& Context;
13781
13782 bool TargetTypeIsNonStaticMemberFunction;
13783 bool FoundNonTemplateFunction;
13784 bool StaticMemberFunctionFromBoundPointer;
13785 bool HasComplained;
13786
13787 OverloadExpr::FindResult OvlExprInfo;
13788 OverloadExpr *OvlExpr;
13789 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13790 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13791 TemplateSpecCandidateSet FailedCandidates;
13792
13793public:
13794 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13795 const QualType &TargetType, bool Complain)
13796 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13797 Complain(Complain), Context(S.getASTContext()),
13798 TargetTypeIsNonStaticMemberFunction(
13799 !!TargetType->getAs<MemberPointerType>()),
13800 FoundNonTemplateFunction(false),
13801 StaticMemberFunctionFromBoundPointer(false),
13802 HasComplained(false),
13803 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13804 OvlExpr(OvlExprInfo.Expression),
13805 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13806 ExtractUnqualifiedFunctionTypeFromTargetType();
13807
13808 if (TargetFunctionType->isFunctionType()) {
13809 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13810 if (!UME->isImplicitAccess() &&
13812 StaticMemberFunctionFromBoundPointer = true;
13813 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13814 DeclAccessPair dap;
13815 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13816 OvlExpr, false, &dap)) {
13817 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13818 if (!Method->isStatic()) {
13819 // If the target type is a non-function type and the function found
13820 // is a non-static member function, pretend as if that was the
13821 // target, it's the only possible type to end up with.
13822 TargetTypeIsNonStaticMemberFunction = true;
13823
13824 // And skip adding the function if its not in the proper form.
13825 // We'll diagnose this due to an empty set of functions.
13826 if (!OvlExprInfo.HasFormOfMemberPointer)
13827 return;
13828 }
13829
13830 Matches.push_back(std::make_pair(dap, Fn));
13831 }
13832 return;
13833 }
13834
13835 if (OvlExpr->hasExplicitTemplateArgs())
13836 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13837
13838 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13839 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13840 EliminateSuboptimalCudaMatches();
13841
13842 // C++ [over.over]p4:
13843 // If more than one function is selected, [...]
13844 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13845 if (FoundNonTemplateFunction) {
13846 EliminateAllTemplateMatches();
13847 EliminateLessPartialOrderingConstrainedMatches();
13848 } else
13849 EliminateAllExceptMostSpecializedTemplate();
13850 }
13851 }
13852 }
13853
13854 bool hasComplained() const { return HasComplained; }
13855
13856private:
13857 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13858 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13859 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13860 }
13861
13862 /// \return true if A is considered a better overload candidate for the
13863 /// desired type than B.
13864 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13865 // If A doesn't have exactly the correct type, we don't want to classify it
13866 // as "better" than anything else. This way, the user is required to
13867 // disambiguate for us if there are multiple candidates and no exact match.
13868 return candidateHasExactlyCorrectType(A) &&
13869 (!candidateHasExactlyCorrectType(B) ||
13870 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13871 }
13872
13873 /// \return true if we were able to eliminate all but one overload candidate,
13874 /// false otherwise.
13875 bool eliminiateSuboptimalOverloadCandidates() {
13876 // Same algorithm as overload resolution -- one pass to pick the "best",
13877 // another pass to be sure that nothing is better than the best.
13878 auto Best = Matches.begin();
13879 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13880 if (isBetterCandidate(I->second, Best->second))
13881 Best = I;
13882
13883 const FunctionDecl *BestFn = Best->second;
13884 auto IsBestOrInferiorToBest = [this, BestFn](
13885 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13886 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13887 };
13888
13889 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13890 // option, so we can potentially give the user a better error
13891 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13892 return false;
13893 Matches[0] = *Best;
13894 Matches.resize(1);
13895 return true;
13896 }
13897
13898 bool isTargetTypeAFunction() const {
13899 return TargetFunctionType->isFunctionType();
13900 }
13901
13902 // [ToType] [Return]
13903
13904 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13905 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13906 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13907 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13908 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13909 }
13910
13911 // return true if any matching specializations were found
13912 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13913 const DeclAccessPair& CurAccessFunPair) {
13914 if (CXXMethodDecl *Method
13915 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13916 // Skip non-static function templates when converting to pointer, and
13917 // static when converting to member pointer.
13918 bool CanConvertToFunctionPointer =
13919 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13920 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13921 return false;
13922 }
13923 else if (TargetTypeIsNonStaticMemberFunction)
13924 return false;
13925
13926 // C++ [over.over]p2:
13927 // If the name is a function template, template argument deduction is
13928 // done (14.8.2.2), and if the argument deduction succeeds, the
13929 // resulting template argument list is used to generate a single
13930 // function template specialization, which is added to the set of
13931 // overloaded functions considered.
13932 FunctionDecl *Specialization = nullptr;
13933 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13935 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13936 Specialization, Info, /*IsAddressOfFunction*/ true);
13937 Result != TemplateDeductionResult::Success) {
13938 // Make a note of the failed deduction for diagnostics.
13939 FailedCandidates.addCandidate()
13940 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13941 MakeDeductionFailureInfo(Context, Result, Info));
13942 return false;
13943 }
13944
13945 // Template argument deduction ensures that we have an exact match or
13946 // compatible pointer-to-function arguments that would be adjusted by ICS.
13947 // This function template specicalization works.
13949 Context.getCanonicalType(Specialization->getType()),
13950 Context.getCanonicalType(TargetFunctionType)));
13951
13953 return false;
13954
13955 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13956 return true;
13957 }
13958
13959 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13960 const DeclAccessPair& CurAccessFunPair) {
13961 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13962 // Skip non-static functions when converting to pointer, and static
13963 // when converting to member pointer.
13964 bool CanConvertToFunctionPointer =
13965 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13966 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13967 return false;
13968 }
13969 else if (TargetTypeIsNonStaticMemberFunction)
13970 return false;
13971
13972 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13973 if (S.getLangOpts().CUDA) {
13974 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13975 if (!(Caller && Caller->isImplicit()) &&
13976 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13977 return false;
13978 }
13979 if (FunDecl->isMultiVersion()) {
13980 const auto *TA = FunDecl->getAttr<TargetAttr>();
13981 if (TA && !TA->isDefaultVersion())
13982 return false;
13983 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13984 if (TVA && !TVA->isDefaultVersion())
13985 return false;
13986 }
13987
13988 // If any candidate has a placeholder return type, trigger its deduction
13989 // now.
13990 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13991 Complain)) {
13992 HasComplained |= Complain;
13993 return false;
13994 }
13995
13996 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13997 return false;
13998
13999 // If we're in C, we need to support types that aren't exactly identical.
14000 if (!S.getLangOpts().CPlusPlus ||
14001 candidateHasExactlyCorrectType(FunDecl)) {
14002 Matches.push_back(std::make_pair(
14003 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
14004 FoundNonTemplateFunction = true;
14005 return true;
14006 }
14007 }
14008
14009 return false;
14010 }
14011
14012 bool FindAllFunctionsThatMatchTargetTypeExactly() {
14013 bool Ret = false;
14014
14015 // If the overload expression doesn't have the form of a pointer to
14016 // member, don't try to convert it to a pointer-to-member type.
14017 if (IsInvalidFormOfPointerToMemberFunction())
14018 return false;
14019
14020 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14021 E = OvlExpr->decls_end();
14022 I != E; ++I) {
14023 // Look through any using declarations to find the underlying function.
14024 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14025
14026 // C++ [over.over]p3:
14027 // Non-member functions and static member functions match
14028 // targets of type "pointer-to-function" or "reference-to-function."
14029 // Nonstatic member functions match targets of
14030 // type "pointer-to-member-function."
14031 // Note that according to DR 247, the containing class does not matter.
14032 if (FunctionTemplateDecl *FunctionTemplate
14033 = dyn_cast<FunctionTemplateDecl>(Fn)) {
14034 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
14035 Ret = true;
14036 }
14037 // If we have explicit template arguments supplied, skip non-templates.
14038 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14039 AddMatchingNonTemplateFunction(Fn, I.getPair()))
14040 Ret = true;
14041 }
14042 assert(Ret || Matches.empty());
14043 return Ret;
14044 }
14045
14046 void EliminateAllExceptMostSpecializedTemplate() {
14047 // [...] and any given function template specialization F1 is
14048 // eliminated if the set contains a second function template
14049 // specialization whose function template is more specialized
14050 // than the function template of F1 according to the partial
14051 // ordering rules of 14.5.5.2.
14052
14053 // The algorithm specified above is quadratic. We instead use a
14054 // two-pass algorithm (similar to the one used to identify the
14055 // best viable function in an overload set) that identifies the
14056 // best function template (if it exists).
14057
14058 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14059 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14060 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14061
14062 // TODO: It looks like FailedCandidates does not serve much purpose
14063 // here, since the no_viable diagnostic has index 0.
14064 UnresolvedSetIterator Result = S.getMostSpecialized(
14065 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14066 SourceExpr->getBeginLoc(), S.PDiag(),
14067 S.PDiag(diag::err_addr_ovl_ambiguous)
14068 << Matches[0].second->getDeclName(),
14069 S.PDiag(diag::note_ovl_candidate)
14070 << (unsigned)oc_function << (unsigned)ocs_described_template,
14071 Complain, TargetFunctionType);
14072
14073 if (Result != MatchesCopy.end()) {
14074 // Make it the first and only element
14075 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14076 Matches[0].second = cast<FunctionDecl>(*Result);
14077 Matches.resize(1);
14078 } else
14079 HasComplained |= Complain;
14080 }
14081
14082 void EliminateAllTemplateMatches() {
14083 // [...] any function template specializations in the set are
14084 // eliminated if the set also contains a non-template function, [...]
14085 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14086 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14087 ++I;
14088 else {
14089 Matches[I] = Matches[--N];
14090 Matches.resize(N);
14091 }
14092 }
14093 }
14094
14095 void EliminateLessPartialOrderingConstrainedMatches() {
14096 // C++ [over.over]p5:
14097 // [...] Any given non-template function F0 is eliminated if the set
14098 // contains a second non-template function that is more
14099 // partial-ordering-constrained than F0. [...]
14100 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14101 "Call EliminateAllTemplateMatches() first");
14102 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14103 Results.push_back(Matches[0]);
14104 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14105 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14106 FunctionDecl *F = getMorePartialOrderingConstrained(
14107 S, Matches[I].second, Results[0].second,
14108 /*IsFn1Reversed=*/false,
14109 /*IsFn2Reversed=*/false);
14110 if (!F) {
14111 Results.push_back(Matches[I]);
14112 continue;
14113 }
14114 if (F == Matches[I].second) {
14115 Results.clear();
14116 Results.push_back(Matches[I]);
14117 }
14118 }
14119 std::swap(Matches, Results);
14120 }
14121
14122 void EliminateSuboptimalCudaMatches() {
14123 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14124 Matches);
14125 }
14126
14127public:
14128 void ComplainNoMatchesFound() const {
14129 assert(Matches.empty());
14130 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14131 << OvlExpr->getName() << TargetFunctionType
14132 << OvlExpr->getSourceRange();
14133 if (FailedCandidates.empty())
14134 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14135 /*TakingAddress=*/true);
14136 else {
14137 // We have some deduction failure messages. Use them to diagnose
14138 // the function templates, and diagnose the non-template candidates
14139 // normally.
14140 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14141 IEnd = OvlExpr->decls_end();
14142 I != IEnd; ++I)
14143 if (FunctionDecl *Fun =
14144 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14146 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14147 /*TakingAddress=*/true);
14148 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14149 }
14150 }
14151
14152 bool IsInvalidFormOfPointerToMemberFunction() const {
14153 return TargetTypeIsNonStaticMemberFunction &&
14154 !OvlExprInfo.HasFormOfMemberPointer;
14155 }
14156
14157 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14158 // TODO: Should we condition this on whether any functions might
14159 // have matched, or is it more appropriate to do that in callers?
14160 // TODO: a fixit wouldn't hurt.
14161 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14162 << TargetType << OvlExpr->getSourceRange();
14163 }
14164
14165 bool IsStaticMemberFunctionFromBoundPointer() const {
14166 return StaticMemberFunctionFromBoundPointer;
14167 }
14168
14169 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14170 S.Diag(OvlExpr->getBeginLoc(),
14171 diag::err_invalid_form_pointer_member_function)
14172 << OvlExpr->getSourceRange();
14173 }
14174
14175 void ComplainOfInvalidConversion() const {
14176 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14177 << OvlExpr->getName() << TargetType;
14178 }
14179
14180 void ComplainMultipleMatchesFound() const {
14181 assert(Matches.size() > 1);
14182 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14183 << OvlExpr->getName() << OvlExpr->getSourceRange();
14184 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14185 /*TakingAddress=*/true);
14186 }
14187
14188 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14189
14190 int getNumMatches() const { return Matches.size(); }
14191
14192 FunctionDecl* getMatchingFunctionDecl() const {
14193 if (Matches.size() != 1) return nullptr;
14194 return Matches[0].second;
14195 }
14196
14197 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14198 if (Matches.size() != 1) return nullptr;
14199 return &Matches[0].first;
14200 }
14201};
14202}
14203
14204FunctionDecl *
14206 QualType TargetType,
14207 bool Complain,
14208 DeclAccessPair &FoundResult,
14209 bool *pHadMultipleCandidates) {
14210 assert(AddressOfExpr->getType() == Context.OverloadTy);
14211
14212 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14213 Complain);
14214 int NumMatches = Resolver.getNumMatches();
14215 FunctionDecl *Fn = nullptr;
14216 bool ShouldComplain = Complain && !Resolver.hasComplained();
14217 if (NumMatches == 0 && ShouldComplain) {
14218 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14219 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14220 else
14221 Resolver.ComplainNoMatchesFound();
14222 }
14223 else if (NumMatches > 1 && ShouldComplain)
14224 Resolver.ComplainMultipleMatchesFound();
14225 else if (NumMatches == 1) {
14226 Fn = Resolver.getMatchingFunctionDecl();
14227 assert(Fn);
14228 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14229 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14230 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14231 if (Complain) {
14232 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14233 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14234 else
14235 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14236 }
14237 }
14238
14239 if (pHadMultipleCandidates)
14240 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14241 return Fn;
14242}
14243
14247 OverloadExpr *Ovl = R.Expression;
14248 bool IsResultAmbiguous = false;
14249 FunctionDecl *Result = nullptr;
14250 DeclAccessPair DAP;
14251 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14252
14253 // Return positive for better, negative for worse, 0 for equal preference.
14254 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14255 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14256 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14257 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14258 };
14259
14260 // Don't use the AddressOfResolver because we're specifically looking for
14261 // cases where we have one overload candidate that lacks
14262 // enable_if/pass_object_size/...
14263 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14264 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14265 if (!FD)
14266 return nullptr;
14267
14269 continue;
14270
14271 // If we found a better result, update Result.
14272 auto FoundBetter = [&]() {
14273 IsResultAmbiguous = false;
14274 DAP = I.getPair();
14275 Result = FD;
14276 };
14277
14278 // We have more than one result - see if it is more
14279 // partial-ordering-constrained than the previous one.
14280 if (Result) {
14281 // Check CUDA preference first. If the candidates have differennt CUDA
14282 // preference, choose the one with higher CUDA preference. Otherwise,
14283 // choose the one with more constraints.
14284 if (getLangOpts().CUDA) {
14285 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14286 // FD has different preference than Result.
14287 if (PreferenceByCUDA != 0) {
14288 // FD is more preferable than Result.
14289 if (PreferenceByCUDA > 0)
14290 FoundBetter();
14291 continue;
14292 }
14293 }
14294 // FD has the same CUDA preference than Result. Continue to check
14295 // constraints.
14296
14297 // C++ [over.over]p5:
14298 // [...] Any given non-template function F0 is eliminated if the set
14299 // contains a second non-template function that is more
14300 // partial-ordering-constrained than F0 [...]
14301 FunctionDecl *MoreConstrained =
14303 /*IsFn1Reversed=*/false,
14304 /*IsFn2Reversed=*/false);
14305 if (MoreConstrained != FD) {
14306 if (!MoreConstrained) {
14307 IsResultAmbiguous = true;
14308 AmbiguousDecls.push_back(FD);
14309 }
14310 continue;
14311 }
14312 // FD is more constrained - replace Result with it.
14313 }
14314 FoundBetter();
14315 }
14316
14317 if (IsResultAmbiguous)
14318 return nullptr;
14319
14320 if (Result) {
14321 // We skipped over some ambiguous declarations which might be ambiguous with
14322 // the selected result.
14323 for (FunctionDecl *Skipped : AmbiguousDecls) {
14324 // If skipped candidate has different CUDA preference than the result,
14325 // there is no ambiguity. Otherwise check whether they have different
14326 // constraints.
14327 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14328 continue;
14329 if (!getMoreConstrainedFunction(Skipped, Result))
14330 return nullptr;
14331 }
14332 Pair = DAP;
14333 }
14334 return Result;
14335}
14336
14338 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14339 Expr *E = SrcExpr.get();
14340 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14341
14342 DeclAccessPair DAP;
14344 if (!Found || Found->isCPUDispatchMultiVersion() ||
14345 Found->isCPUSpecificMultiVersion())
14346 return false;
14347
14348 // Emitting multiple diagnostics for a function that is both inaccessible and
14349 // unavailable is consistent with our behavior elsewhere. So, always check
14350 // for both.
14354 if (Res.isInvalid())
14355 return false;
14356 Expr *Fixed = Res.get();
14357 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14358 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14359 else
14360 SrcExpr = Fixed;
14361 return true;
14362}
14363
14365 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14366 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14367 // C++ [over.over]p1:
14368 // [...] [Note: any redundant set of parentheses surrounding the
14369 // overloaded function name is ignored (5.1). ]
14370 // C++ [over.over]p1:
14371 // [...] The overloaded function name can be preceded by the &
14372 // operator.
14373
14374 // If we didn't actually find any template-ids, we're done.
14375 if (!ovl->hasExplicitTemplateArgs())
14376 return nullptr;
14377
14378 TemplateArgumentListInfo ExplicitTemplateArgs;
14379 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14380
14381 // Look through all of the overloaded functions, searching for one
14382 // whose type matches exactly.
14383 FunctionDecl *Matched = nullptr;
14384 for (UnresolvedSetIterator I = ovl->decls_begin(),
14385 E = ovl->decls_end(); I != E; ++I) {
14386 // C++0x [temp.arg.explicit]p3:
14387 // [...] In contexts where deduction is done and fails, or in contexts
14388 // where deduction is not done, if a template argument list is
14389 // specified and it, along with any default template arguments,
14390 // identifies a single function template specialization, then the
14391 // template-id is an lvalue for the function template specialization.
14393 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14394 if (!FunctionTemplate)
14395 continue;
14396
14397 // C++ [over.over]p2:
14398 // If the name is a function template, template argument deduction is
14399 // done (14.8.2.2), and if the argument deduction succeeds, the
14400 // resulting template argument list is used to generate a single
14401 // function template specialization, which is added to the set of
14402 // overloaded functions considered.
14403 FunctionDecl *Specialization = nullptr;
14404 TemplateDeductionInfo Info(ovl->getNameLoc());
14406 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14407 /*IsAddressOfFunction*/ true);
14409 // Make a note of the failed deduction for diagnostics.
14410 if (FailedTSC)
14411 FailedTSC->addCandidate().set(
14412 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14414 continue;
14415 }
14416
14417 assert(Specialization && "no specialization and no error?");
14418
14419 // C++ [temp.deduct.call]p6:
14420 // [...] If all successful deductions yield the same deduced A, that
14421 // deduced A is the result of deduction; otherwise, the parameter is
14422 // treated as a non-deduced context.
14423 if (Matched) {
14424 if (ForTypeDeduction &&
14426 Specialization->getType()))
14427 continue;
14428 // Multiple matches; we can't resolve to a single declaration.
14429 if (Complain) {
14430 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14431 << ovl->getName();
14433 }
14434 return nullptr;
14435 }
14436
14437 Matched = Specialization;
14438 if (FoundResult) *FoundResult = I.getPair();
14439 }
14440
14441 if (Matched &&
14442 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14443 return nullptr;
14444
14445 return Matched;
14446}
14447
14449 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14450 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14451 unsigned DiagIDForComplaining) {
14452 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14453
14455
14456 DeclAccessPair found;
14457 ExprResult SingleFunctionExpression;
14459 ovl.Expression, /*complain*/ false, &found)) {
14460 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14461 SrcExpr = ExprError();
14462 return true;
14463 }
14464
14465 // It is only correct to resolve to an instance method if we're
14466 // resolving a form that's permitted to be a pointer to member.
14467 // Otherwise we'll end up making a bound member expression, which
14468 // is illegal in all the contexts we resolve like this.
14469 if (!ovl.HasFormOfMemberPointer &&
14470 isa<CXXMethodDecl>(fn) &&
14471 cast<CXXMethodDecl>(fn)->isInstance()) {
14472 if (!complain) return false;
14473
14474 Diag(ovl.Expression->getExprLoc(),
14475 diag::err_bound_member_function)
14476 << 0 << ovl.Expression->getSourceRange();
14477
14478 // TODO: I believe we only end up here if there's a mix of
14479 // static and non-static candidates (otherwise the expression
14480 // would have 'bound member' type, not 'overload' type).
14481 // Ideally we would note which candidate was chosen and why
14482 // the static candidates were rejected.
14483 SrcExpr = ExprError();
14484 return true;
14485 }
14486
14487 // Fix the expression to refer to 'fn'.
14488 SingleFunctionExpression =
14489 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14490
14491 // If desired, do function-to-pointer decay.
14492 if (doFunctionPointerConversion) {
14493 SingleFunctionExpression =
14494 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14495 if (SingleFunctionExpression.isInvalid()) {
14496 SrcExpr = ExprError();
14497 return true;
14498 }
14499 }
14500 }
14501
14502 if (!SingleFunctionExpression.isUsable()) {
14503 if (complain) {
14504 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14505 << ovl.Expression->getName()
14506 << DestTypeForComplaining
14507 << OpRangeForComplaining
14509 NoteAllOverloadCandidates(SrcExpr.get());
14510
14511 SrcExpr = ExprError();
14512 return true;
14513 }
14514
14515 return false;
14516 }
14517
14518 SrcExpr = SingleFunctionExpression;
14519 return true;
14520}
14521
14522/// Add a single candidate to the overload set.
14524 DeclAccessPair FoundDecl,
14525 TemplateArgumentListInfo *ExplicitTemplateArgs,
14526 ArrayRef<Expr *> Args,
14527 OverloadCandidateSet &CandidateSet,
14528 bool PartialOverloading,
14529 bool KnownValid) {
14530 NamedDecl *Callee = FoundDecl.getDecl();
14531 if (isa<UsingShadowDecl>(Callee))
14532 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14533
14534 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14535 if (ExplicitTemplateArgs) {
14536 assert(!KnownValid && "Explicit template arguments?");
14537 return;
14538 }
14539 // Prevent ill-formed function decls to be added as overload candidates.
14540 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14541 return;
14542
14543 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14544 /*SuppressUserConversions=*/false,
14545 PartialOverloading);
14546 return;
14547 }
14548
14549 if (FunctionTemplateDecl *FuncTemplate
14550 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14551 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14552 ExplicitTemplateArgs, Args, CandidateSet,
14553 /*SuppressUserConversions=*/false,
14554 PartialOverloading);
14555 return;
14556 }
14557
14558 assert(!KnownValid && "unhandled case in overloaded call candidate");
14559}
14560
14562 ArrayRef<Expr *> Args,
14563 OverloadCandidateSet &CandidateSet,
14564 bool PartialOverloading) {
14565
14566#ifndef NDEBUG
14567 // Verify that ArgumentDependentLookup is consistent with the rules
14568 // in C++0x [basic.lookup.argdep]p3:
14569 //
14570 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14571 // and let Y be the lookup set produced by argument dependent
14572 // lookup (defined as follows). If X contains
14573 //
14574 // -- a declaration of a class member, or
14575 //
14576 // -- a block-scope function declaration that is not a
14577 // using-declaration, or
14578 //
14579 // -- a declaration that is neither a function or a function
14580 // template
14581 //
14582 // then Y is empty.
14583
14584 if (ULE->requiresADL()) {
14586 E = ULE->decls_end(); I != E; ++I) {
14587 assert(!(*I)->getDeclContext()->isRecord());
14588 assert(isa<UsingShadowDecl>(*I) ||
14589 !(*I)->getDeclContext()->isFunctionOrMethod());
14590 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14591 }
14592 }
14593#endif
14594
14595 // It would be nice to avoid this copy.
14596 TemplateArgumentListInfo TABuffer;
14597 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14598 if (ULE->hasExplicitTemplateArgs()) {
14599 ULE->copyTemplateArgumentsInto(TABuffer);
14600 ExplicitTemplateArgs = &TABuffer;
14601 }
14602
14604 E = ULE->decls_end(); I != E; ++I)
14605 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14606 CandidateSet, PartialOverloading,
14607 /*KnownValid*/ true);
14608
14609 if (ULE->requiresADL())
14611 Args, ExplicitTemplateArgs,
14612 CandidateSet, PartialOverloading);
14613}
14614
14616 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14617 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14618 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14619 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14620 CandidateSet, false, /*KnownValid*/ false);
14621}
14622
14623/// Determine whether a declaration with the specified name could be moved into
14624/// a different namespace.
14626 switch (Name.getCXXOverloadedOperator()) {
14627 case OO_New: case OO_Array_New:
14628 case OO_Delete: case OO_Array_Delete:
14629 return false;
14630
14631 default:
14632 return true;
14633 }
14634}
14635
14636/// Attempt to recover from an ill-formed use of a non-dependent name in a
14637/// template, where the non-dependent name was declared after the template
14638/// was defined. This is common in code written for compilers which do not
14639/// correctly implement two-stage name lookup.
14640///
14641/// Returns true if a viable candidate was found and a diagnostic was issued.
14643 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14645 const OverloadCandidateSet &ResolvedCandidates,
14646 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14647 CXXRecordDecl **FoundInClass = nullptr) {
14648 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14649 return false;
14650
14651 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14652 if (DC->isTransparentContext())
14653 continue;
14654
14655 SemaRef.LookupQualifiedName(R, DC);
14656
14657 if (!R.empty()) {
14658 R.suppressDiagnostics();
14659
14660 OverloadCandidateSet Candidates(FnLoc, CSK);
14661 // We have performed a BestViableFunction over these candidates, so
14662 // exclude them.
14663 for (auto &Cand : ResolvedCandidates) {
14664 if (Cand.Function)
14665 Candidates.exclude(Cand.Function);
14666 else if (Cand.IsSurrogate)
14667 Candidates.exclude(Cand.Surrogate);
14668 }
14669 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14670 Candidates);
14671
14674 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14675
14676 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14677 // We either found non-function declarations or a best viable function
14678 // at class scope. A class-scope lookup result disables ADL. Don't
14679 // look past this, but let the caller know that we found something that
14680 // either is, or might be, usable in this class.
14681 if (FoundInClass) {
14682 *FoundInClass = RD;
14683 if (OR == OR_Success) {
14684 R.clear();
14685 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14686 R.resolveKind();
14687 }
14688 }
14689 return false;
14690 }
14691
14692 if (OR != OR_Success) {
14693 // There wasn't a unique best function or function template.
14694 return false;
14695 }
14696
14697 // Find the namespaces where ADL would have looked, and suggest
14698 // declaring the function there instead.
14699 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14700 Sema::AssociatedClassSet AssociatedClasses;
14701 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14702 AssociatedNamespaces,
14703 AssociatedClasses);
14704 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14705 if (canBeDeclaredInNamespace(R.getLookupName())) {
14706 DeclContext *Std = SemaRef.getStdNamespace();
14707 for (Sema::AssociatedNamespaceSet::iterator
14708 it = AssociatedNamespaces.begin(),
14709 end = AssociatedNamespaces.end(); it != end; ++it) {
14710 // Never suggest declaring a function within namespace 'std'.
14711 if (Std && Std->Encloses(*it))
14712 continue;
14713
14714 // Never suggest declaring a function within a namespace with a
14715 // reserved name, like __gnu_cxx.
14716 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14717 if (NS &&
14718 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14719 continue;
14720
14721 SuggestedNamespaces.insert(*it);
14722 }
14723 }
14724
14725 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14726 << R.getLookupName();
14727 if (SuggestedNamespaces.empty()) {
14728 SemaRef.Diag(Best->Function->getLocation(),
14729 diag::note_not_found_by_two_phase_lookup)
14730 << R.getLookupName() << 0;
14731 } else if (SuggestedNamespaces.size() == 1) {
14732 SemaRef.Diag(Best->Function->getLocation(),
14733 diag::note_not_found_by_two_phase_lookup)
14734 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14735 } else {
14736 // FIXME: It would be useful to list the associated namespaces here,
14737 // but the diagnostics infrastructure doesn't provide a way to produce
14738 // a localized representation of a list of items.
14739 SemaRef.Diag(Best->Function->getLocation(),
14740 diag::note_not_found_by_two_phase_lookup)
14741 << R.getLookupName() << 2;
14742 }
14743
14744 // Try to recover by calling this function.
14745 return true;
14746 }
14747
14748 R.clear();
14749 }
14750
14751 return false;
14752}
14753
14754/// Attempt to recover from ill-formed use of a non-dependent operator in a
14755/// template, where the non-dependent operator was declared after the template
14756/// was defined.
14757///
14758/// Returns true if a viable candidate was found and a diagnostic was issued.
14760 Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc,
14761 ArrayRef<Expr *> Args, const OverloadCandidateSet &ResolvedCandidateSet) {
14762 DeclarationName OpName =
14764 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14767 ResolvedCandidateSet,
14768 /*ExplicitTemplateArgs=*/nullptr, Args, /*FoundInClass=*/nullptr);
14769}
14770
14771namespace {
14772class BuildRecoveryCallExprRAII {
14773 Sema &SemaRef;
14774 Sema::SatisfactionStackResetRAII SatStack;
14775
14776public:
14777 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14778 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14779 SemaRef.IsBuildingRecoveryCallExpr = true;
14780 }
14781
14782 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14783};
14784}
14785
14786/// Attempts to recover from a call where no functions were found.
14787///
14788/// This function will do one of three things:
14789/// * Diagnose, recover, and return a recovery expression.
14790/// * Diagnose, fail to recover, and return ExprError().
14791/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14792/// expected to diagnose as appropriate.
14793static ExprResult
14795 UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
14797 const OverloadCandidateSet &ResolvedCandidateSet,
14798 bool AllowTypoCorrection) {
14799 // Do not try to recover if it is already building a recovery call.
14800 // This stops infinite loops for template instantiations like
14801 //
14802 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14803 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14804 if (SemaRef.IsBuildingRecoveryCallExpr)
14805 return ExprResult();
14806 BuildRecoveryCallExprRAII RCE(SemaRef);
14807
14808 CXXScopeSpec SS;
14809 SS.Adopt(ULE->getQualifierLoc());
14810 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14811
14812 TemplateArgumentListInfo TABuffer;
14813 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14814 if (ULE->hasExplicitTemplateArgs()) {
14815 ULE->copyTemplateArgumentsInto(TABuffer);
14816 ExplicitTemplateArgs = &TABuffer;
14817 }
14818
14819 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14821 CXXRecordDecl *FoundInClass = nullptr;
14823 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
14824 ResolvedCandidateSet, ExplicitTemplateArgs, Args, &FoundInClass)) {
14825 // OK, diagnosed a two-phase lookup issue.
14826 } else if (ResolvedCandidateSet.empty()) {
14827 // Try to recover from an empty lookup with typo correction.
14828 R.clear();
14829 NoTypoCorrectionCCC NoTypoValidator{};
14830 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14831 ExplicitTemplateArgs != nullptr,
14832 dyn_cast<MemberExpr>(Fn));
14833 CorrectionCandidateCallback &Validator =
14834 AllowTypoCorrection
14835 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14836 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14837 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14838 Args))
14839 return ExprError();
14840 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14841 // We found a usable declaration of the name in a dependent base of some
14842 // enclosing class.
14843 // FIXME: We should also explain why the candidates found by name lookup
14844 // were not viable.
14845 if (SemaRef.DiagnoseDependentMemberLookup(R))
14846 return ExprError();
14847 } else {
14848 // We had viable candidates and couldn't recover; let the caller diagnose
14849 // this.
14850 return ExprResult();
14851 }
14852
14853 // If we get here, we should have issued a diagnostic and formed a recovery
14854 // lookup result.
14855 assert(!R.empty() && "lookup results empty despite recovery");
14856
14857 // If recovery created an ambiguity, just bail out.
14858 if (R.isAmbiguous()) {
14859 R.suppressDiagnostics();
14860 return ExprError();
14861 }
14862
14863 // Build an implicit member call if appropriate. Just drop the
14864 // casts and such from the call, we don't really care.
14865 ExprResult NewFn = ExprError();
14866 if ((*R.begin())->isCXXClassMember())
14867 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14868 ExplicitTemplateArgs, S);
14869 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14870 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14871 ExplicitTemplateArgs);
14872 else
14873 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14874
14875 if (NewFn.isInvalid())
14876 return ExprError();
14877
14878 // This shouldn't cause an infinite loop because we're giving it
14879 // an expression with viable lookup results, which should never
14880 // end up here.
14881 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14882 MultiExprArg(Args.data(), Args.size()),
14883 RParenLoc);
14884}
14885
14888 MultiExprArg Args,
14889 SourceLocation RParenLoc,
14890 OverloadCandidateSet *CandidateSet,
14891 ExprResult *Result) {
14892#ifndef NDEBUG
14893 if (ULE->requiresADL()) {
14894 // To do ADL, we must have found an unqualified name.
14895 assert(!ULE->getQualifier() && "qualified name with ADL");
14896
14897 // We don't perform ADL for implicit declarations of builtins.
14898 // Verify that this was correctly set up.
14899 FunctionDecl *F;
14900 if (ULE->decls_begin() != ULE->decls_end() &&
14901 ULE->decls_begin() + 1 == ULE->decls_end() &&
14902 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14903 F->getBuiltinID() && F->isImplicit())
14904 llvm_unreachable("performing ADL for builtin");
14905
14906 // We don't perform ADL in C.
14907 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14908 }
14909#endif
14910
14911 UnbridgedCastsSet UnbridgedCasts;
14912 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14913 *Result = ExprError();
14914 return true;
14915 }
14916
14917 // Add the functions denoted by the callee to the set of candidate
14918 // functions, including those from argument-dependent lookup.
14919 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14920
14921 if (getLangOpts().MSVCCompat &&
14922 CurContext->isDependentContext() && !isSFINAEContext() &&
14924
14926 if (CandidateSet->empty() ||
14927 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14929 // In Microsoft mode, if we are inside a template class member function
14930 // then create a type dependent CallExpr. The goal is to postpone name
14931 // lookup to instantiation time to be able to search into type dependent
14932 // base classes.
14933 CallExpr *CE =
14934 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14935 RParenLoc, CurFPFeatureOverrides());
14937 *Result = CE;
14938 return true;
14939 }
14940 }
14941
14942 if (CandidateSet->empty())
14943 return false;
14944
14945 UnbridgedCasts.restore();
14946 return false;
14947}
14948
14949// Guess at what the return type for an unresolvable overload should be.
14952 std::optional<QualType> Result;
14953 // Adjust Type after seeing a candidate.
14954 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14955 if (!Candidate.Function)
14956 return;
14957 if (Candidate.Function->isInvalidDecl())
14958 return;
14959 QualType T = Candidate.Function->getReturnType();
14960 if (T.isNull())
14961 return;
14962 if (!Result)
14963 Result = T;
14964 else if (Result != T)
14965 Result = QualType();
14966 };
14967
14968 // Look for an unambiguous type from a progressively larger subset.
14969 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14970 //
14971 // First, consider only the best candidate.
14972 if (Best && *Best != CS.end())
14973 ConsiderCandidate(**Best);
14974 // Next, consider only viable candidates.
14975 if (!Result)
14976 for (const auto &C : CS)
14977 if (C.Viable)
14978 ConsiderCandidate(C);
14979 // Finally, consider all candidates.
14980 if (!Result)
14981 for (const auto &C : CS)
14982 ConsiderCandidate(C);
14983
14984 if (!Result)
14985 return QualType();
14986 auto Value = *Result;
14987 if (Value.isNull() || Value->isUndeducedType())
14988 return QualType();
14989 return Value;
14990}
14991
14992/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14993/// the completed call expression. If overload resolution fails, emits
14994/// diagnostics and returns ExprError()
14997 SourceLocation LParenLoc,
14998 MultiExprArg Args,
14999 SourceLocation RParenLoc,
15000 Expr *ExecConfig,
15001 OverloadCandidateSet *CandidateSet,
15003 OverloadingResult OverloadResult,
15004 bool AllowTypoCorrection) {
15005 switch (OverloadResult) {
15006 case OR_Success: {
15007 FunctionDecl *FDecl = (*Best)->Function;
15008 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
15009 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
15010 return ExprError();
15011 ExprResult Res =
15012 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15013 if (Res.isInvalid())
15014 return ExprError();
15015 return SemaRef.BuildResolvedCallExpr(
15016 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15017 /*IsExecConfig=*/false,
15018 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15019 }
15020
15021 case OR_No_Viable_Function: {
15022 if (*Best != CandidateSet->end() &&
15023 CandidateSet->getKind() ==
15025 if (CXXMethodDecl *M =
15026 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
15028 CandidateSet->NoteCandidates(
15030 Fn->getBeginLoc(),
15031 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
15032 SemaRef, OCD_AmbiguousCandidates, Args);
15033 return ExprError();
15034 }
15035 }
15036
15037 // Try to recover by looking for viable functions which the user might
15038 // have meant to call.
15039 ExprResult Recovery =
15040 BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15041 *CandidateSet, AllowTypoCorrection);
15042 if (Recovery.isInvalid() || Recovery.isUsable())
15043 return Recovery;
15044
15045 // If the user passes in a function that we can't take the address of, we
15046 // generally end up emitting really bad error messages. Here, we attempt to
15047 // emit better ones.
15048 for (const Expr *Arg : Args) {
15049 if (!Arg->getType()->isFunctionType())
15050 continue;
15051 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
15052 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15053 if (FD &&
15054 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15055 Arg->getExprLoc()))
15056 return ExprError();
15057 }
15058 }
15059
15060 CandidateSet->NoteCandidates(
15062 Fn->getBeginLoc(),
15063 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15064 << ULE->getName() << Fn->getSourceRange()),
15065 SemaRef, OCD_AllCandidates, Args);
15066 break;
15067 }
15068
15069 case OR_Ambiguous:
15070 CandidateSet->NoteCandidates(
15071 PartialDiagnosticAt(Fn->getBeginLoc(),
15072 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15073 << ULE->getName() << Fn->getSourceRange()),
15074 SemaRef, OCD_AmbiguousCandidates, Args);
15075 break;
15076
15077 case OR_Deleted: {
15078 FunctionDecl *FDecl = (*Best)->Function;
15079 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15080 Fn->getSourceRange(), ULE->getName(),
15081 *CandidateSet, FDecl, Args);
15082
15083 // We emitted an error for the unavailable/deleted function call but keep
15084 // the call in the AST.
15085 ExprResult Res =
15086 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15087 if (Res.isInvalid())
15088 return ExprError();
15089 return SemaRef.BuildResolvedCallExpr(
15090 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15091 /*IsExecConfig=*/false,
15092 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15093 }
15094 }
15095
15096 // Overload resolution failed, try to recover.
15097 SmallVector<Expr *, 8> SubExprs = {Fn};
15098 SubExprs.append(Args.begin(), Args.end());
15099 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15100 chooseRecoveryType(*CandidateSet, Best));
15101}
15102
15105 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15106 if (I->Viable &&
15107 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15108 I->Viable = false;
15109 I->FailureKind = ovl_fail_addr_not_available;
15110 }
15111 }
15112}
15113
15116 SourceLocation LParenLoc,
15117 MultiExprArg Args,
15118 SourceLocation RParenLoc,
15119 Expr *ExecConfig,
15120 bool AllowTypoCorrection,
15121 bool CalleesAddressIsTaken) {
15122
15126
15127 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15128 ExprResult result;
15129
15130 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15131 &result))
15132 return result;
15133
15134 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15135 // functions that aren't addressible are considered unviable.
15136 if (CalleesAddressIsTaken)
15137 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15138
15140 OverloadingResult OverloadResult =
15141 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15142
15143 // [C++23][over.call.func]
15144 // if overload resolution selects a non-static member function,
15145 // the call is ill-formed;
15147 Best != CandidateSet.end()) {
15148 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15149 M && M->isImplicitObjectMemberFunction()) {
15150 OverloadResult = OR_No_Viable_Function;
15151 }
15152 }
15153
15154 // Model the case with a call to a templated function whose definition
15155 // encloses the call and whose return type contains a placeholder type as if
15156 // the UnresolvedLookupExpr was type-dependent.
15157 if (OverloadResult == OR_Success) {
15158 const FunctionDecl *FDecl = Best->Function;
15159 if (LangOpts.CUDA)
15160 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15161 if (FDecl && FDecl->isTemplateInstantiation() &&
15162 FDecl->getReturnType()->isUndeducedType()) {
15163
15164 // Creating dependent CallExpr is not okay if the enclosing context itself
15165 // is not dependent. This situation notably arises if a non-dependent
15166 // member function calls the later-defined overloaded static function.
15167 //
15168 // For example, in
15169 // class A {
15170 // void c() { callee(1); }
15171 // static auto callee(auto x) { }
15172 // };
15173 //
15174 // Here callee(1) is unresolved at the call site, but is not inside a
15175 // dependent context. There will be no further attempt to resolve this
15176 // call if it is made dependent.
15177
15178 if (const auto *TP =
15179 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15180 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15181 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15182 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15183 }
15184 }
15185 }
15186
15187 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15188 ExecConfig, &CandidateSet, &Best,
15189 OverloadResult, AllowTypoCorrection);
15190}
15191
15195 const UnresolvedSetImpl &Fns,
15196 bool PerformADL) {
15198 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15199 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15200}
15201
15204 bool HadMultipleCandidates) {
15205 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15206 // the FoundDecl as it impedes TransformMemberExpr.
15207 // We go a bit further here: if there's no difference in UnderlyingDecl,
15208 // then using FoundDecl vs Method shouldn't make a difference either.
15209 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15210 FoundDecl = Method;
15211 // Convert the expression to match the conversion function's implicit object
15212 // parameter.
15213 ExprResult Exp;
15214 if (Method->isExplicitObjectMemberFunction())
15216 else
15218 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15219 if (Exp.isInvalid())
15220 return true;
15221
15222 if (Method->getParent()->isLambda() &&
15223 Method->getConversionType()->isBlockPointerType()) {
15224 // This is a lambda conversion to block pointer; check if the argument
15225 // was a LambdaExpr.
15226 Expr *SubE = E;
15227 auto *CE = dyn_cast<CastExpr>(SubE);
15228 if (CE && CE->getCastKind() == CK_NoOp)
15229 SubE = CE->getSubExpr();
15230 SubE = SubE->IgnoreParens();
15231 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15232 SubE = BE->getSubExpr();
15233 if (isa<LambdaExpr>(SubE)) {
15234 // For the conversion to block pointer on a lambda expression, we
15235 // construct a special BlockLiteral instead; this doesn't really make
15236 // a difference in ARC, but outside of ARC the resulting block literal
15237 // follows the normal lifetime rules for block literals instead of being
15238 // autoreleased.
15242 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15244
15245 // FIXME: This note should be produced by a CodeSynthesisContext.
15246 if (BlockExp.isInvalid())
15247 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15248 return BlockExp;
15249 }
15250 }
15251 CallExpr *CE;
15252 QualType ResultType = Method->getReturnType();
15254 ResultType = ResultType.getNonLValueExprType(Context);
15255 if (Method->isExplicitObjectMemberFunction()) {
15256 ExprResult FnExpr =
15257 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15258 HadMultipleCandidates, E->getBeginLoc());
15259 if (FnExpr.isInvalid())
15260 return ExprError();
15261 Expr *ObjectParam = Exp.get();
15262 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15263 ResultType, VK, Exp.get()->getEndLoc(),
15265 CE->setUsesMemberSyntax(true);
15266 } else {
15267 MemberExpr *ME =
15268 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15270 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15271 HadMultipleCandidates, DeclarationNameInfo(),
15272 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15273
15274 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15275 Exp.get()->getEndLoc(),
15277 }
15278
15279 if (CheckFunctionCall(Method, CE,
15280 Method->getType()->castAs<FunctionProtoType>()))
15281 return ExprError();
15282
15284}
15285
15288 const UnresolvedSetImpl &Fns,
15289 ArrayRef<Expr *> Args, bool PerformADL) {
15290 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15291
15292 SourceLocation OpLoc = CandidateSet.getLocation();
15293 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15294
15295 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15296 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15297 if (PerformADL)
15298 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15299 /*ExplicitTemplateArgs*/ nullptr,
15300 CandidateSet);
15301 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15302}
15303
15306 const UnresolvedSetImpl &Fns,
15307 Expr *Input, bool PerformADL) {
15309 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15310 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15311 // TODO: provide better source location info.
15312 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15313
15314 if (checkPlaceholderForOverload(*this, Input))
15315 return ExprError();
15316
15317 Expr *Args[2] = { Input, nullptr };
15318 unsigned NumArgs = 1;
15319
15320 // For post-increment and post-decrement, add the implicit '0' as
15321 // the second argument, so that we know this is a post-increment or
15322 // post-decrement.
15323 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15324 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15325 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15326 SourceLocation());
15327 NumArgs = 2;
15328 }
15329
15330 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15331
15332 if (Input->isTypeDependent()) {
15334 // [C++26][expr.unary.op][expr.pre.incr]
15335 // The * operator yields an lvalue of type
15336 // The pre/post increment operators yied an lvalue.
15337 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15338 VK = VK_LValue;
15339
15340 if (Fns.empty())
15341 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15342 OK_Ordinary, OpLoc, false,
15344
15345 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15347 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15348 if (Fn.isInvalid())
15349 return ExprError();
15350 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15351 Context.DependentTy, VK_PRValue, OpLoc,
15353 }
15354
15355 // Build an empty overload set.
15357 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15358
15359 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15360
15361 // Perform overload resolution.
15363 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15364 case OR_Success: {
15365 // We found a built-in operator or an overloaded operator.
15366 FunctionDecl *FnDecl = Best->Function;
15367
15368 if (FnDecl) {
15369 Expr *Base = nullptr;
15370 // We matched an overloaded operator. Build a call to that
15371 // operator.
15372
15373 // Convert the arguments.
15374 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15375 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15376
15377 ExprResult InputInit;
15378 if (Method->isExplicitObjectMemberFunction())
15379 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15380 else
15382 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15383 if (InputInit.isInvalid())
15384 return ExprError();
15385 Base = Input = InputInit.get();
15386 } else {
15387 // Convert the arguments.
15388 ExprResult InputInit
15390 Context,
15391 FnDecl->getParamDecl(0)),
15393 Input);
15394 if (InputInit.isInvalid())
15395 return ExprError();
15396 Input = InputInit.get();
15397 }
15398
15399 // Build the actual expression node.
15400 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15401 Base, HadMultipleCandidates,
15402 OpLoc);
15403 if (FnExpr.isInvalid())
15404 return ExprError();
15405
15406 // Determine the result type.
15407 QualType ResultTy = FnDecl->getReturnType();
15409 ResultTy = ResultTy.getNonLValueExprType(Context);
15410
15411 Args[0] = Input;
15413 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15415 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15416
15417 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15418 return ExprError();
15419
15420 if (CheckFunctionCall(FnDecl, TheCall,
15421 FnDecl->getType()->castAs<FunctionProtoType>()))
15422 return ExprError();
15423 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15424 } else {
15425 // We matched a built-in operator. Convert the arguments, then
15426 // break out so that we will build the appropriate built-in
15427 // operator node.
15429 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15432 if (InputRes.isInvalid())
15433 return ExprError();
15434 Input = InputRes.get();
15435 break;
15436 }
15437 }
15438
15440 // This is an erroneous use of an operator which can be overloaded by
15441 // a non-member function. Check for non-member operators which were
15442 // defined too late to be candidates.
15443 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray,
15444 CandidateSet))
15445 // FIXME: Recover by calling the found function.
15446 return ExprError();
15447
15448 // No viable function; fall through to handling this as a
15449 // built-in operator, which will produce an error message for us.
15450 break;
15451
15452 case OR_Ambiguous:
15453 CandidateSet.NoteCandidates(
15454 PartialDiagnosticAt(OpLoc,
15455 PDiag(diag::err_ovl_ambiguous_oper_unary)
15457 << Input->getType() << Input->getSourceRange()),
15458 *this, OCD_AmbiguousCandidates, ArgsArray,
15459 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15460 return ExprError();
15461
15462 case OR_Deleted: {
15463 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15464 // object whose method was called. Later in NoteCandidates size of ArgsArray
15465 // is passed further and it eventually ends up compared to number of
15466 // function candidate parameters which never includes the object parameter,
15467 // so slice ArgsArray to make sure apples are compared to apples.
15468 StringLiteral *Msg = Best->Function->getDeletedMessage();
15469 CandidateSet.NoteCandidates(
15470 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15472 << (Msg != nullptr)
15473 << (Msg ? Msg->getString() : StringRef())
15474 << Input->getSourceRange()),
15475 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15476 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15477 return ExprError();
15478 }
15479 }
15480
15481 // Either we found no viable overloaded operator or we matched a
15482 // built-in operator. In either case, fall through to trying to
15483 // build a built-in operation.
15484 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15485}
15486
15489 const UnresolvedSetImpl &Fns,
15490 ArrayRef<Expr *> Args, bool PerformADL) {
15491 SourceLocation OpLoc = CandidateSet.getLocation();
15492
15493 OverloadedOperatorKind ExtraOp =
15496 : OO_None;
15497
15498 // Add the candidates from the given function set. This also adds the
15499 // rewritten candidates using these functions if necessary.
15500 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15501
15502 // As template candidates are not deduced immediately,
15503 // persist the array in the overload set.
15504 ArrayRef<Expr *> ReversedArgs;
15505 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15506 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15507 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15508
15509 // Add operator candidates that are member functions.
15510 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15511 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15512 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15514
15515 // In C++20, also add any rewritten member candidates.
15516 if (ExtraOp) {
15517 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15518 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15519 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15521 }
15522
15523 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15524 // performed for an assignment operator (nor for operator[] nor operator->,
15525 // which don't get here).
15526 if (Op != OO_Equal && PerformADL) {
15527 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15528 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15529 /*ExplicitTemplateArgs*/ nullptr,
15530 CandidateSet);
15531 if (ExtraOp) {
15532 DeclarationName ExtraOpName =
15533 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15534 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15535 /*ExplicitTemplateArgs*/ nullptr,
15536 CandidateSet);
15537 }
15538 }
15539
15540 // Add builtin operator candidates.
15541 //
15542 // FIXME: We don't add any rewritten candidates here. This is strictly
15543 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15544 // resulting in our selecting a rewritten builtin candidate. For example:
15545 //
15546 // enum class E { e };
15547 // bool operator!=(E, E) requires false;
15548 // bool k = E::e != E::e;
15549 //
15550 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15551 // it seems unreasonable to consider rewritten builtin candidates. A core
15552 // issue has been filed proposing to removed this requirement.
15553 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15554}
15555
15558 const UnresolvedSetImpl &Fns, Expr *LHS,
15559 Expr *RHS, bool PerformADL,
15560 bool AllowRewrittenCandidates,
15561 FunctionDecl *DefaultedFn) {
15562 Expr *Args[2] = { LHS, RHS };
15563 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15564
15565 if (!getLangOpts().CPlusPlus20)
15566 AllowRewrittenCandidates = false;
15567
15569
15570 // If either side is type-dependent, create an appropriate dependent
15571 // expression.
15572 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15573 if (Fns.empty()) {
15574 // If there are no functions to store, just build a dependent
15575 // BinaryOperator or CompoundAssignment.
15578 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15579 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15580 Context.DependentTy);
15582 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15584 }
15585
15586 // FIXME: save results of ADL from here?
15587 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15588 // TODO: provide better source location info in DNLoc component.
15589 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15590 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15592 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15593 if (Fn.isInvalid())
15594 return ExprError();
15595 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15596 Context.DependentTy, VK_PRValue, OpLoc,
15598 }
15599
15600 // If this is the .* operator, which is not overloadable, just
15601 // create a built-in binary operator.
15602 if (Opc == BO_PtrMemD) {
15603 auto CheckPlaceholder = [&](Expr *&Arg) {
15605 if (Res.isUsable())
15606 Arg = Res.get();
15607 return !Res.isUsable();
15608 };
15609
15610 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15611 // expression that contains placeholders (in either the LHS or RHS).
15612 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15613 return ExprError();
15614 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15615 }
15616
15617 // Always do placeholder-like conversions on the RHS.
15618 if (checkPlaceholderForOverload(*this, Args[1]))
15619 return ExprError();
15620
15621 // Do placeholder-like conversion on the LHS; note that we should
15622 // not get here with a PseudoObject LHS.
15623 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15624 if (checkPlaceholderForOverload(*this, Args[0]))
15625 return ExprError();
15626
15627 // If this is the assignment operator, we only perform overload resolution
15628 // if the left-hand side is a class or enumeration type. This is actually
15629 // a hack. The standard requires that we do overload resolution between the
15630 // various built-in candidates, but as DR507 points out, this can lead to
15631 // problems. So we do it this way, which pretty much follows what GCC does.
15632 // Note that we go the traditional code path for compound assignment forms.
15633 // In HLSL, user-defined structs/classes do not have constructors or
15634 // overloadable assignment operators, so we can take this shortcut too.
15635 const Type *LHSTy = Args[0]->getType().getTypePtr();
15636 if (Opc == BO_Assign &&
15637 (!LHSTy->isOverloadableType() ||
15638 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15640 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15641
15642 // Build the overload set.
15645 Op, OpLoc, AllowRewrittenCandidates));
15646 if (DefaultedFn)
15647 CandidateSet.exclude(DefaultedFn);
15648 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15649
15650 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15651
15652 // Perform overload resolution.
15654 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15655 case OR_Success: {
15656 // We found a built-in operator or an overloaded operator.
15657 FunctionDecl *FnDecl = Best->Function;
15658
15659 bool IsReversed = Best->isReversed();
15660 if (IsReversed)
15661 std::swap(Args[0], Args[1]);
15662
15663 if (FnDecl) {
15664
15665 if (FnDecl->isInvalidDecl())
15666 return ExprError();
15667
15668 Expr *Base = nullptr;
15669 // We matched an overloaded operator. Build a call to that
15670 // operator.
15671
15672 OverloadedOperatorKind ChosenOp =
15674
15675 // C++2a [over.match.oper]p9:
15676 // If a rewritten operator== candidate is selected by overload
15677 // resolution for an operator@, its return type shall be cv bool
15678 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15679 !FnDecl->getReturnType()->isBooleanType()) {
15680 bool IsExtension =
15682 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15683 : diag::err_ovl_rewrite_equalequal_not_bool)
15684 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15685 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15686 Diag(FnDecl->getLocation(), diag::note_declared_at);
15687 if (!IsExtension)
15688 return ExprError();
15689 }
15690
15691 if (AllowRewrittenCandidates && !IsReversed &&
15692 CandidateSet.getRewriteInfo().isReversible()) {
15693 // We could have reversed this operator, but didn't. Check if some
15694 // reversed form was a viable candidate, and if so, if it had a
15695 // better conversion for either parameter. If so, this call is
15696 // formally ambiguous, and allowing it is an extension.
15698 for (OverloadCandidate &Cand : CandidateSet) {
15699 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15700 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15701 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15703 *this, OpLoc, Cand.Conversions[ArgIdx],
15704 Best->Conversions[ArgIdx]) ==
15706 AmbiguousWith.push_back(Cand.Function);
15707 break;
15708 }
15709 }
15710 }
15711 }
15712
15713 if (!AmbiguousWith.empty()) {
15714 bool AmbiguousWithSelf =
15715 AmbiguousWith.size() == 1 &&
15716 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15717 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15719 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15720 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15721 if (AmbiguousWithSelf) {
15722 Diag(FnDecl->getLocation(),
15723 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15724 // Mark member== const or provide matching != to disallow reversed
15725 // args. Eg.
15726 // struct S { bool operator==(const S&); };
15727 // S()==S();
15728 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15729 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15730 !MD->isConst() &&
15731 !MD->hasCXXExplicitFunctionObjectParameter() &&
15732 Context.hasSameUnqualifiedType(
15733 MD->getFunctionObjectParameterType(),
15734 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15735 Context.hasSameUnqualifiedType(
15736 MD->getFunctionObjectParameterType(),
15737 Args[0]->getType()) &&
15738 Context.hasSameUnqualifiedType(
15739 MD->getFunctionObjectParameterType(),
15740 Args[1]->getType()))
15741 Diag(FnDecl->getLocation(),
15742 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15743 } else {
15744 Diag(FnDecl->getLocation(),
15745 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15746 for (auto *F : AmbiguousWith)
15747 Diag(F->getLocation(),
15748 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15749 }
15750 }
15751 }
15752
15753 // Check for nonnull = nullable.
15754 // This won't be caught in the arg's initialization: the parameter to
15755 // the assignment operator is not marked nonnull.
15756 if (Op == OO_Equal)
15758 Args[1]->getType(), OpLoc);
15759
15760 // Convert the arguments.
15761 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15762 // Best->Access is only meaningful for class members.
15763 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15764
15765 ExprResult Arg0, Arg1;
15766 unsigned ParamIdx = 0;
15767 if (Method->isExplicitObjectMemberFunction()) {
15768 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15769 ParamIdx = 1;
15770 } else {
15772 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15773 }
15776 Context, FnDecl->getParamDecl(ParamIdx)),
15777 SourceLocation(), Args[1]);
15778 if (Arg0.isInvalid() || Arg1.isInvalid())
15779 return ExprError();
15780
15781 Base = Args[0] = Arg0.getAs<Expr>();
15782 Args[1] = RHS = Arg1.getAs<Expr>();
15783 } else {
15784 // Convert the arguments.
15787 FnDecl->getParamDecl(0)),
15788 SourceLocation(), Args[0]);
15789 if (Arg0.isInvalid())
15790 return ExprError();
15791
15792 ExprResult Arg1 =
15795 FnDecl->getParamDecl(1)),
15796 SourceLocation(), Args[1]);
15797 if (Arg1.isInvalid())
15798 return ExprError();
15799 Args[0] = LHS = Arg0.getAs<Expr>();
15800 Args[1] = RHS = Arg1.getAs<Expr>();
15801 }
15802
15803 // Build the actual expression node.
15804 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15805 Best->FoundDecl, Base,
15806 HadMultipleCandidates, OpLoc);
15807 if (FnExpr.isInvalid())
15808 return ExprError();
15809
15810 // Determine the result type.
15811 QualType ResultTy = FnDecl->getReturnType();
15813 ResultTy = ResultTy.getNonLValueExprType(Context);
15814
15815 CallExpr *TheCall;
15816 ArrayRef<const Expr *> ArgsArray(Args, 2);
15817 const Expr *ImplicitThis = nullptr;
15818
15819 // We always create a CXXOperatorCallExpr, even for explicit object
15820 // members; CodeGen should take care not to emit the this pointer.
15822 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15824 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15825 IsReversed);
15826
15827 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15828 Method && Method->isImplicitObjectMemberFunction()) {
15829 // Cut off the implicit 'this'.
15830 ImplicitThis = ArgsArray[0];
15831 ArgsArray = ArgsArray.slice(1);
15832 }
15833
15834 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15835 FnDecl))
15836 return ExprError();
15837
15838 if (Op == OO_Equal) {
15839 // Check for a self move.
15840 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15841 // lifetime check.
15843 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15844 Args[1]);
15845 }
15846 if (ImplicitThis) {
15847 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15848 QualType ThisTypeFromDecl = Context.getPointerType(
15849 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15850
15851 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15852 ThisTypeFromDecl);
15853 }
15854
15855 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15856 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15858
15859 ExprResult R = MaybeBindToTemporary(TheCall);
15860 if (R.isInvalid())
15861 return ExprError();
15862
15863 R = CheckForImmediateInvocation(R, FnDecl);
15864 if (R.isInvalid())
15865 return ExprError();
15866
15867 // For a rewritten candidate, we've already reversed the arguments
15868 // if needed. Perform the rest of the rewrite now.
15869 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15870 (Op == OO_Spaceship && IsReversed)) {
15871 if (Op == OO_ExclaimEqual) {
15872 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15873 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15874 } else {
15875 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15876 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15877 Expr *ZeroLiteral =
15879
15882 Ctx.Entity = FnDecl;
15884
15886 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15887 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15888 /*AllowRewrittenCandidates=*/false);
15889
15891 }
15892 if (R.isInvalid())
15893 return ExprError();
15894 } else {
15895 assert(ChosenOp == Op && "unexpected operator name");
15896 }
15897
15898 // Make a note in the AST if we did any rewriting.
15899 if (Best->RewriteKind != CRK_None)
15900 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15901
15902 return R;
15903 } else {
15904 // We matched a built-in operator. Convert the arguments, then
15905 // break out so that we will build the appropriate built-in
15906 // operator node.
15908 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15911 if (ArgsRes0.isInvalid())
15912 return ExprError();
15913 Args[0] = ArgsRes0.get();
15914
15916 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15919 if (ArgsRes1.isInvalid())
15920 return ExprError();
15921 Args[1] = ArgsRes1.get();
15922 break;
15923 }
15924 }
15925
15926 case OR_No_Viable_Function: {
15927 // C++ [over.match.oper]p9:
15928 // If the operator is the operator , [...] and there are no
15929 // viable functions, then the operator is assumed to be the
15930 // built-in operator and interpreted according to clause 5.
15931 if (Opc == BO_Comma)
15932 break;
15933
15934 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15935 // compare result using '==' and '<'.
15936 if (DefaultedFn && Opc == BO_Cmp) {
15937 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15938 Args[1], DefaultedFn);
15939 if (E.isInvalid() || E.isUsable())
15940 return E;
15941 }
15942
15943 // For class as left operand for assignment or compound assignment
15944 // operator do not fall through to handling in built-in, but report that
15945 // no overloaded assignment operator found
15947 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15948 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15949 Args, OpLoc);
15950 DeferDiagsRAII DDR(*this,
15951 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15952 if (Args[0]->getType()->isRecordType() &&
15953 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15954 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15956 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15957 if (Args[0]->getType()->isIncompleteType()) {
15958 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15959 << Args[0]->getType()
15960 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15961 }
15962 } else {
15963 // This is an erroneous use of an operator which can be overloaded by
15964 // a non-member function. Check for non-member operators which were
15965 // defined too late to be candidates.
15966 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args,
15967 CandidateSet))
15968 // FIXME: Recover by calling the found function.
15969 return ExprError();
15970
15971 // No viable function; try to create a built-in operation, which will
15972 // produce an error. Then, show the non-viable candidates.
15973 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15974 }
15975 assert(Result.isInvalid() &&
15976 "C++ binary operator overloading is missing candidates!");
15977 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15978 return Result;
15979 }
15980
15981 case OR_Ambiguous:
15982 CandidateSet.NoteCandidates(
15983 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15985 << Args[0]->getType()
15986 << Args[1]->getType()
15987 << Args[0]->getSourceRange()
15988 << Args[1]->getSourceRange()),
15990 OpLoc);
15991 return ExprError();
15992
15993 case OR_Deleted: {
15994 if (isImplicitlyDeleted(Best->Function)) {
15995 FunctionDecl *DeletedFD = Best->Function;
15997 DeletedFD->getDefaultedFunctionKind();
15998 if (DFK.isSpecialMember()) {
15999 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
16000 << Args[0]->getType() << DFK.asSpecialMember();
16001 } else {
16002 assert(DFK.isComparison());
16003 Diag(OpLoc, diag::err_ovl_deleted_comparison)
16004 << Args[0]->getType() << DeletedFD;
16005 }
16006
16007 // The user probably meant to call this special member. Just
16008 // explain why it's deleted.
16009 NoteDeletedFunction(DeletedFD);
16010 return ExprError();
16011 }
16012
16013 StringLiteral *Msg = Best->Function->getDeletedMessage();
16014 CandidateSet.NoteCandidates(
16016 OpLoc,
16017 PDiag(diag::err_ovl_deleted_oper)
16018 << getOperatorSpelling(Best->Function->getDeclName()
16019 .getCXXOverloadedOperator())
16020 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
16021 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
16023 OpLoc);
16024 return ExprError();
16025 }
16026 }
16027
16028 // We matched a built-in operator; build it.
16029 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
16030}
16031
16033 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16034 FunctionDecl *DefaultedFn) {
16035 const ComparisonCategoryInfo *Info =
16036 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
16037 // If we're not producing a known comparison category type, we can't
16038 // synthesize a three-way comparison. Let the caller diagnose this.
16039 if (!Info)
16040 return ExprResult((Expr*)nullptr);
16041
16042 // If we ever want to perform this synthesis more generally, we will need to
16043 // apply the temporary materialization conversion to the operands.
16044 assert(LHS->isGLValue() && RHS->isGLValue() &&
16045 "cannot use prvalue expressions more than once");
16046 Expr *OrigLHS = LHS;
16047 Expr *OrigRHS = RHS;
16048
16049 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16050 // each of them multiple times below.
16051 LHS = new (Context)
16052 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16053 LHS->getObjectKind(), LHS);
16054 RHS = new (Context)
16055 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16056 RHS->getObjectKind(), RHS);
16057
16058 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16059 DefaultedFn);
16060 if (Eq.isInvalid())
16061 return ExprError();
16062
16063 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16064 true, DefaultedFn);
16065 if (Less.isInvalid())
16066 return ExprError();
16067
16069 if (Info->isPartial()) {
16070 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16071 DefaultedFn);
16072 if (Greater.isInvalid())
16073 return ExprError();
16074 }
16075
16076 // Form the list of comparisons we're going to perform.
16077 struct Comparison {
16080 } Comparisons[4] =
16086 };
16087
16088 int I = Info->isPartial() ? 3 : 2;
16089
16090 // Combine the comparisons with suitable conditional expressions.
16092 for (; I >= 0; --I) {
16093 // Build a reference to the comparison category constant.
16094 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16095 // FIXME: Missing a constant for a comparison category. Diagnose this?
16096 if (!VI)
16097 return ExprResult((Expr*)nullptr);
16098 ExprResult ThisResult =
16100 if (ThisResult.isInvalid())
16101 return ExprError();
16102
16103 // Build a conditional unless this is the final case.
16104 if (Result.get()) {
16105 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16106 ThisResult.get(), Result.get());
16107 if (Result.isInvalid())
16108 return ExprError();
16109 } else {
16110 Result = ThisResult;
16111 }
16112 }
16113
16114 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16115 // bind the OpaqueValueExprs before they're (repeatedly) used.
16116 Expr *SyntacticForm = BinaryOperator::Create(
16117 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16118 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16120 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16121 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16122}
16123
16125 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16126 MultiExprArg Args, SourceLocation LParenLoc) {
16127
16128 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16129 unsigned NumParams = Proto->getNumParams();
16130 unsigned NumArgsSlots =
16131 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16132 // Build the full argument list for the method call (the implicit object
16133 // parameter is placed at the beginning of the list).
16134 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16135 bool IsError = false;
16136 // Initialize the implicit object parameter.
16137 // Check the argument types.
16138 for (unsigned i = 0; i != NumParams; i++) {
16139 Expr *Arg;
16140 if (i < Args.size()) {
16141 Arg = Args[i];
16142 ExprResult InputInit =
16144 S.Context, Method->getParamDecl(i)),
16145 SourceLocation(), Arg);
16146 IsError |= InputInit.isInvalid();
16147 Arg = InputInit.getAs<Expr>();
16148 } else {
16149 ExprResult DefArg =
16150 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16151 if (DefArg.isInvalid()) {
16152 IsError = true;
16153 break;
16154 }
16155 Arg = DefArg.getAs<Expr>();
16156 }
16157
16158 MethodArgs.push_back(Arg);
16159 }
16160 return IsError;
16161}
16162
16164 SourceLocation RLoc,
16165 Expr *Base,
16166 MultiExprArg ArgExpr) {
16168 Args.push_back(Base);
16169 for (auto *e : ArgExpr) {
16170 Args.push_back(e);
16171 }
16172 DeclarationName OpName =
16173 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16174
16175 SourceRange Range = ArgExpr.empty()
16176 ? SourceRange{}
16177 : SourceRange(ArgExpr.front()->getBeginLoc(),
16178 ArgExpr.back()->getEndLoc());
16179
16180 // If either side is type-dependent, create an appropriate dependent
16181 // expression.
16183
16184 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16185 // CHECKME: no 'operator' keyword?
16186 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16187 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16189 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16190 if (Fn.isInvalid())
16191 return ExprError();
16192 // Can't add any actual overloads yet
16193
16194 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16195 Context.DependentTy, VK_PRValue, RLoc,
16197 }
16198
16199 // Handle placeholders
16200 UnbridgedCastsSet UnbridgedCasts;
16201 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16202 return ExprError();
16203 }
16204 // Build an empty overload set.
16206
16207 // Subscript can only be overloaded as a member function.
16208
16209 // Add operator candidates that are member functions.
16210 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16211
16212 // Add builtin operator candidates.
16213 if (Args.size() == 2)
16214 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16215
16216 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16217
16218 // Perform overload resolution.
16220 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16221 case OR_Success: {
16222 // We found a built-in operator or an overloaded operator.
16223 FunctionDecl *FnDecl = Best->Function;
16224
16225 if (FnDecl) {
16226 // We matched an overloaded operator. Build a call to that
16227 // operator.
16228
16229 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16230
16231 // Convert the arguments.
16233 SmallVector<Expr *, 2> MethodArgs;
16234
16235 // Initialize the object parameter.
16236 if (Method->isExplicitObjectMemberFunction()) {
16237 ExprResult Res =
16239 if (Res.isInvalid())
16240 return ExprError();
16241 Args[0] = Res.get();
16242 ArgExpr = Args;
16243 } else {
16245 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16246 if (Arg0.isInvalid())
16247 return ExprError();
16248
16249 MethodArgs.push_back(Arg0.get());
16250 }
16251
16253 *this, MethodArgs, Method, ArgExpr, LLoc);
16254 if (IsError)
16255 return ExprError();
16256
16257 // Build the actual expression node.
16258 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16259 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16260 ExprResult FnExpr =
16261 CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, Base,
16262 HadMultipleCandidates, OpLocInfo);
16263 if (FnExpr.isInvalid())
16264 return ExprError();
16265
16266 // Determine the result type
16267 QualType ResultTy = FnDecl->getReturnType();
16269 ResultTy = ResultTy.getNonLValueExprType(Context);
16270
16272 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16274
16275 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16276 return ExprError();
16277
16278 if (CheckFunctionCall(Method, TheCall,
16279 Method->getType()->castAs<FunctionProtoType>()))
16280 return ExprError();
16281
16283 FnDecl);
16284 } else {
16285 // We matched a built-in operator. Convert the arguments, then
16286 // break out so that we will build the appropriate built-in
16287 // operator node.
16289 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16292 if (ArgsRes0.isInvalid())
16293 return ExprError();
16294 Args[0] = ArgsRes0.get();
16295
16297 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16300 if (ArgsRes1.isInvalid())
16301 return ExprError();
16302 Args[1] = ArgsRes1.get();
16303
16304 break;
16305 }
16306 }
16307
16308 case OR_No_Viable_Function: {
16310 CandidateSet.empty()
16311 ? (PDiag(diag::err_ovl_no_oper)
16312 << Args[0]->getType() << /*subscript*/ 0
16313 << Args[0]->getSourceRange() << Range)
16314 : (PDiag(diag::err_ovl_no_viable_subscript)
16315 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16316 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16317 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16318 return ExprError();
16319 }
16320
16321 case OR_Ambiguous:
16322 if (Args.size() == 2) {
16323 CandidateSet.NoteCandidates(
16325 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16326 << "[]" << Args[0]->getType() << Args[1]->getType()
16327 << Args[0]->getSourceRange() << Range),
16328 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16329 } else {
16330 CandidateSet.NoteCandidates(
16332 PDiag(diag::err_ovl_ambiguous_subscript_call)
16333 << Args[0]->getType()
16334 << Args[0]->getSourceRange() << Range),
16335 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16336 }
16337 return ExprError();
16338
16339 case OR_Deleted: {
16340 StringLiteral *Msg = Best->Function->getDeletedMessage();
16341 CandidateSet.NoteCandidates(
16343 PDiag(diag::err_ovl_deleted_oper)
16344 << "[]" << (Msg != nullptr)
16345 << (Msg ? Msg->getString() : StringRef())
16346 << Args[0]->getSourceRange() << Range),
16347 *this, OCD_AllCandidates, Args, "[]", LLoc);
16348 return ExprError();
16349 }
16350 }
16351
16352 // We matched a built-in operator; build it.
16353 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16354}
16355
16357 SourceLocation LParenLoc,
16358 MultiExprArg Args,
16359 SourceLocation RParenLoc,
16360 Expr *ExecConfig, bool IsExecConfig,
16361 bool AllowRecovery) {
16362 assert(MemExprE->getType() == Context.BoundMemberTy ||
16363 MemExprE->getType() == Context.OverloadTy);
16364
16365 // Dig out the member expression. This holds both the object
16366 // argument and the member function we're referring to.
16367 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16368
16369 // Determine whether this is a call to a pointer-to-member function.
16370 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16371 assert(op->getType() == Context.BoundMemberTy);
16372 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16373
16374 QualType fnType =
16375 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16376
16377 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16378 QualType resultType = proto->getCallResultType(Context);
16380
16381 // Check that the object type isn't more qualified than the
16382 // member function we're calling.
16383 Qualifiers funcQuals = proto->getMethodQuals();
16384
16385 QualType objectType = op->getLHS()->getType();
16386 if (op->getOpcode() == BO_PtrMemI)
16387 objectType = objectType->castAs<PointerType>()->getPointeeType();
16388 Qualifiers objectQuals = objectType.getQualifiers();
16389
16390 Qualifiers difference = objectQuals - funcQuals;
16391 difference.removeObjCGCAttr();
16392 difference.removeAddressSpace();
16393 if (difference) {
16394 std::string qualsString = difference.getAsString();
16395 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16396 << fnType.getUnqualifiedType()
16397 << qualsString
16398 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16399 }
16400
16402 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16404
16405 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16406 call, nullptr))
16407 return ExprError();
16408
16409 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16410 return ExprError();
16411
16412 if (CheckOtherCall(call, proto))
16413 return ExprError();
16414
16415 return MaybeBindToTemporary(call);
16416 }
16417
16418 // We only try to build a recovery expr at this level if we can preserve
16419 // the return type, otherwise we return ExprError() and let the caller
16420 // recover.
16421 auto BuildRecoveryExpr = [&](QualType Type) {
16422 if (!AllowRecovery)
16423 return ExprError();
16424 std::vector<Expr *> SubExprs = {MemExprE};
16425 llvm::append_range(SubExprs, Args);
16426 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16427 Type);
16428 };
16429 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16430 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16431 RParenLoc, CurFPFeatureOverrides());
16432
16433 UnbridgedCastsSet UnbridgedCasts;
16434 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16435 return ExprError();
16436
16437 MemberExpr *MemExpr;
16438 CXXMethodDecl *Method = nullptr;
16439 bool HadMultipleCandidates = false;
16440 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16441 NestedNameSpecifier Qualifier = std::nullopt;
16442 if (isa<MemberExpr>(NakedMemExpr)) {
16443 MemExpr = cast<MemberExpr>(NakedMemExpr);
16445 FoundDecl = MemExpr->getFoundDecl();
16446 Qualifier = MemExpr->getQualifier();
16447 UnbridgedCasts.restore();
16448 } else {
16449 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16450 Qualifier = UnresExpr->getQualifier();
16451
16452 QualType ObjectType = UnresExpr->getBaseType();
16453 Expr::Classification ObjectClassification
16455 : UnresExpr->getBase()->Classify(Context);
16456
16457 // Add overload candidates
16458 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16460
16461 // FIXME: avoid copy.
16462 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16463 if (UnresExpr->hasExplicitTemplateArgs()) {
16464 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16465 TemplateArgs = &TemplateArgsBuffer;
16466 }
16467
16469 E = UnresExpr->decls_end(); I != E; ++I) {
16470
16471 QualType ExplicitObjectType = ObjectType;
16472
16473 NamedDecl *Func = *I;
16474 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16476 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16477
16478 bool HasExplicitParameter = false;
16479 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16480 M && M->hasCXXExplicitFunctionObjectParameter())
16481 HasExplicitParameter = true;
16482 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16483 M &&
16484 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16485 HasExplicitParameter = true;
16486
16487 if (HasExplicitParameter)
16488 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16489
16490 // Microsoft supports direct constructor calls.
16491 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16493 CandidateSet,
16494 /*SuppressUserConversions*/ false);
16495 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16496 // If explicit template arguments were provided, we can't call a
16497 // non-template member function.
16498 if (TemplateArgs)
16499 continue;
16500
16501 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16502 ObjectClassification, Args, CandidateSet,
16503 /*SuppressUserConversions=*/false);
16504 } else {
16506 I.getPair(), ActingDC, TemplateArgs,
16507 ExplicitObjectType, ObjectClassification,
16508 Args, CandidateSet,
16509 /*SuppressUserConversions=*/false);
16510 }
16511 }
16512
16513 HadMultipleCandidates = (CandidateSet.size() > 1);
16514
16515 DeclarationName DeclName = UnresExpr->getMemberName();
16516
16517 UnbridgedCasts.restore();
16518
16520 bool Succeeded = false;
16521 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16522 Best)) {
16523 case OR_Success:
16524 Method = cast<CXXMethodDecl>(Best->Function);
16525 FoundDecl = Best->FoundDecl;
16526 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16527 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16528 break;
16529 // If FoundDecl is different from Method (such as if one is a template
16530 // and the other a specialization), make sure DiagnoseUseOfDecl is
16531 // called on both.
16532 // FIXME: This would be more comprehensively addressed by modifying
16533 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16534 // being used.
16535 if (Method != FoundDecl.getDecl() &&
16537 break;
16538 Succeeded = true;
16539 break;
16540
16542 CandidateSet.NoteCandidates(
16544 UnresExpr->getMemberLoc(),
16545 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16546 << DeclName << MemExprE->getSourceRange()),
16547 *this, OCD_AllCandidates, Args);
16548 break;
16549 case OR_Ambiguous:
16550 CandidateSet.NoteCandidates(
16551 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16552 PDiag(diag::err_ovl_ambiguous_member_call)
16553 << DeclName << MemExprE->getSourceRange()),
16554 *this, OCD_AmbiguousCandidates, Args);
16555 break;
16556 case OR_Deleted:
16558 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16559 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16560 break;
16561 }
16562 // Overload resolution fails, try to recover.
16563 if (!Succeeded)
16564 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16565
16566 ExprResult Res =
16567 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16568 if (Res.isInvalid())
16569 return ExprError();
16570 MemExprE = Res.get();
16571
16572 // If overload resolution picked a static member
16573 // build a non-member call based on that function.
16574 if (Method->isStatic()) {
16575 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16576 ExecConfig, IsExecConfig);
16577 }
16578
16579 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16580 }
16581
16582 QualType ResultType = Method->getReturnType();
16584 ResultType = ResultType.getNonLValueExprType(Context);
16585
16586 assert(Method && "Member call to something that isn't a method?");
16587 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16588
16589 CallExpr *TheCall = nullptr;
16591 if (Method->isExplicitObjectMemberFunction()) {
16592 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16593 NewArgs))
16594 return ExprError();
16595
16596 // FIXME: avoid copy.
16597 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16598 if (MemExpr->hasExplicitTemplateArgs()) {
16599 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16600 TemplateArgs = &TemplateArgsBuffer;
16601 }
16602
16603 // Build the actual expression node.
16605 *this, MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(),
16606 Method, FoundDecl, MemExpr, HadMultipleCandidates,
16607 MemExpr->getMemberNameInfo(), TemplateArgs);
16608 if (FnExpr.isInvalid())
16609 return ExprError();
16610
16611 TheCall =
16612 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16613 CurFPFeatureOverrides(), Proto->getNumParams());
16614 TheCall->setUsesMemberSyntax(true);
16615 } else {
16616 // Convert the object argument (for a non-static member function call).
16618 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16619 if (ObjectArg.isInvalid())
16620 return ExprError();
16621 MemExpr->setBase(ObjectArg.get());
16622 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16623 RParenLoc, CurFPFeatureOverrides(),
16624 Proto->getNumParams());
16625 }
16626
16627 // Check for a valid return type.
16628 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16629 TheCall, Method))
16630 return BuildRecoveryExpr(ResultType);
16631
16632 // Convert the rest of the arguments
16633 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16634 RParenLoc))
16635 return BuildRecoveryExpr(ResultType);
16636
16637 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16638
16639 if (CheckFunctionCall(Method, TheCall, Proto))
16640 return ExprError();
16641
16642 // In the case the method to call was not selected by the overloading
16643 // resolution process, we still need to handle the enable_if attribute. Do
16644 // that here, so it will not hide previous -- and more relevant -- errors.
16645 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16646 if (const EnableIfAttr *Attr =
16647 CheckEnableIf(Method, LParenLoc, Args, true)) {
16648 Diag(MemE->getMemberLoc(),
16649 diag::err_ovl_no_viable_member_function_in_call)
16650 << Method << Method->getSourceRange();
16651 Diag(Method->getLocation(),
16652 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16653 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16654 return ExprError();
16655 }
16656 }
16657
16659 TheCall->getDirectCallee()->isPureVirtual()) {
16660 const FunctionDecl *MD = TheCall->getDirectCallee();
16661
16662 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16664 Diag(MemExpr->getBeginLoc(),
16665 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16667 << MD->getParent();
16668
16669 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16670 if (getLangOpts().AppleKext)
16671 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16672 << MD->getParent() << MD->getDeclName();
16673 }
16674 }
16675
16676 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16677 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16678 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16679 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16680 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16681 MemExpr->getMemberLoc());
16682 }
16683
16685 TheCall->getDirectCallee());
16686}
16687
16690 SourceLocation LParenLoc,
16691 MultiExprArg Args,
16692 SourceLocation RParenLoc) {
16693 if (checkPlaceholderForOverload(*this, Obj))
16694 return ExprError();
16695 ExprResult Object = Obj;
16696
16697 UnbridgedCastsSet UnbridgedCasts;
16698 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16699 return ExprError();
16700
16701 assert(Object.get()->getType()->isRecordType() &&
16702 "Requires object type argument");
16703
16704 // C++ [over.call.object]p1:
16705 // If the primary-expression E in the function call syntax
16706 // evaluates to a class object of type "cv T", then the set of
16707 // candidate functions includes at least the function call
16708 // operators of T. The function call operators of T are obtained by
16709 // ordinary lookup of the name operator() in the context of
16710 // (E).operator().
16711 OverloadCandidateSet CandidateSet(LParenLoc,
16713 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16714
16715 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16716 diag::err_incomplete_object_call, Object.get()))
16717 return true;
16718
16719 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16720 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16722 R.suppressAccessDiagnostics();
16723
16724 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16725 Oper != OperEnd; ++Oper) {
16726 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16727 Object.get()->Classify(Context), Args, CandidateSet,
16728 /*SuppressUserConversion=*/false);
16729 }
16730
16731 // When calling a lambda, both the call operator, and
16732 // the conversion operator to function pointer
16733 // are considered. But when constraint checking
16734 // on the call operator fails, it will also fail on the
16735 // conversion operator as the constraints are always the same.
16736 // As the user probably does not intend to perform a surrogate call,
16737 // we filter them out to produce better error diagnostics, ie to avoid
16738 // showing 2 failed overloads instead of one.
16739 bool IgnoreSurrogateFunctions = false;
16740 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16741 const OverloadCandidate &Candidate = *CandidateSet.begin();
16742 if (!Candidate.Viable &&
16744 IgnoreSurrogateFunctions = true;
16745 }
16746
16747 // C++ [over.call.object]p2:
16748 // In addition, for each (non-explicit in C++0x) conversion function
16749 // declared in T of the form
16750 //
16751 // operator conversion-type-id () cv-qualifier;
16752 //
16753 // where cv-qualifier is the same cv-qualification as, or a
16754 // greater cv-qualification than, cv, and where conversion-type-id
16755 // denotes the type "pointer to function of (P1,...,Pn) returning
16756 // R", or the type "reference to pointer to function of
16757 // (P1,...,Pn) returning R", or the type "reference to function
16758 // of (P1,...,Pn) returning R", a surrogate call function [...]
16759 // is also considered as a candidate function. Similarly,
16760 // surrogate call functions are added to the set of candidate
16761 // functions for each conversion function declared in an
16762 // accessible base class provided the function is not hidden
16763 // within T by another intervening declaration.
16764 const auto &Conversions = Record->getVisibleConversionFunctions();
16765 for (auto I = Conversions.begin(), E = Conversions.end();
16766 !IgnoreSurrogateFunctions && I != E; ++I) {
16767 NamedDecl *D = *I;
16768 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16769 if (isa<UsingShadowDecl>(D))
16770 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16771
16772 // Skip over templated conversion functions; they aren't
16773 // surrogates.
16775 continue;
16776
16778 if (!Conv->isExplicit()) {
16779 // Strip the reference type (if any) and then the pointer type (if
16780 // any) to get down to what might be a function type.
16781 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16782 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16783 ConvType = ConvPtrType->getPointeeType();
16784
16785 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16786 {
16787 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16788 Object.get(), Args, CandidateSet);
16789 }
16790 }
16791 }
16792
16793 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16794
16795 // Perform overload resolution.
16797 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16798 Best)) {
16799 case OR_Success:
16800 // Overload resolution succeeded; we'll build the appropriate call
16801 // below.
16802 break;
16803
16804 case OR_No_Viable_Function: {
16806 CandidateSet.empty()
16807 ? (PDiag(diag::err_ovl_no_oper)
16808 << Object.get()->getType() << /*call*/ 1
16809 << Object.get()->getSourceRange())
16810 : (PDiag(diag::err_ovl_no_viable_object_call)
16811 << Object.get()->getType() << Object.get()->getSourceRange());
16812 CandidateSet.NoteCandidates(
16813 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16814 OCD_AllCandidates, Args);
16815 break;
16816 }
16817 case OR_Ambiguous:
16818 if (!R.isAmbiguous())
16819 CandidateSet.NoteCandidates(
16820 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16821 PDiag(diag::err_ovl_ambiguous_object_call)
16822 << Object.get()->getType()
16823 << Object.get()->getSourceRange()),
16824 *this, OCD_AmbiguousCandidates, Args);
16825 break;
16826
16827 case OR_Deleted: {
16828 // FIXME: Is this diagnostic here really necessary? It seems that
16829 // 1. we don't have any tests for this diagnostic, and
16830 // 2. we already issue err_deleted_function_use for this later on anyway.
16831 StringLiteral *Msg = Best->Function->getDeletedMessage();
16832 CandidateSet.NoteCandidates(
16833 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16834 PDiag(diag::err_ovl_deleted_object_call)
16835 << Object.get()->getType() << (Msg != nullptr)
16836 << (Msg ? Msg->getString() : StringRef())
16837 << Object.get()->getSourceRange()),
16838 *this, OCD_AllCandidates, Args);
16839 break;
16840 }
16841 }
16842
16843 if (Best == CandidateSet.end())
16844 return true;
16845
16846 UnbridgedCasts.restore();
16847
16848 if (Best->Function == nullptr) {
16849 // Since there is no function declaration, this is one of the
16850 // surrogate candidates. Dig out the conversion function.
16851 CXXConversionDecl *Conv
16853 Best->Conversions[0].UserDefined.ConversionFunction);
16854
16855 // FoundDecl may be a UsingShadowDecl naming the conversion function.
16856 assert(Conv == Best->FoundDecl.getDecl()->getUnderlyingDecl() &&
16857 "Found Decl & conversion-to-functionptr should be same, right?!");
16858 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16859 Best->FoundDecl);
16860 if (DiagnoseUseOfDecl(Conv, LParenLoc))
16861 return ExprError();
16862 // We selected one of the surrogate functions that converts the
16863 // object parameter to a function pointer. Perform the conversion
16864 // on the object argument, then let BuildCallExpr finish the job.
16865
16866 // Create an implicit member expr to refer to the conversion operator.
16867 // and then call it.
16868 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16869 Conv, HadMultipleCandidates);
16870 if (Call.isInvalid())
16871 return ExprError();
16872 // Record usage of conversion in an implicit cast.
16874 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16875 nullptr, VK_PRValue, CurFPFeatureOverrides());
16876
16877 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16878 }
16879
16880 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16881
16882 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16883 // that calls this method, using Object for the implicit object
16884 // parameter and passing along the remaining arguments.
16885 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16886
16887 // An error diagnostic has already been printed when parsing the declaration.
16888 if (Method->isInvalidDecl())
16889 return ExprError();
16890
16891 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16892 unsigned NumParams = Proto->getNumParams();
16893
16894 DeclarationNameInfo OpLocInfo(
16895 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16896 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16897 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, Obj,
16898 HadMultipleCandidates, OpLocInfo);
16899 if (NewFn.isInvalid())
16900 return true;
16901
16902 SmallVector<Expr *, 8> MethodArgs;
16903 MethodArgs.reserve(NumParams + 1);
16904
16905 bool IsError = false;
16906
16907 // Initialize the object parameter.
16909 if (Method->isExplicitObjectMemberFunction()) {
16910 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16911 } else {
16913 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16914 if (ObjRes.isInvalid())
16915 IsError = true;
16916 else
16917 Object = ObjRes;
16918 MethodArgs.push_back(Object.get());
16919 }
16920
16922 *this, MethodArgs, Method, Args, LParenLoc);
16923
16924 // If this is a variadic call, handle args passed through "...".
16925 if (Proto->isVariadic()) {
16926 // Promote the arguments (C99 6.5.2.2p7).
16927 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16929 Args[i], VariadicCallType::Method, nullptr);
16930 IsError |= Arg.isInvalid();
16931 MethodArgs.push_back(Arg.get());
16932 }
16933 }
16934
16935 if (IsError)
16936 return true;
16937
16938 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16939
16940 // Once we've built TheCall, all of the expressions are properly owned.
16941 QualType ResultTy = Method->getReturnType();
16943 ResultTy = ResultTy.getNonLValueExprType(Context);
16944
16946 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16948
16949 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16950 return true;
16951
16952 if (CheckFunctionCall(Method, TheCall, Proto))
16953 return true;
16954
16956}
16957
16959 SourceLocation OpLoc,
16960 bool *NoArrowOperatorFound) {
16961 assert(Base->getType()->isRecordType() &&
16962 "left-hand side must have class type");
16963
16965 return ExprError();
16966
16967 SourceLocation Loc = Base->getExprLoc();
16968
16969 // C++ [over.ref]p1:
16970 //
16971 // [...] An expression x->m is interpreted as (x.operator->())->m
16972 // for a class object x of type T if T::operator->() exists and if
16973 // the operator is selected as the best match function by the
16974 // overload resolution mechanism (13.3).
16975 DeclarationName OpName =
16976 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16978
16979 if (RequireCompleteType(Loc, Base->getType(),
16980 diag::err_typecheck_incomplete_tag, Base))
16981 return ExprError();
16982
16983 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16984 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16985 R.suppressAccessDiagnostics();
16986
16987 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16988 Oper != OperEnd; ++Oper) {
16989 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16990 {}, CandidateSet,
16991 /*SuppressUserConversion=*/false);
16992 }
16993
16994 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16995
16996 // Perform overload resolution.
16998 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16999 case OR_Success:
17000 // Overload resolution succeeded; we'll build the call below.
17001 break;
17002
17003 case OR_No_Viable_Function: {
17004 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
17005 if (CandidateSet.empty()) {
17006 QualType BaseType = Base->getType();
17007 if (NoArrowOperatorFound) {
17008 // Report this specific error to the caller instead of emitting a
17009 // diagnostic, as requested.
17010 *NoArrowOperatorFound = true;
17011 return ExprError();
17012 }
17013 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
17014 << BaseType << Base->getSourceRange();
17015 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
17016 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
17017 << FixItHint::CreateReplacement(OpLoc, ".");
17018 }
17019 } else
17020 Diag(OpLoc, diag::err_ovl_no_viable_oper)
17021 << "operator->" << Base->getSourceRange();
17022 CandidateSet.NoteCandidates(*this, Base, Cands);
17023 return ExprError();
17024 }
17025 case OR_Ambiguous:
17026 if (!R.isAmbiguous())
17027 CandidateSet.NoteCandidates(
17028 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
17029 << "->" << Base->getType()
17030 << Base->getSourceRange()),
17032 return ExprError();
17033
17034 case OR_Deleted: {
17035 StringLiteral *Msg = Best->Function->getDeletedMessage();
17036 CandidateSet.NoteCandidates(
17037 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
17038 << "->" << (Msg != nullptr)
17039 << (Msg ? Msg->getString() : StringRef())
17040 << Base->getSourceRange()),
17041 *this, OCD_AllCandidates, Base);
17042 return ExprError();
17043 }
17044 }
17045
17046 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
17047
17048 // Convert the object parameter.
17049 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
17050
17051 if (Method->isExplicitObjectMemberFunction()) {
17053 if (R.isInvalid())
17054 return ExprError();
17055 Base = R.get();
17056 } else {
17058 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17059 if (BaseResult.isInvalid())
17060 return ExprError();
17061 Base = BaseResult.get();
17062 }
17063
17064 // Build the operator call.
17065 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17066 Base, HadMultipleCandidates, OpLoc);
17067 if (FnExpr.isInvalid())
17068 return ExprError();
17069
17070 QualType ResultTy = Method->getReturnType();
17072 ResultTy = ResultTy.getNonLValueExprType(Context);
17073
17074 CallExpr *TheCall =
17075 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17076 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17077
17078 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17079 return ExprError();
17080
17081 if (CheckFunctionCall(Method, TheCall,
17082 Method->getType()->castAs<FunctionProtoType>()))
17083 return ExprError();
17084
17086}
17087
17089 DeclarationNameInfo &SuffixInfo,
17090 ArrayRef<Expr*> Args,
17091 SourceLocation LitEndLoc,
17092 TemplateArgumentListInfo *TemplateArgs) {
17093 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17094
17095 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17097 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17098 TemplateArgs);
17099
17100 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17101
17102 // Perform overload resolution. This will usually be trivial, but might need
17103 // to perform substitutions for a literal operator template.
17105 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17106 case OR_Success:
17107 case OR_Deleted:
17108 break;
17109
17111 CandidateSet.NoteCandidates(
17112 PartialDiagnosticAt(UDSuffixLoc,
17113 PDiag(diag::err_ovl_no_viable_function_in_call)
17114 << R.getLookupName()),
17115 *this, OCD_AllCandidates, Args);
17116 return ExprError();
17117
17118 case OR_Ambiguous:
17119 CandidateSet.NoteCandidates(
17120 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17121 << R.getLookupName()),
17122 *this, OCD_AmbiguousCandidates, Args);
17123 return ExprError();
17124 }
17125
17126 FunctionDecl *FD = Best->Function;
17127 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, nullptr,
17128 HadMultipleCandidates, SuffixInfo);
17129 if (Fn.isInvalid())
17130 return true;
17131
17132 // Check the argument types. This should almost always be a no-op, except
17133 // that array-to-pointer decay is applied to string literals.
17134 Expr *ConvArgs[2];
17135 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17138 SourceLocation(), Args[ArgIdx]);
17139 if (InputInit.isInvalid())
17140 return true;
17141 ConvArgs[ArgIdx] = InputInit.get();
17142 }
17143
17144 QualType ResultTy = FD->getReturnType();
17146 ResultTy = ResultTy.getNonLValueExprType(Context);
17147
17149 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17150 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17151
17152 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17153 return ExprError();
17154
17155 if (CheckFunctionCall(FD, UDL, nullptr))
17156 return ExprError();
17157
17159}
17160
17163 SourceLocation RangeLoc,
17164 const DeclarationNameInfo &NameInfo,
17165 LookupResult &MemberLookup,
17166 OverloadCandidateSet *CandidateSet,
17167 Expr *Range, ExprResult *CallExpr) {
17168 Scope *S = nullptr;
17169
17171 if (!MemberLookup.empty()) {
17172 ExprResult MemberRef =
17173 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17174 /*IsPtr=*/false, CXXScopeSpec(),
17175 /*TemplateKWLoc=*/SourceLocation(),
17176 /*FirstQualifierInScope=*/nullptr,
17177 MemberLookup,
17178 /*TemplateArgs=*/nullptr, S);
17179 if (MemberRef.isInvalid()) {
17180 *CallExpr = ExprError();
17181 return FRS_DiagnosticIssued;
17182 }
17183 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17184 if (CallExpr->isInvalid()) {
17185 *CallExpr = ExprError();
17186 return FRS_DiagnosticIssued;
17187 }
17188 } else {
17189 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17191 NameInfo, UnresolvedSet<0>());
17192 if (FnR.isInvalid())
17193 return FRS_DiagnosticIssued;
17195
17196 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17197 CandidateSet, CallExpr);
17198 if (CandidateSet->empty() || CandidateSetError) {
17199 *CallExpr = ExprError();
17200 return FRS_NoViableFunction;
17201 }
17203 OverloadingResult OverloadResult =
17204 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17205
17206 if (OverloadResult == OR_No_Viable_Function) {
17207 *CallExpr = ExprError();
17208 return FRS_NoViableFunction;
17209 }
17210 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17211 Loc, nullptr, CandidateSet, &Best,
17212 OverloadResult,
17213 /*AllowTypoCorrection=*/false);
17214 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17215 *CallExpr = ExprError();
17216 return FRS_DiagnosticIssued;
17217 }
17218 }
17219 return FRS_Success;
17220}
17221
17223 FunctionDecl *Fn) {
17224 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17225 ExprResult SubExpr =
17226 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17227 if (SubExpr.isInvalid())
17228 return ExprError();
17229 if (SubExpr.get() == PE->getSubExpr())
17230 return PE;
17231
17232 return new (Context)
17233 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17234 }
17235
17236 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17237 ExprResult SubExpr =
17238 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17239 if (SubExpr.isInvalid())
17240 return ExprError();
17241 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17242 SubExpr.get()->getType()) &&
17243 "Implicit cast type cannot be determined from overload");
17244 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17245 if (SubExpr.get() == ICE->getSubExpr())
17246 return ICE;
17247
17248 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17249 SubExpr.get(), nullptr, ICE->getValueKind(),
17251 }
17252
17253 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17254 if (!GSE->isResultDependent()) {
17255 ExprResult SubExpr =
17256 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17257 if (SubExpr.isInvalid())
17258 return ExprError();
17259 if (SubExpr.get() == GSE->getResultExpr())
17260 return GSE;
17261
17262 // Replace the resulting type information before rebuilding the generic
17263 // selection expression.
17264 ArrayRef<Expr *> A = GSE->getAssocExprs();
17265 SmallVector<Expr *, 4> AssocExprs(A);
17266 unsigned ResultIdx = GSE->getResultIndex();
17267 AssocExprs[ResultIdx] = SubExpr.get();
17268
17269 if (GSE->isExprPredicate())
17271 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17272 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17273 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17274 ResultIdx);
17276 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17277 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17278 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17279 ResultIdx);
17280 }
17281 // Rather than fall through to the unreachable, return the original generic
17282 // selection expression.
17283 return GSE;
17284 }
17285
17286 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17287 assert(UnOp->getOpcode() == UO_AddrOf &&
17288 "Can only take the address of an overloaded function");
17289 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17290 if (!Method->isImplicitObjectMemberFunction()) {
17291 // Do nothing: the address of static and
17292 // explicit object member functions is a (non-member) function pointer.
17293 } else {
17294 // Fix the subexpression, which really has to be an
17295 // UnresolvedLookupExpr holding an overloaded member function
17296 // or template.
17297 ExprResult SubExpr =
17298 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17299 if (SubExpr.isInvalid())
17300 return ExprError();
17301 if (SubExpr.get() == UnOp->getSubExpr())
17302 return UnOp;
17303
17304 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17305 SubExpr.get(), Method))
17306 return ExprError();
17307
17308 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17309 "fixed to something other than a decl ref");
17310 NestedNameSpecifier Qualifier =
17311 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17312 assert(Qualifier &&
17313 "fixed to a member ref with no nested name qualifier");
17314
17315 // We have taken the address of a pointer to member
17316 // function. Perform the computation here so that we get the
17317 // appropriate pointer to member type.
17318 QualType MemPtrType = Context.getMemberPointerType(
17319 Fn->getType(), Qualifier,
17320 cast<CXXRecordDecl>(Method->getDeclContext()));
17321 // Under the MS ABI, lock down the inheritance model now.
17322 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17323 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17324
17325 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17326 MemPtrType, VK_PRValue, OK_Ordinary,
17327 UnOp->getOperatorLoc(), false,
17329 }
17330 }
17331 ExprResult SubExpr =
17332 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17333 if (SubExpr.isInvalid())
17334 return ExprError();
17335 if (SubExpr.get() == UnOp->getSubExpr())
17336 return UnOp;
17337
17338 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17339 SubExpr.get());
17340 }
17341
17342 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17343 if (Found.getAccess() == AS_none) {
17345 }
17346 // FIXME: avoid copy.
17347 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17348 if (ULE->hasExplicitTemplateArgs()) {
17349 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17350 TemplateArgs = &TemplateArgsBuffer;
17351 }
17352
17353 QualType Type = Fn->getType();
17354 ExprValueKind ValueKind =
17355 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17356 ? VK_LValue
17357 : VK_PRValue;
17358
17359 // FIXME: Duplicated from BuildDeclarationNameExpr.
17360 if (unsigned BID = Fn->getBuiltinID()) {
17361 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17362 Type = Context.BuiltinFnTy;
17363 ValueKind = VK_PRValue;
17364 }
17365 }
17366
17368 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17369 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17370 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17371 return DRE;
17372 }
17373
17374 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17375 // FIXME: avoid copy.
17376 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17377 if (MemExpr->hasExplicitTemplateArgs()) {
17378 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17379 TemplateArgs = &TemplateArgsBuffer;
17380 }
17381
17382 Expr *Base;
17383
17384 // If we're filling in a static method where we used to have an
17385 // implicit member access, rewrite to a simple decl ref.
17386 if (MemExpr->isImplicitAccess()) {
17387 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17389 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17390 MemExpr->getQualifierLoc(), Found.getDecl(),
17391 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17392 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17393 return DRE;
17394 } else {
17395 SourceLocation Loc = MemExpr->getMemberLoc();
17396 if (MemExpr->getQualifier())
17397 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17398 Base =
17399 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17400 }
17401 } else
17402 Base = MemExpr->getBase();
17403
17404 ExprValueKind valueKind;
17405 QualType type;
17406 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17407 valueKind = VK_LValue;
17408 type = Fn->getType();
17409 } else {
17410 valueKind = VK_PRValue;
17411 type = Context.BoundMemberTy;
17412 }
17413
17414 return BuildMemberExpr(
17415 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17416 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17417 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17418 type, valueKind, OK_Ordinary, TemplateArgs);
17419 }
17420
17421 llvm_unreachable("Invalid reference to overloaded function");
17422}
17423
17429
17430bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17432 if (!PartialOverloading || !Function)
17433 return true;
17434 if (Function->isVariadic())
17435 return false;
17436 if (const auto *Proto =
17437 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17438 if (Proto->isTemplateVariadic())
17439 return false;
17440 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17441 if (const auto *Proto =
17442 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17443 if (Proto->isTemplateVariadic())
17444 return false;
17445 return true;
17446}
17447
17449 DeclarationName Name,
17450 OverloadCandidateSet &CandidateSet,
17451 FunctionDecl *Fn, MultiExprArg Args,
17452 bool IsMember) {
17453 StringLiteral *Msg = Fn->getDeletedMessage();
17454 CandidateSet.NoteCandidates(
17455 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17456 << IsMember << Name << (Msg != nullptr)
17457 << (Msg ? Msg->getString() : StringRef())
17458 << Range),
17459 *this, OCD_AllCandidates, Args);
17460}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:186
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:32
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress, TemplateSpecCandidateSetKind CandidateSetKind=TemplateSpecCandidateSetKind::Normal)
Diagnose a failed template-argument deduction.
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, const OverloadCandidateSet &ResolvedCandidateSet)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, const OverloadCandidateSet &ResolvedCandidateSet, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, const OverloadCandidateSet &ResolvedCandidates, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static ExprResult CreateFunctionRefExpr(Sema &S, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
A convenience routine for creating a decayed reference to a function.
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:123
bool isAbsent() const
Definition APValue.h:485
bool isFloat() const
Definition APValue.h:490
bool isInt() const
Definition APValue.h:489
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:985
APFloat & getFloat()
Definition APValue.h:526
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
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:850
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:966
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:965
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:3983
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:399
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3813
QualType getElementType() const
Definition TypeBase.h:3825
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8244
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2211
StringRef getOpcodeStr() const
Definition Expr.h:4148
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2164
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:5138
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
Pointer to a block type.
Definition TypeBase.h:3646
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:2642
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3106
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3009
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3013
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:725
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:655
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1569
bool hasDefinition() const
Definition DeclCXX.h:562
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
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:1545
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3151
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3369
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:5160
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3851
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:4478
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4497
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4494
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:1290
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:1483
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:494
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:796
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:781
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:772
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:608
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4146
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4364
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4262
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1973
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1957
const Expr * getExpr() const
Definition DeclCXX.h:1958
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1497
The return type of classify().
Definition Expr.h:340
bool isLValue() const
Definition Expr.h:391
bool isPRValue() const
Definition Expr.h:394
bool isXValue() const
Definition Expr.h:392
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:399
bool isRValue() const
Definition Expr.h:395
This represents one expression.
Definition Expr.h:113
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:288
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3372
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:831
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:4104
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:480
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:416
QualType getType() const
Definition Expr.h:145
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
ExtVectorType - Extended vector type.
Definition TypeBase.h:4358
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3295
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2123
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2152
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
param_iterator param_end()
Definition Decl.h:2918
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3708
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3907
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4303
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4352
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3789
param_iterator param_begin()
Definition Decl.h:2917
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3119
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4296
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3911
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4169
bool isConsteval() const
Definition Decl.h:2609
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3752
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3286
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:2993
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:3757
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3868
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5398
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5902
unsigned getNumParams() const
Definition TypeBase.h:5676
Qualifiers getMethodQuals() const
Definition TypeBase.h:5824
QualType getParamType(unsigned i) const
Definition TypeBase.h:5678
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5802
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5838
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:4705
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4776
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4633
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
ExtInfo getExtInfo() const
Definition TypeBase.h:4950
CallingConv getCallConv() const
Definition TypeBase.h:4949
QualType getReturnType() const
Definition TypeBase.h:4934
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4962
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:4759
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:3897
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2103
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:5352
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5468
unsigned getNumInits() const
Definition Expr.h:5385
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2529
const Expr * getInit(unsigned Init) const
Definition Expr.h:5407
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2547
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:3708
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:4442
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3597
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3519
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding the member name, if any.
Definition Expr.h:3525
NestedNameSpecifierLoc getQualifierLoc() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name,...
Definition Expr.h:3510
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
bool hasExplicitTemplateArgs() const
Determines whether the member name was followed by an explicit template argument list.
Definition Expr.h:3552
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3505
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:3556
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3626
Expr * getBase() const
Definition Expr.h:3485
void setBase(Expr *E)
Definition Expr.h:3484
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1824
DeclarationNameInfo getMemberNameInfo() const
Retrieve the member declaration name info.
Definition Expr.h:3585
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3495
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3744
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3776
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5827
QualType getPointeeType() const
Definition TypeBase.h:3762
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1682
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
Represent a C++ namespace.
Definition Decl.h:593
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8013
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8069
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8158
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8127
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8081
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8121
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2007
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8133
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
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:1463
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1397
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:1413
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:1428
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1350
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1388
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:3142
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3294
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3203
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3258
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3255
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3233
decls_iterator decls_begin() const
Definition ExprCXX.h:3235
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3246
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3268
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3264
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3324
decls_iterator decls_end() const
Definition ExprCXX.h:3238
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3252
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:2226
Represents a parameter to a function.
Definition Decl.h:1820
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3044
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5232
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8512
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8506
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8517
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3810
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:8428
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8554
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8468
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:8613
QualType getCanonicalType() const
Definition TypeBase.h:8480
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8522
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:8582
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8501
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8549
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8474
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:8593
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8460
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8368
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8375
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4967
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:3726
Represents a struct/union/class.
Definition Decl.h:4460
field_range fields() const
Definition Decl.h:4663
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3671
QualType getPointeeType() const
Definition TypeBase.h:3693
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:1663
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1708
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:211
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:462
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:399
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:409
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:311
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10385
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:10108
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1384
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1419
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:12573
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12607
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1446
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:10126
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:9394
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9421
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9406
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9402
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:418
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:169
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition Sema.h:1471
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:10468
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10471
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10477
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10475
@ AR_dependent
Definition Sema.h:1690
@ AR_accessible
Definition Sema.h:1688
@ AR_inaccessible
Definition Sema.h:1689
@ AR_delayed
Definition Sema.h:1691
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:2079
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:1768
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1304
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp: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:228
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition Sema.h:1516
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:764
ASTContext & getASTContext() const
Definition Sema.h:935
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp: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:10856
@ FRS_DiagnosticIssued
Definition Sema.h:10858
@ FRS_NoViableFunction
Definition Sema.h:10857
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9387
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:10177
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1208
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3651
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:12271
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:928
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1302
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
SemaHLSL & HLSL()
Definition Sema.h:1481
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9386
MemberPointerConversionDirection
Definition Sema.h:10309
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:10496
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15668
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:9922
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:7019
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:1444
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:8232
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:14079
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:7516
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:13822
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:15623
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:127
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6782
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6751
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:10301
SourceManager & SourceMgr
Definition Sema.h:1307
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1306
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:524
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6459
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:1451
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:8712
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:1819
StringRef getString() const
Definition Expr.h:1887
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:684
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:726
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:711
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3673
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:8685
bool isVoidType() const
Definition TypeBase.h:9037
bool isBooleanType() const
Definition TypeBase.h:9174
bool isObjCBuiltinType() const
Definition TypeBase.h:8895
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2411
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:2118
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:916
bool isIncompleteArrayType() const
Definition TypeBase.h:8772
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2388
bool isFloat16Type() const
Definition TypeBase.h:9046
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:853
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2295
bool isRValueReferenceType() const
Definition TypeBase.h:8697
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:8768
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9204
bool isArrayType() const
Definition TypeBase.h:8764
bool isCharType() const
Definition Type.cpp:2315
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9109
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2546
bool isPointerType() const
Definition TypeBase.h:8665
bool isArrayParameterType() const
Definition TypeBase.h:8780
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9081
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2791
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
bool isReferenceType() const
Definition TypeBase.h:8689
bool isEnumeralType() const
Definition TypeBase.h:8796
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2278
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8865
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9159
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2351
bool isExtVectorBoolType() const
Definition TypeBase.h:8812
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8852
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:8693
bool isBitIntType() const
Definition TypeBase.h:8940
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:2627
bool isAnyComplexType() const
Definition TypeBase.h:8800
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9097
bool isHalfType() const
Definition TypeBase.h:9041
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9019
bool isQueueT() const
Definition TypeBase.h:8921
bool isMemberPointerType() const
Definition TypeBase.h:8746
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9187
bool isObjCIdType() const
Definition TypeBase.h:8877
bool isMatrixType() const
Definition TypeBase.h:8828
bool isOverflowBehaviorType() const
Definition TypeBase.h:8836
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9180
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:8913
bool isBFloat16Type() const
Definition TypeBase.h:9058
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2651
bool isFunctionType() const
Definition TypeBase.h:8661
bool isObjCObjectPointerType() const
Definition TypeBase.h:8844
bool isVectorType() const
Definition TypeBase.h:8804
bool isObjCClassType() const
Definition TypeBase.h:8883
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2529
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2812
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:8994
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:2456
bool isAnyPointerType() const
Definition TypeBase.h:8673
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:8909
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:782
bool isNullPtrType() const
Definition TypeBase.h:9074
bool isRecordType() const
Definition TypeBase.h:8792
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1458
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:5195
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1434
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3372
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3441
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:463
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4179
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4287
QualType getBaseType() const
Definition ExprCXX.h:4261
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4271
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4252
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4297
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4291
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:999
QualType getType() const
Definition Decl.h:724
unsigned getNumElements() const
Definition TypeBase.h:4281
QualType getElementType() const
Definition TypeBase.h:4280
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:283
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
Top level wrappers for InstallAPI frontend operations.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:817
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:65
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
Stmt Stmt * Callback
Definition StmtOpenMP.h:919
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:661
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h: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:1062
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:683
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:706
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:727
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:685
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:723
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:581
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:217
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2019
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h: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:374
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:424
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:419
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:395
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:381
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:414
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:398
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:387
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:401
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:411
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:405
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:408
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h: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:1524
@ 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:832
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:840
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:838
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6010
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:442
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h: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:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
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).
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:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * ExtendedDiag
Location where we spot ptr to int cast or null subobject while evaluating constant expression in MS c...
Definition Expr.h:654
Extra information about a function prototype.
Definition TypeBase.h:5483
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5488
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:10588
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10595
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13233
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13318
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13367
Abstract class used to diagnose incomplete types.
Definition Sema.h:8309
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.