clang 19.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
14#include "clang/AST/ASTLambda.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/SmallVector.h"
44#include "llvm/Support/Casting.h"
45#include <algorithm>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
174 static const char *const Name[] = {
175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
179 "Function pointer conversion",
180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
183 "Complex promotion",
184 "Integral conversion",
185 "Floating conversion",
186 "Complex conversion",
187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
190 "Boolean conversion",
191 "Compatible-types conversion",
192 "Derived-to-base conversion",
193 "Vector conversion",
194 "SVE Vector conversion",
195 "RVV Vector conversion",
196 "Vector splat",
197 "Complex-real conversion",
198 "Block Pointer conversion",
199 "Transparent Union Conversion",
200 "Writeback conversion",
201 "OpenCL Zero Event Conversion",
202 "OpenCL Zero Queue Conversion",
203 "C specific type conversion",
204 "Incompatible pointer conversion",
205 "Fixed point conversion",
206 "HLSL vector truncation",
207 "Non-decaying array conversion",
208 };
209 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
210 return Name[Kind];
211}
212
213/// StandardConversionSequence - Set the standard conversion
214/// sequence to the identity conversion.
222 ReferenceBinding = false;
223 DirectBinding = false;
224 IsLvalueReference = true;
225 BindsToFunctionLvalue = false;
226 BindsToRvalue = false;
229 CopyConstructor = nullptr;
230}
231
232/// getRank - Retrieve the rank of this standard conversion sequence
233/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
234/// implicit conversions.
237 if (GetConversionRank(First) > Rank)
238 Rank = GetConversionRank(First);
239 if (GetConversionRank(Second) > Rank)
241 if (GetConversionRank(Element) > Rank)
243 if (GetConversionRank(Third) > Rank)
244 Rank = GetConversionRank(Third);
245 return Rank;
246}
247
248/// isPointerConversionToBool - Determines whether this conversion is
249/// a conversion of a pointer or pointer-to-member to bool. This is
250/// used as part of the ranking of standard conversion sequences
251/// (C++ 13.3.3.2p4).
253 // Note that FromType has not necessarily been transformed by the
254 // array-to-pointer or function-to-pointer implicit conversions, so
255 // check for their presence as well as checking whether FromType is
256 // a pointer.
257 if (getToType(1)->isBooleanType() &&
258 (getFromType()->isPointerType() ||
259 getFromType()->isMemberPointerType() ||
260 getFromType()->isObjCObjectPointerType() ||
261 getFromType()->isBlockPointerType() ||
263 return true;
264
265 return false;
266}
267
268/// isPointerConversionToVoidPointer - Determines whether this
269/// conversion is a conversion of a pointer to a void pointer. This is
270/// used as part of the ranking of standard conversion sequences (C++
271/// 13.3.3.2p4).
272bool
275 QualType FromType = getFromType();
276 QualType ToType = getToType(1);
277
278 // Note that FromType has not necessarily been transformed by the
279 // array-to-pointer implicit conversion, so check for its presence
280 // and redo the conversion to get a pointer.
282 FromType = Context.getArrayDecayedType(FromType);
283
284 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
285 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
286 return ToPtrType->getPointeeType()->isVoidType();
287
288 return false;
289}
290
291/// Skip any implicit casts which could be either part of a narrowing conversion
292/// or after one in an implicit conversion.
294 const Expr *Converted) {
295 // We can have cleanups wrapping the converted expression; these need to be
296 // preserved so that destructors run if necessary.
297 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
298 Expr *Inner =
299 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
300 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
301 EWC->getObjects());
302 }
303
304 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
305 switch (ICE->getCastKind()) {
306 case CK_NoOp:
307 case CK_IntegralCast:
308 case CK_IntegralToBoolean:
309 case CK_IntegralToFloating:
310 case CK_BooleanToSignedIntegral:
311 case CK_FloatingToIntegral:
312 case CK_FloatingToBoolean:
313 case CK_FloatingCast:
314 Converted = ICE->getSubExpr();
315 continue;
316
317 default:
318 return Converted;
319 }
320 }
321
322 return Converted;
323}
324
325/// Check if this standard conversion sequence represents a narrowing
326/// conversion, according to C++11 [dcl.init.list]p7.
327///
328/// \param Ctx The AST context.
329/// \param Converted The result of applying this standard conversion sequence.
330/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
331/// value of the expression prior to the narrowing conversion.
332/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
333/// type of the expression prior to the narrowing conversion.
334/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
335/// from floating point types to integral types should be ignored.
337 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
338 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
339 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
340 "narrowing check outside C++");
341
342 // C++11 [dcl.init.list]p7:
343 // A narrowing conversion is an implicit conversion ...
344 QualType FromType = getToType(0);
345 QualType ToType = getToType(1);
346
347 // A conversion to an enumeration type is narrowing if the conversion to
348 // the underlying type is narrowing. This only arises for expressions of
349 // the form 'Enum{init}'.
350 if (auto *ET = ToType->getAs<EnumType>())
351 ToType = ET->getDecl()->getIntegerType();
352
353 switch (Second) {
354 // 'bool' is an integral type; dispatch to the right place to handle it.
356 if (FromType->isRealFloatingType())
357 goto FloatingIntegralConversion;
359 goto IntegralConversion;
360 // -- from a pointer type or pointer-to-member type to bool, or
361 return NK_Type_Narrowing;
362
363 // -- from a floating-point type to an integer type, or
364 //
365 // -- from an integer type or unscoped enumeration type to a floating-point
366 // type, except where the source is a constant expression and the actual
367 // value after conversion will fit into the target type and will produce
368 // the original value when converted back to the original type, or
370 FloatingIntegralConversion:
371 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
372 return NK_Type_Narrowing;
373 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
374 ToType->isRealFloatingType()) {
375 if (IgnoreFloatToIntegralConversion)
376 return NK_Not_Narrowing;
377 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
378 assert(Initializer && "Unknown conversion expression");
379
380 // If it's value-dependent, we can't tell whether it's narrowing.
381 if (Initializer->isValueDependent())
383
384 if (std::optional<llvm::APSInt> IntConstantValue =
385 Initializer->getIntegerConstantExpr(Ctx)) {
386 // Convert the integer to the floating type.
387 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
388 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
389 llvm::APFloat::rmNearestTiesToEven);
390 // And back.
391 llvm::APSInt ConvertedValue = *IntConstantValue;
392 bool ignored;
393 Result.convertToInteger(ConvertedValue,
394 llvm::APFloat::rmTowardZero, &ignored);
395 // If the resulting value is different, this was a narrowing conversion.
396 if (*IntConstantValue != ConvertedValue) {
397 ConstantValue = APValue(*IntConstantValue);
398 ConstantType = Initializer->getType();
400 }
401 } else {
402 // Variables are always narrowings.
404 }
405 }
406 return NK_Not_Narrowing;
407
408 // -- from long double to double or float, or from double to float, except
409 // where the source is a constant expression and the actual value after
410 // conversion is within the range of values that can be represented (even
411 // if it cannot be represented exactly), or
413 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
414 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
415 // FromType is larger than ToType.
416 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
417
418 // If it's value-dependent, we can't tell whether it's narrowing.
419 if (Initializer->isValueDependent())
421
423 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
424 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
425 // Constant!
426 if (Ctx.getLangOpts().C23)
427 ConstantValue = R.Val;
428 assert(ConstantValue.isFloat());
429 llvm::APFloat FloatVal = ConstantValue.getFloat();
430 // Convert the source value into the target type.
431 bool ignored;
432 llvm::APFloat Converted = FloatVal;
433 llvm::APFloat::opStatus ConvertStatus =
434 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
435 llvm::APFloat::rmNearestTiesToEven, &ignored);
436 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
437 llvm::APFloat::rmNearestTiesToEven, &ignored);
438 if (Ctx.getLangOpts().C23) {
439 if (FloatVal.isNaN() && Converted.isNaN() &&
440 !FloatVal.isSignaling() && !Converted.isSignaling()) {
441 // Quiet NaNs are considered the same value, regardless of
442 // payloads.
443 return NK_Not_Narrowing;
444 }
445 // For normal values, check exact equality.
446 if (!Converted.bitwiseIsEqual(FloatVal)) {
447 ConstantType = Initializer->getType();
449 }
450 } else {
451 // If there was no overflow, the source value is within the range of
452 // values that can be represented.
453 if (ConvertStatus & llvm::APFloat::opOverflow) {
454 ConstantType = Initializer->getType();
456 }
457 }
458 } else {
460 }
461 }
462 return NK_Not_Narrowing;
463
464 // -- from an integer type or unscoped enumeration type to an integer type
465 // that cannot represent all the values of the original type, except where
466 // the source is a constant expression and the actual value after
467 // conversion will fit into the target type and will produce the original
468 // value when converted back to the original type.
470 IntegralConversion: {
471 assert(FromType->isIntegralOrUnscopedEnumerationType());
472 assert(ToType->isIntegralOrUnscopedEnumerationType());
473 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
474 const unsigned FromWidth = Ctx.getIntWidth(FromType);
475 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
476 const unsigned ToWidth = Ctx.getIntWidth(ToType);
477
478 if (FromWidth > ToWidth ||
479 (FromWidth == ToWidth && FromSigned != ToSigned) ||
480 (FromSigned && !ToSigned)) {
481 // Not all values of FromType can be represented in ToType.
482 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
483
484 // If it's value-dependent, we can't tell whether it's narrowing.
485 if (Initializer->isValueDependent())
487
488 std::optional<llvm::APSInt> OptInitializerValue;
489 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
490 // Such conversions on variables are always narrowing.
492 }
493 llvm::APSInt &InitializerValue = *OptInitializerValue;
494 bool Narrowing = false;
495 if (FromWidth < ToWidth) {
496 // Negative -> unsigned is narrowing. Otherwise, more bits is never
497 // narrowing.
498 if (InitializerValue.isSigned() && InitializerValue.isNegative())
499 Narrowing = true;
500 } else {
501 // Add a bit to the InitializerValue so we don't have to worry about
502 // signed vs. unsigned comparisons.
503 InitializerValue = InitializerValue.extend(
504 InitializerValue.getBitWidth() + 1);
505 // Convert the initializer to and from the target width and signed-ness.
506 llvm::APSInt ConvertedValue = InitializerValue;
507 ConvertedValue = ConvertedValue.trunc(ToWidth);
508 ConvertedValue.setIsSigned(ToSigned);
509 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
510 ConvertedValue.setIsSigned(InitializerValue.isSigned());
511 // If the result is different, this was a narrowing conversion.
512 if (ConvertedValue != InitializerValue)
513 Narrowing = true;
514 }
515 if (Narrowing) {
516 ConstantType = Initializer->getType();
517 ConstantValue = APValue(InitializerValue);
519 }
520 }
521 return NK_Not_Narrowing;
522 }
523 case ICK_Complex_Real:
524 if (FromType->isComplexType() && !ToType->isComplexType())
525 return NK_Type_Narrowing;
526 return NK_Not_Narrowing;
527
529 if (Ctx.getLangOpts().C23) {
530 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
532 if (Initializer->EvaluateAsRValue(R, Ctx)) {
533 ConstantValue = R.Val;
534 assert(ConstantValue.isFloat());
535 llvm::APFloat FloatVal = ConstantValue.getFloat();
536 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
537 // value, the unqualified versions of the type of the initializer and
538 // the corresponding real type of the object declared shall be
539 // compatible.
540 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
541 ConstantType = Initializer->getType();
543 }
544 }
545 }
546 return NK_Not_Narrowing;
547 default:
548 // Other kinds of conversions are not narrowings.
549 return NK_Not_Narrowing;
550 }
551}
552
553/// dump - Print this standard conversion sequence to standard
554/// error. Useful for debugging overloading issues.
555LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
556 raw_ostream &OS = llvm::errs();
557 bool PrintedSomething = false;
558 if (First != ICK_Identity) {
560 PrintedSomething = true;
561 }
562
563 if (Second != ICK_Identity) {
564 if (PrintedSomething) {
565 OS << " -> ";
566 }
568
569 if (CopyConstructor) {
570 OS << " (by copy constructor)";
571 } else if (DirectBinding) {
572 OS << " (direct reference binding)";
573 } else if (ReferenceBinding) {
574 OS << " (reference binding)";
575 }
576 PrintedSomething = true;
577 }
578
579 if (Third != ICK_Identity) {
580 if (PrintedSomething) {
581 OS << " -> ";
582 }
584 PrintedSomething = true;
585 }
586
587 if (!PrintedSomething) {
588 OS << "No conversions required";
589 }
590}
591
592/// dump - Print this user-defined conversion sequence to standard
593/// error. Useful for debugging overloading issues.
595 raw_ostream &OS = llvm::errs();
596 if (Before.First || Before.Second || Before.Third) {
597 Before.dump();
598 OS << " -> ";
599 }
601 OS << '\'' << *ConversionFunction << '\'';
602 else
603 OS << "aggregate initialization";
604 if (After.First || After.Second || After.Third) {
605 OS << " -> ";
606 After.dump();
607 }
608}
609
610/// dump - Print this implicit conversion sequence to standard
611/// error. Useful for debugging overloading issues.
613 raw_ostream &OS = llvm::errs();
615 OS << "Worst list element conversion: ";
616 switch (ConversionKind) {
618 OS << "Standard conversion: ";
619 Standard.dump();
620 break;
622 OS << "User-defined conversion: ";
624 break;
626 OS << "Ellipsis conversion";
627 break;
629 OS << "Ambiguous conversion";
630 break;
631 case BadConversion:
632 OS << "Bad conversion";
633 break;
634 }
635
636 OS << "\n";
637}
638
640 new (&conversions()) ConversionSet();
641}
642
644 conversions().~ConversionSet();
645}
646
647void
652}
653
654namespace {
655 // Structure used by DeductionFailureInfo to store
656 // template argument information.
657 struct DFIArguments {
658 TemplateArgument FirstArg;
659 TemplateArgument SecondArg;
660 };
661 // Structure used by DeductionFailureInfo to store
662 // template parameter and template argument information.
663 struct DFIParamWithArguments : DFIArguments {
664 TemplateParameter Param;
665 };
666 // Structure used by DeductionFailureInfo to store template argument
667 // information and the index of the problematic call argument.
668 struct DFIDeducedMismatchArgs : DFIArguments {
669 TemplateArgumentList *TemplateArgs;
670 unsigned CallArgIndex;
671 };
672 // Structure used by DeductionFailureInfo to store information about
673 // unsatisfied constraints.
674 struct CNSInfo {
675 TemplateArgumentList *TemplateArgs;
676 ConstraintSatisfaction Satisfaction;
677 };
678}
679
680/// Convert from Sema's representation of template deduction information
681/// to the form used in overload-candidate information.
685 TemplateDeductionInfo &Info) {
687 Result.Result = static_cast<unsigned>(TDK);
688 Result.HasDiagnostic = false;
689 switch (TDK) {
696 Result.Data = nullptr;
697 break;
698
701 Result.Data = Info.Param.getOpaqueValue();
702 break;
703
706 // FIXME: Should allocate from normal heap so that we can free this later.
707 auto *Saved = new (Context) DFIDeducedMismatchArgs;
708 Saved->FirstArg = Info.FirstArg;
709 Saved->SecondArg = Info.SecondArg;
710 Saved->TemplateArgs = Info.takeSugared();
711 Saved->CallArgIndex = Info.CallArgIndex;
712 Result.Data = Saved;
713 break;
714 }
715
717 // FIXME: Should allocate from normal heap so that we can free this later.
718 DFIArguments *Saved = new (Context) DFIArguments;
719 Saved->FirstArg = Info.FirstArg;
720 Saved->SecondArg = Info.SecondArg;
721 Result.Data = Saved;
722 break;
723 }
724
726 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
729 // FIXME: Should allocate from normal heap so that we can free this later.
730 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
731 Saved->Param = Info.Param;
732 Saved->FirstArg = Info.FirstArg;
733 Saved->SecondArg = Info.SecondArg;
734 Result.Data = Saved;
735 break;
736 }
737
739 Result.Data = Info.takeSugared();
740 if (Info.hasSFINAEDiagnostic()) {
744 Result.HasDiagnostic = true;
745 }
746 break;
747
749 CNSInfo *Saved = new (Context) CNSInfo;
750 Saved->TemplateArgs = Info.takeSugared();
751 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
752 Result.Data = Saved;
753 break;
754 }
755
759 llvm_unreachable("not a deduction failure");
760 }
761
762 return Result;
763}
764
766 switch (static_cast<TemplateDeductionResult>(Result)) {
776 break;
777
784 // FIXME: Destroy the data?
785 Data = nullptr;
786 break;
787
789 // FIXME: Destroy the template argument list?
790 Data = nullptr;
792 Diag->~PartialDiagnosticAt();
793 HasDiagnostic = false;
794 }
795 break;
796
798 // FIXME: Destroy the template argument list?
799 Data = nullptr;
801 Diag->~PartialDiagnosticAt();
802 HasDiagnostic = false;
803 }
804 break;
805
806 // Unhandled
809 break;
810 }
811}
812
814 if (HasDiagnostic)
815 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
816 return nullptr;
817}
818
820 switch (static_cast<TemplateDeductionResult>(Result)) {
833 return TemplateParameter();
834
837 return TemplateParameter::getFromOpaqueValue(Data);
838
842 return static_cast<DFIParamWithArguments*>(Data)->Param;
843
844 // Unhandled
847 break;
848 }
849
850 return TemplateParameter();
851}
852
854 switch (static_cast<TemplateDeductionResult>(Result)) {
868 return nullptr;
869
872 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
873
875 return static_cast<TemplateArgumentList*>(Data);
876
878 return static_cast<CNSInfo*>(Data)->TemplateArgs;
879
880 // Unhandled
883 break;
884 }
885
886 return nullptr;
887}
888
890 switch (static_cast<TemplateDeductionResult>(Result)) {
902 return nullptr;
903
910 return &static_cast<DFIArguments*>(Data)->FirstArg;
911
912 // Unhandled
915 break;
916 }
917
918 return nullptr;
919}
920
922 switch (static_cast<TemplateDeductionResult>(Result)) {
935 return nullptr;
936
942 return &static_cast<DFIArguments*>(Data)->SecondArg;
943
944 // Unhandled
947 break;
948 }
949
950 return nullptr;
951}
952
953std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
954 switch (static_cast<TemplateDeductionResult>(Result)) {
957 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
958
959 default:
960 return std::nullopt;
961 }
962}
963
965 const FunctionDecl *Y) {
966 if (!X || !Y)
967 return false;
968 if (X->getNumParams() != Y->getNumParams())
969 return false;
970 // FIXME: when do rewritten comparison operators
971 // with explicit object parameters correspond?
972 // https://cplusplus.github.io/CWG/issues/2797.html
973 for (unsigned I = 0; I < X->getNumParams(); ++I)
974 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
975 Y->getParamDecl(I)->getType()))
976 return false;
977 if (auto *FTX = X->getDescribedFunctionTemplate()) {
978 auto *FTY = Y->getDescribedFunctionTemplate();
979 if (!FTY)
980 return false;
981 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
982 FTY->getTemplateParameters()))
983 return false;
984 }
985 return true;
986}
987
989 Expr *FirstOperand, FunctionDecl *EqFD) {
990 assert(EqFD->getOverloadedOperator() ==
991 OverloadedOperatorKind::OO_EqualEqual);
992 // C++2a [over.match.oper]p4:
993 // A non-template function or function template F named operator== is a
994 // rewrite target with first operand o unless a search for the name operator!=
995 // in the scope S from the instantiation context of the operator expression
996 // finds a function or function template that would correspond
997 // ([basic.scope.scope]) to F if its name were operator==, where S is the
998 // scope of the class type of o if F is a class member, and the namespace
999 // scope of which F is a member otherwise. A function template specialization
1000 // named operator== is a rewrite target if its function template is a rewrite
1001 // target.
1003 OverloadedOperatorKind::OO_ExclaimEqual);
1004 if (isa<CXXMethodDecl>(EqFD)) {
1005 // If F is a class member, search scope is class type of first operand.
1006 QualType RHS = FirstOperand->getType();
1007 auto *RHSRec = RHS->getAs<RecordType>();
1008 if (!RHSRec)
1009 return true;
1010 LookupResult Members(S, NotEqOp, OpLoc,
1012 S.LookupQualifiedName(Members, RHSRec->getDecl());
1013 Members.suppressAccessDiagnostics();
1014 for (NamedDecl *Op : Members)
1015 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1016 return false;
1017 return true;
1018 }
1019 // Otherwise the search scope is the namespace scope of which F is a member.
1020 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1021 auto *NotEqFD = Op->getAsFunction();
1022 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1023 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1024 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1026 cast<Decl>(Op->getLexicalDeclContext())))
1027 return false;
1028 }
1029 return true;
1030}
1031
1035 return false;
1036 return Op == OO_EqualEqual || Op == OO_Spaceship;
1037}
1038
1040 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1041 auto Op = FD->getOverloadedOperator();
1042 if (!allowsReversed(Op))
1043 return false;
1044 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1045 assert(OriginalArgs.size() == 2);
1047 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1048 return false;
1049 }
1050 // Don't bother adding a reversed candidate that can never be a better
1051 // match than the non-reversed version.
1052 return FD->getNumNonObjectParams() != 2 ||
1054 FD->getParamDecl(1)->getType()) ||
1055 FD->hasAttr<EnableIfAttr>();
1056}
1057
1058void OverloadCandidateSet::destroyCandidates() {
1059 for (iterator i = begin(), e = end(); i != e; ++i) {
1060 for (auto &C : i->Conversions)
1061 C.~ImplicitConversionSequence();
1062 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1063 i->DeductionFailure.Destroy();
1064 }
1065}
1066
1068 destroyCandidates();
1069 SlabAllocator.Reset();
1070 NumInlineBytesUsed = 0;
1071 Candidates.clear();
1072 Functions.clear();
1073 Kind = CSK;
1074}
1075
1076namespace {
1077 class UnbridgedCastsSet {
1078 struct Entry {
1079 Expr **Addr;
1080 Expr *Saved;
1081 };
1082 SmallVector<Entry, 2> Entries;
1083
1084 public:
1085 void save(Sema &S, Expr *&E) {
1086 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1087 Entry entry = { &E, E };
1088 Entries.push_back(entry);
1089 E = S.stripARCUnbridgedCast(E);
1090 }
1091
1092 void restore() {
1094 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1095 *i->Addr = i->Saved;
1096 }
1097 };
1098}
1099
1100/// checkPlaceholderForOverload - Do any interesting placeholder-like
1101/// preprocessing on the given expression.
1102///
1103/// \param unbridgedCasts a collection to which to add unbridged casts;
1104/// without this, they will be immediately diagnosed as errors
1105///
1106/// Return true on unrecoverable error.
1107static bool
1109 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1110 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1111 // We can't handle overloaded expressions here because overload
1112 // resolution might reasonably tweak them.
1113 if (placeholder->getKind() == BuiltinType::Overload) return false;
1114
1115 // If the context potentially accepts unbridged ARC casts, strip
1116 // the unbridged cast and add it to the collection for later restoration.
1117 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1118 unbridgedCasts) {
1119 unbridgedCasts->save(S, E);
1120 return false;
1121 }
1122
1123 // Go ahead and check everything else.
1124 ExprResult result = S.CheckPlaceholderExpr(E);
1125 if (result.isInvalid())
1126 return true;
1127
1128 E = result.get();
1129 return false;
1130 }
1131
1132 // Nothing to do.
1133 return false;
1134}
1135
1136/// checkArgPlaceholdersForOverload - Check a set of call operands for
1137/// placeholders.
1139 UnbridgedCastsSet &unbridged) {
1140 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1141 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1142 return true;
1143
1144 return false;
1145}
1146
1147/// Determine whether the given New declaration is an overload of the
1148/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1149/// New and Old cannot be overloaded, e.g., if New has the same signature as
1150/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1151/// functions (or function templates) at all. When it does return Ovl_Match or
1152/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1153/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1154/// declaration.
1155///
1156/// Example: Given the following input:
1157///
1158/// void f(int, float); // #1
1159/// void f(int, int); // #2
1160/// int f(int, int); // #3
1161///
1162/// When we process #1, there is no previous declaration of "f", so IsOverload
1163/// will not be used.
1164///
1165/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1166/// the parameter types, we see that #1 and #2 are overloaded (since they have
1167/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1168/// unchanged.
1169///
1170/// When we process #3, Old is an overload set containing #1 and #2. We compare
1171/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1172/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1173/// functions are not part of the signature), IsOverload returns Ovl_Match and
1174/// MatchedDecl will be set to point to the FunctionDecl for #2.
1175///
1176/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1177/// by a using declaration. The rules for whether to hide shadow declarations
1178/// ignore some properties which otherwise figure into a function template's
1179/// signature.
1182 NamedDecl *&Match, bool NewIsUsingDecl) {
1183 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1184 I != E; ++I) {
1185 NamedDecl *OldD = *I;
1186
1187 bool OldIsUsingDecl = false;
1188 if (isa<UsingShadowDecl>(OldD)) {
1189 OldIsUsingDecl = true;
1190
1191 // We can always introduce two using declarations into the same
1192 // context, even if they have identical signatures.
1193 if (NewIsUsingDecl) continue;
1194
1195 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1196 }
1197
1198 // A using-declaration does not conflict with another declaration
1199 // if one of them is hidden.
1200 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1201 continue;
1202
1203 // If either declaration was introduced by a using declaration,
1204 // we'll need to use slightly different rules for matching.
1205 // Essentially, these rules are the normal rules, except that
1206 // function templates hide function templates with different
1207 // return types or template parameter lists.
1208 bool UseMemberUsingDeclRules =
1209 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1210 !New->getFriendObjectKind();
1211
1212 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1213 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1214 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1215 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1216 continue;
1217 }
1218
1219 if (!isa<FunctionTemplateDecl>(OldD) &&
1220 !shouldLinkPossiblyHiddenDecl(*I, New))
1221 continue;
1222
1223 Match = *I;
1224 return Ovl_Match;
1225 }
1226
1227 // Builtins that have custom typechecking or have a reference should
1228 // not be overloadable or redeclarable.
1229 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1230 Match = *I;
1231 return Ovl_NonFunction;
1232 }
1233 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1234 // We can overload with these, which can show up when doing
1235 // redeclaration checks for UsingDecls.
1236 assert(Old.getLookupKind() == LookupUsingDeclName);
1237 } else if (isa<TagDecl>(OldD)) {
1238 // We can always overload with tags by hiding them.
1239 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1240 // Optimistically assume that an unresolved using decl will
1241 // overload; if it doesn't, we'll have to diagnose during
1242 // template instantiation.
1243 //
1244 // Exception: if the scope is dependent and this is not a class
1245 // member, the using declaration can only introduce an enumerator.
1246 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1247 Match = *I;
1248 return Ovl_NonFunction;
1249 }
1250 } else {
1251 // (C++ 13p1):
1252 // Only function declarations can be overloaded; object and type
1253 // declarations cannot be overloaded.
1254 Match = *I;
1255 return Ovl_NonFunction;
1256 }
1257 }
1258
1259 // C++ [temp.friend]p1:
1260 // For a friend function declaration that is not a template declaration:
1261 // -- if the name of the friend is a qualified or unqualified template-id,
1262 // [...], otherwise
1263 // -- if the name of the friend is a qualified-id and a matching
1264 // non-template function is found in the specified class or namespace,
1265 // the friend declaration refers to that function, otherwise,
1266 // -- if the name of the friend is a qualified-id and a matching function
1267 // template is found in the specified class or namespace, the friend
1268 // declaration refers to the deduced specialization of that function
1269 // template, otherwise
1270 // -- the name shall be an unqualified-id [...]
1271 // If we get here for a qualified friend declaration, we've just reached the
1272 // third bullet. If the type of the friend is dependent, skip this lookup
1273 // until instantiation.
1274 if (New->getFriendObjectKind() && New->getQualifier() &&
1277 !New->getType()->isDependentType()) {
1278 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1279 TemplateSpecResult.addAllDecls(Old);
1280 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1281 /*QualifiedFriend*/true)) {
1282 New->setInvalidDecl();
1283 return Ovl_Overload;
1284 }
1285
1286 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1287 return Ovl_Match;
1288 }
1289
1290 return Ovl_Overload;
1291}
1292
1293static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1294 FunctionDecl *Old,
1295 bool UseMemberUsingDeclRules,
1296 bool ConsiderCudaAttrs,
1297 bool UseOverrideRules = false) {
1298 // C++ [basic.start.main]p2: This function shall not be overloaded.
1299 if (New->isMain())
1300 return false;
1301
1302 // MSVCRT user defined entry points cannot be overloaded.
1303 if (New->isMSVCRTEntryPoint())
1304 return false;
1305
1308
1309 // C++ [temp.fct]p2:
1310 // A function template can be overloaded with other function templates
1311 // and with normal (non-template) functions.
1312 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1313 return true;
1314
1315 // Is the function New an overload of the function Old?
1316 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1317 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1318
1319 // Compare the signatures (C++ 1.3.10) of the two functions to
1320 // determine whether they are overloads. If we find any mismatch
1321 // in the signature, they are overloads.
1322
1323 // If either of these functions is a K&R-style function (no
1324 // prototype), then we consider them to have matching signatures.
1325 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1326 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1327 return false;
1328
1329 const auto *OldType = cast<FunctionProtoType>(OldQType);
1330 const auto *NewType = cast<FunctionProtoType>(NewQType);
1331
1332 // The signature of a function includes the types of its
1333 // parameters (C++ 1.3.10), which includes the presence or absence
1334 // of the ellipsis; see C++ DR 357).
1335 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1336 return true;
1337
1338 // For member-like friends, the enclosing class is part of the signature.
1339 if ((New->isMemberLikeConstrainedFriend() ||
1342 return true;
1343
1344 // Compare the parameter lists.
1345 // This can only be done once we have establish that friend functions
1346 // inhabit the same context, otherwise we might tried to instantiate
1347 // references to non-instantiated entities during constraint substitution.
1348 // GH78101.
1349 if (NewTemplate) {
1350 // C++ [temp.over.link]p4:
1351 // The signature of a function template consists of its function
1352 // signature, its return type and its template parameter list. The names
1353 // of the template parameters are significant only for establishing the
1354 // relationship between the template parameters and the rest of the
1355 // signature.
1356 //
1357 // We check the return type and template parameter lists for function
1358 // templates first; the remaining checks follow.
1359 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1360 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1361 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1362 bool SameReturnType = SemaRef.Context.hasSameType(
1364 // FIXME(GH58571): Match template parameter list even for non-constrained
1365 // template heads. This currently ensures that the code prior to C++20 is
1366 // not newly broken.
1367 bool ConstraintsInTemplateHead =
1370 // C++ [namespace.udecl]p11:
1371 // The set of declarations named by a using-declarator that inhabits a
1372 // class C does not include member functions and member function
1373 // templates of a base class that "correspond" to (and thus would
1374 // conflict with) a declaration of a function or function template in
1375 // C.
1376 // Comparing return types is not required for the "correspond" check to
1377 // decide whether a member introduced by a shadow declaration is hidden.
1378 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1379 !SameTemplateParameterList)
1380 return true;
1381 if (!UseMemberUsingDeclRules &&
1382 (!SameTemplateParameterList || !SameReturnType))
1383 return true;
1384 }
1385
1386 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1387 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1388
1389 int OldParamsOffset = 0;
1390 int NewParamsOffset = 0;
1391
1392 // When determining if a method is an overload from a base class, act as if
1393 // the implicit object parameter are of the same type.
1394
1395 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1397 return Q;
1398
1399 // We do not allow overloading based off of '__restrict'.
1400 Q.removeRestrict();
1401
1402 // We may not have applied the implicit const for a constexpr member
1403 // function yet (because we haven't yet resolved whether this is a static
1404 // or non-static member function). Add it now, on the assumption that this
1405 // is a redeclaration of OldMethod.
1406 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1407 (M->isConstexpr() || M->isConsteval()) &&
1408 !isa<CXXConstructorDecl>(NewMethod))
1409 Q.addConst();
1410 return Q;
1411 };
1412
1413 auto CompareType = [&](QualType Base, QualType D) {
1414 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1415 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1416
1417 auto DS = D.getNonReferenceType().getCanonicalType().split();
1418 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1419
1420 if (BS.Quals != DS.Quals)
1421 return false;
1422
1423 if (OldMethod->isImplicitObjectMemberFunction() &&
1424 OldMethod->getParent() != NewMethod->getParent()) {
1425 QualType ParentType =
1426 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1428 if (ParentType.getTypePtr() != BS.Ty)
1429 return false;
1430 BS.Ty = DS.Ty;
1431 }
1432
1433 // FIXME: should we ignore some type attributes here?
1434 if (BS.Ty != DS.Ty)
1435 return false;
1436
1437 if (Base->isLValueReferenceType())
1438 return D->isLValueReferenceType();
1439 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1440 };
1441
1442 // If the function is a class member, its signature includes the
1443 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1444 auto DiagnoseInconsistentRefQualifiers = [&]() {
1445 if (SemaRef.LangOpts.CPlusPlus23)
1446 return false;
1447 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1448 return false;
1449 if (OldMethod->isExplicitObjectMemberFunction() ||
1450 NewMethod->isExplicitObjectMemberFunction())
1451 return false;
1452 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1453 NewMethod->getRefQualifier() == RQ_None)) {
1454 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1455 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1456 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1457 return true;
1458 }
1459 return false;
1460 };
1461
1462 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1463 OldParamsOffset++;
1464 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1465 NewParamsOffset++;
1466
1467 if (OldType->getNumParams() - OldParamsOffset !=
1468 NewType->getNumParams() - NewParamsOffset ||
1470 {OldType->param_type_begin() + OldParamsOffset,
1471 OldType->param_type_end()},
1472 {NewType->param_type_begin() + NewParamsOffset,
1473 NewType->param_type_end()},
1474 nullptr)) {
1475 return true;
1476 }
1477
1478 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1479 !OldMethod->isStatic()) {
1480 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1481 const CXXMethodDecl *New) {
1482 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1483 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1484
1485 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1486 return F->getRefQualifier() == RQ_None &&
1487 !F->isExplicitObjectMemberFunction();
1488 };
1489
1490 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1491 CompareType(OldObjectType.getNonReferenceType(),
1492 NewObjectType.getNonReferenceType()))
1493 return true;
1494 return CompareType(OldObjectType, NewObjectType);
1495 }(OldMethod, NewMethod);
1496
1497 if (!HaveCorrespondingObjectParameters) {
1498 if (DiagnoseInconsistentRefQualifiers())
1499 return true;
1500 // CWG2554
1501 // and, if at least one is an explicit object member function, ignoring
1502 // object parameters
1503 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1504 !OldMethod->isExplicitObjectMemberFunction()))
1505 return true;
1506 }
1507 }
1508
1509 if (!UseOverrideRules) {
1510 Expr *NewRC = New->getTrailingRequiresClause(),
1511 *OldRC = Old->getTrailingRequiresClause();
1512 if ((NewRC != nullptr) != (OldRC != nullptr))
1513 return true;
1514
1515 if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1516 return true;
1517 }
1518
1519 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1520 NewMethod->isImplicitObjectMemberFunction()) {
1521 if (DiagnoseInconsistentRefQualifiers())
1522 return true;
1523 }
1524
1525 // Though pass_object_size is placed on parameters and takes an argument, we
1526 // consider it to be a function-level modifier for the sake of function
1527 // identity. Either the function has one or more parameters with
1528 // pass_object_size or it doesn't.
1531 return true;
1532
1533 // enable_if attributes are an order-sensitive part of the signature.
1535 NewI = New->specific_attr_begin<EnableIfAttr>(),
1536 NewE = New->specific_attr_end<EnableIfAttr>(),
1537 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1538 OldE = Old->specific_attr_end<EnableIfAttr>();
1539 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1540 if (NewI == NewE || OldI == OldE)
1541 return true;
1542 llvm::FoldingSetNodeID NewID, OldID;
1543 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1544 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1545 if (NewID != OldID)
1546 return true;
1547 }
1548
1549 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1550 // Don't allow overloading of destructors. (In theory we could, but it
1551 // would be a giant change to clang.)
1552 if (!isa<CXXDestructorDecl>(New)) {
1553 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1554 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1555 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1556 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1557 "Unexpected invalid target.");
1558
1559 // Allow overloading of functions with same signature and different CUDA
1560 // target attributes.
1561 if (NewTarget != OldTarget)
1562 return true;
1563 }
1564 }
1565 }
1566
1567 // The signatures match; this is not an overload.
1568 return false;
1569}
1570
1572 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1573 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1574 ConsiderCudaAttrs);
1575}
1576
1578 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1579 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1580 /*UseMemberUsingDeclRules=*/false,
1581 /*ConsiderCudaAttrs=*/true,
1582 /*UseOverrideRules=*/true);
1583}
1584
1585/// Tries a user-defined conversion from From to ToType.
1586///
1587/// Produces an implicit conversion sequence for when a standard conversion
1588/// is not an option. See TryImplicitConversion for more information.
1591 bool SuppressUserConversions,
1592 AllowedExplicit AllowExplicit,
1593 bool InOverloadResolution,
1594 bool CStyle,
1595 bool AllowObjCWritebackConversion,
1596 bool AllowObjCConversionOnExplicit) {
1598
1599 if (SuppressUserConversions) {
1600 // We're not in the case above, so there is no conversion that
1601 // we can perform.
1603 return ICS;
1604 }
1605
1606 // Attempt user-defined conversion.
1607 OverloadCandidateSet Conversions(From->getExprLoc(),
1609 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1610 Conversions, AllowExplicit,
1611 AllowObjCConversionOnExplicit)) {
1612 case OR_Success:
1613 case OR_Deleted:
1614 ICS.setUserDefined();
1615 // C++ [over.ics.user]p4:
1616 // A conversion of an expression of class type to the same class
1617 // type is given Exact Match rank, and a conversion of an
1618 // expression of class type to a base class of that type is
1619 // given Conversion rank, in spite of the fact that a copy
1620 // constructor (i.e., a user-defined conversion function) is
1621 // called for those cases.
1622 if (CXXConstructorDecl *Constructor
1623 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1624 QualType FromCanon
1626 QualType ToCanon
1628 if (Constructor->isCopyConstructor() &&
1629 (FromCanon == ToCanon ||
1630 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1631 // Turn this into a "standard" conversion sequence, so that it
1632 // gets ranked with standard conversion sequences.
1634 ICS.setStandard();
1636 ICS.Standard.setFromType(From->getType());
1637 ICS.Standard.setAllToTypes(ToType);
1638 ICS.Standard.CopyConstructor = Constructor;
1639 ICS.Standard.FoundCopyConstructor = Found;
1640 if (ToCanon != FromCanon)
1642 }
1643 }
1644 break;
1645
1646 case OR_Ambiguous:
1647 ICS.setAmbiguous();
1648 ICS.Ambiguous.setFromType(From->getType());
1649 ICS.Ambiguous.setToType(ToType);
1650 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1651 Cand != Conversions.end(); ++Cand)
1652 if (Cand->Best)
1653 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1654 break;
1655
1656 // Fall through.
1659 break;
1660 }
1661
1662 return ICS;
1663}
1664
1665/// TryImplicitConversion - Attempt to perform an implicit conversion
1666/// from the given expression (Expr) to the given type (ToType). This
1667/// function returns an implicit conversion sequence that can be used
1668/// to perform the initialization. Given
1669///
1670/// void f(float f);
1671/// void g(int i) { f(i); }
1672///
1673/// this routine would produce an implicit conversion sequence to
1674/// describe the initialization of f from i, which will be a standard
1675/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1676/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1677//
1678/// Note that this routine only determines how the conversion can be
1679/// performed; it does not actually perform the conversion. As such,
1680/// it will not produce any diagnostics if no conversion is available,
1681/// but will instead return an implicit conversion sequence of kind
1682/// "BadConversion".
1683///
1684/// If @p SuppressUserConversions, then user-defined conversions are
1685/// not permitted.
1686/// If @p AllowExplicit, then explicit user-defined conversions are
1687/// permitted.
1688///
1689/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1690/// writeback conversion, which allows __autoreleasing id* parameters to
1691/// be initialized with __strong id* or __weak id* arguments.
1694 bool SuppressUserConversions,
1695 AllowedExplicit AllowExplicit,
1696 bool InOverloadResolution,
1697 bool CStyle,
1698 bool AllowObjCWritebackConversion,
1699 bool AllowObjCConversionOnExplicit) {
1701 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1702 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1703 ICS.setStandard();
1704 return ICS;
1705 }
1706
1707 if (!S.getLangOpts().CPlusPlus) {
1709 return ICS;
1710 }
1711
1712 // C++ [over.ics.user]p4:
1713 // A conversion of an expression of class type to the same class
1714 // type is given Exact Match rank, and a conversion of an
1715 // expression of class type to a base class of that type is
1716 // given Conversion rank, in spite of the fact that a copy/move
1717 // constructor (i.e., a user-defined conversion function) is
1718 // called for those cases.
1719 QualType FromType = From->getType();
1720 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1721 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1722 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1723 ICS.setStandard();
1725 ICS.Standard.setFromType(FromType);
1726 ICS.Standard.setAllToTypes(ToType);
1727
1728 // We don't actually check at this point whether there is a valid
1729 // copy/move constructor, since overloading just assumes that it
1730 // exists. When we actually perform initialization, we'll find the
1731 // appropriate constructor to copy the returned object, if needed.
1732 ICS.Standard.CopyConstructor = nullptr;
1733
1734 // Determine whether this is considered a derived-to-base conversion.
1735 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1737
1738 return ICS;
1739 }
1740
1741 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1742 AllowExplicit, InOverloadResolution, CStyle,
1743 AllowObjCWritebackConversion,
1744 AllowObjCConversionOnExplicit);
1745}
1746
1749 bool SuppressUserConversions,
1750 AllowedExplicit AllowExplicit,
1751 bool InOverloadResolution,
1752 bool CStyle,
1753 bool AllowObjCWritebackConversion) {
1754 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1755 AllowExplicit, InOverloadResolution, CStyle,
1756 AllowObjCWritebackConversion,
1757 /*AllowObjCConversionOnExplicit=*/false);
1758}
1759
1760/// PerformImplicitConversion - Perform an implicit conversion of the
1761/// expression From to the type ToType. Returns the
1762/// converted expression. Flavor is the kind of conversion we're
1763/// performing, used in the error message. If @p AllowExplicit,
1764/// explicit user-defined conversions are permitted.
1766 AssignmentAction Action,
1767 bool AllowExplicit) {
1768 if (checkPlaceholderForOverload(*this, From))
1769 return ExprError();
1770
1771 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1772 bool AllowObjCWritebackConversion
1773 = getLangOpts().ObjCAutoRefCount &&
1774 (Action == AA_Passing || Action == AA_Sending);
1775 if (getLangOpts().ObjC)
1776 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1777 From->getType(), From);
1779 *this, From, ToType,
1780 /*SuppressUserConversions=*/false,
1781 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1782 /*InOverloadResolution=*/false,
1783 /*CStyle=*/false, AllowObjCWritebackConversion,
1784 /*AllowObjCConversionOnExplicit=*/false);
1785 return PerformImplicitConversion(From, ToType, ICS, Action);
1786}
1787
1788/// Determine whether the conversion from FromType to ToType is a valid
1789/// conversion that strips "noexcept" or "noreturn" off the nested function
1790/// type.
1792 QualType &ResultTy) {
1793 if (Context.hasSameUnqualifiedType(FromType, ToType))
1794 return false;
1795
1796 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1797 // or F(t noexcept) -> F(t)
1798 // where F adds one of the following at most once:
1799 // - a pointer
1800 // - a member pointer
1801 // - a block pointer
1802 // Changes here need matching changes in FindCompositePointerType.
1803 CanQualType CanTo = Context.getCanonicalType(ToType);
1804 CanQualType CanFrom = Context.getCanonicalType(FromType);
1805 Type::TypeClass TyClass = CanTo->getTypeClass();
1806 if (TyClass != CanFrom->getTypeClass()) return false;
1807 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1808 if (TyClass == Type::Pointer) {
1809 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1810 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1811 } else if (TyClass == Type::BlockPointer) {
1812 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1813 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1814 } else if (TyClass == Type::MemberPointer) {
1815 auto ToMPT = CanTo.castAs<MemberPointerType>();
1816 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1817 // A function pointer conversion cannot change the class of the function.
1818 if (ToMPT->getClass() != FromMPT->getClass())
1819 return false;
1820 CanTo = ToMPT->getPointeeType();
1821 CanFrom = FromMPT->getPointeeType();
1822 } else {
1823 return false;
1824 }
1825
1826 TyClass = CanTo->getTypeClass();
1827 if (TyClass != CanFrom->getTypeClass()) return false;
1828 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1829 return false;
1830 }
1831
1832 const auto *FromFn = cast<FunctionType>(CanFrom);
1833 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1834
1835 const auto *ToFn = cast<FunctionType>(CanTo);
1836 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1837
1838 bool Changed = false;
1839
1840 // Drop 'noreturn' if not present in target type.
1841 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1842 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1843 Changed = true;
1844 }
1845
1846 // Drop 'noexcept' if not present in target type.
1847 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1848 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1849 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1850 FromFn = cast<FunctionType>(
1851 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1852 EST_None)
1853 .getTypePtr());
1854 Changed = true;
1855 }
1856
1857 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1858 // only if the ExtParameterInfo lists of the two function prototypes can be
1859 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1861 bool CanUseToFPT, CanUseFromFPT;
1862 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1863 CanUseFromFPT, NewParamInfos) &&
1864 CanUseToFPT && !CanUseFromFPT) {
1865 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1866 ExtInfo.ExtParameterInfos =
1867 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1868 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1869 FromFPT->getParamTypes(), ExtInfo);
1870 FromFn = QT->getAs<FunctionType>();
1871 Changed = true;
1872 }
1873 }
1874
1875 if (!Changed)
1876 return false;
1877
1878 assert(QualType(FromFn, 0).isCanonical());
1879 if (QualType(FromFn, 0) != CanTo) return false;
1880
1881 ResultTy = ToType;
1882 return true;
1883}
1884
1885/// Determine whether the conversion from FromType to ToType is a valid
1886/// floating point conversion.
1887///
1888static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1889 QualType ToType) {
1890 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1891 return false;
1892 // FIXME: disable conversions between long double, __ibm128 and __float128
1893 // if their representation is different until there is back end support
1894 // We of course allow this conversion if long double is really double.
1895
1896 // Conversions between bfloat16 and float16 are currently not supported.
1897 if ((FromType->isBFloat16Type() &&
1898 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1899 (ToType->isBFloat16Type() &&
1900 (FromType->isFloat16Type() || FromType->isHalfType())))
1901 return false;
1902
1903 // Conversions between IEEE-quad and IBM-extended semantics are not
1904 // permitted.
1905 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1906 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1907 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1908 &ToSem == &llvm::APFloat::IEEEquad()) ||
1909 (&FromSem == &llvm::APFloat::IEEEquad() &&
1910 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1911 return false;
1912 return true;
1913}
1914
1915static bool IsVectorElementConversion(Sema &S, QualType FromType,
1916 QualType ToType,
1917 ImplicitConversionKind &ICK, Expr *From) {
1918 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1919 return true;
1920
1921 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1923 return true;
1924 }
1925
1926 if (IsFloatingPointConversion(S, FromType, ToType)) {
1928 return true;
1929 }
1930
1931 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1933 return true;
1934 }
1935
1936 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1938 ToType->isRealFloatingType())) {
1940 return true;
1941 }
1942
1943 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1945 return true;
1946 }
1947
1948 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1949 ToType->isIntegralType(S.Context)) {
1951 return true;
1952 }
1953
1954 return false;
1955}
1956
1957/// Determine whether the conversion from FromType to ToType is a valid
1958/// vector conversion.
1959///
1960/// \param ICK Will be set to the vector conversion kind, if this is a vector
1961/// conversion.
1962static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1964 ImplicitConversionKind &ElConv, Expr *From,
1965 bool InOverloadResolution, bool CStyle) {
1966 // We need at least one of these types to be a vector type to have a vector
1967 // conversion.
1968 if (!ToType->isVectorType() && !FromType->isVectorType())
1969 return false;
1970
1971 // Identical types require no conversions.
1972 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1973 return false;
1974
1975 // There are no conversions between extended vector types, only identity.
1976 if (ToType->isExtVectorType()) {
1977 if (FromType->isExtVectorType()) {
1978 // HLSL allows implicit truncation of vector types.
1979 if (S.getLangOpts().HLSL) {
1980 unsigned FromElts = FromType->getAs<VectorType>()->getNumElements();
1981 unsigned ToElts = ToType->getAs<VectorType>()->getNumElements();
1982 if (FromElts < ToElts)
1983 return false;
1984 if (FromElts == ToElts)
1985 ICK = ICK_Identity;
1986 else
1988
1989 QualType FromElTy = FromType->getAs<VectorType>()->getElementType();
1990 QualType ToElTy = ToType->getAs<VectorType>()->getElementType();
1991 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
1992 return true;
1993 return IsVectorElementConversion(S, FromElTy, ToElTy, ElConv, From);
1994 }
1995 // There are no conversions between extended vector types other than the
1996 // identity conversion.
1997 return false;
1998 }
1999
2000 // Vector splat from any arithmetic type to a vector.
2001 if (FromType->isArithmeticType()) {
2002 ICK = ICK_Vector_Splat;
2003 return true;
2004 }
2005 }
2006
2007 if (ToType->isSVESizelessBuiltinType() ||
2008 FromType->isSVESizelessBuiltinType())
2009 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2010 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2012 return true;
2013 }
2014
2015 if (ToType->isRVVSizelessBuiltinType() ||
2016 FromType->isRVVSizelessBuiltinType())
2017 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2018 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2020 return true;
2021 }
2022
2023 // We can perform the conversion between vector types in the following cases:
2024 // 1)vector types are equivalent AltiVec and GCC vector types
2025 // 2)lax vector conversions are permitted and the vector types are of the
2026 // same size
2027 // 3)the destination type does not have the ARM MVE strict-polymorphism
2028 // attribute, which inhibits lax vector conversion for overload resolution
2029 // only
2030 if (ToType->isVectorType() && FromType->isVectorType()) {
2031 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2032 (S.isLaxVectorConversion(FromType, ToType) &&
2033 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2034 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2035 S.isLaxVectorConversion(FromType, ToType) &&
2036 S.anyAltivecTypes(FromType, ToType) &&
2037 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2038 !InOverloadResolution && !CStyle) {
2039 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2040 << FromType << ToType;
2041 }
2043 return true;
2044 }
2045 }
2046
2047 return false;
2048}
2049
2050static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2051 bool InOverloadResolution,
2053 bool CStyle);
2054
2055/// IsStandardConversion - Determines whether there is a standard
2056/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2057/// expression From to the type ToType. Standard conversion sequences
2058/// only consider non-class types; for conversions that involve class
2059/// types, use TryImplicitConversion. If a conversion exists, SCS will
2060/// contain the standard conversion sequence required to perform this
2061/// conversion and this routine will return true. Otherwise, this
2062/// routine will return false and the value of SCS is unspecified.
2063static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2064 bool InOverloadResolution,
2066 bool CStyle,
2067 bool AllowObjCWritebackConversion) {
2068 QualType FromType = From->getType();
2069
2070 // Standard conversions (C++ [conv])
2072 SCS.IncompatibleObjC = false;
2073 SCS.setFromType(FromType);
2074 SCS.CopyConstructor = nullptr;
2075
2076 // There are no standard conversions for class types in C++, so
2077 // abort early. When overloading in C, however, we do permit them.
2078 if (S.getLangOpts().CPlusPlus &&
2079 (FromType->isRecordType() || ToType->isRecordType()))
2080 return false;
2081
2082 // The first conversion can be an lvalue-to-rvalue conversion,
2083 // array-to-pointer conversion, or function-to-pointer conversion
2084 // (C++ 4p1).
2085
2086 if (FromType == S.Context.OverloadTy) {
2087 DeclAccessPair AccessPair;
2088 if (FunctionDecl *Fn
2089 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2090 AccessPair)) {
2091 // We were able to resolve the address of the overloaded function,
2092 // so we can convert to the type of that function.
2093 FromType = Fn->getType();
2094 SCS.setFromType(FromType);
2095
2096 // we can sometimes resolve &foo<int> regardless of ToType, so check
2097 // if the type matches (identity) or we are converting to bool
2099 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2100 QualType resultTy;
2101 // if the function type matches except for [[noreturn]], it's ok
2102 if (!S.IsFunctionConversion(FromType,
2103 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2104 // otherwise, only a boolean conversion is standard
2105 if (!ToType->isBooleanType())
2106 return false;
2107 }
2108
2109 // Check if the "from" expression is taking the address of an overloaded
2110 // function and recompute the FromType accordingly. Take advantage of the
2111 // fact that non-static member functions *must* have such an address-of
2112 // expression.
2113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2114 if (Method && !Method->isStatic() &&
2115 !Method->isExplicitObjectMemberFunction()) {
2116 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2117 "Non-unary operator on non-static member address");
2118 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2119 == UO_AddrOf &&
2120 "Non-address-of operator on non-static member address");
2121 const Type *ClassType
2123 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2124 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2125 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2126 UO_AddrOf &&
2127 "Non-address-of operator for overloaded function expression");
2128 FromType = S.Context.getPointerType(FromType);
2129 }
2130 } else {
2131 return false;
2132 }
2133 }
2134 // Lvalue-to-rvalue conversion (C++11 4.1):
2135 // A glvalue (3.10) of a non-function, non-array type T can
2136 // be converted to a prvalue.
2137 bool argIsLValue = From->isGLValue();
2138 if (argIsLValue && !FromType->canDecayToPointerType() &&
2139 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2141
2142 // C11 6.3.2.1p2:
2143 // ... if the lvalue has atomic type, the value has the non-atomic version
2144 // of the type of the lvalue ...
2145 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2146 FromType = Atomic->getValueType();
2147
2148 // If T is a non-class type, the type of the rvalue is the
2149 // cv-unqualified version of T. Otherwise, the type of the rvalue
2150 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2151 // just strip the qualifiers because they don't matter.
2152 FromType = FromType.getUnqualifiedType();
2153 } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2154 ToType->isArrayParameterType()) {
2155 // HLSL constant array parameters do not decay, so if the argument is a
2156 // constant array and the parameter is an ArrayParameterType we have special
2157 // handling here.
2158 FromType = S.Context.getArrayParameterType(FromType);
2159 if (S.Context.getCanonicalType(FromType) !=
2160 S.Context.getCanonicalType(ToType))
2161 return false;
2162
2164 SCS.setAllToTypes(ToType);
2165 return true;
2166 } else if (FromType->isArrayType()) {
2167 // Array-to-pointer conversion (C++ 4.2)
2169
2170 // An lvalue or rvalue of type "array of N T" or "array of unknown
2171 // bound of T" can be converted to an rvalue of type "pointer to
2172 // T" (C++ 4.2p1).
2173 FromType = S.Context.getArrayDecayedType(FromType);
2174
2175 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2176 // This conversion is deprecated in C++03 (D.4)
2178
2179 // For the purpose of ranking in overload resolution
2180 // (13.3.3.1.1), this conversion is considered an
2181 // array-to-pointer conversion followed by a qualification
2182 // conversion (4.4). (C++ 4.2p2)
2183 SCS.Second = ICK_Identity;
2186 SCS.setAllToTypes(FromType);
2187 return true;
2188 }
2189 } else if (FromType->isFunctionType() && argIsLValue) {
2190 // Function-to-pointer conversion (C++ 4.3).
2192
2193 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2194 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2196 return false;
2197
2198 // An lvalue of function type T can be converted to an rvalue of
2199 // type "pointer to T." The result is a pointer to the
2200 // function. (C++ 4.3p1).
2201 FromType = S.Context.getPointerType(FromType);
2202 } else {
2203 // We don't require any conversions for the first step.
2204 SCS.First = ICK_Identity;
2205 }
2206 SCS.setToType(0, FromType);
2207
2208 // The second conversion can be an integral promotion, floating
2209 // point promotion, integral conversion, floating point conversion,
2210 // floating-integral conversion, pointer conversion,
2211 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2212 // For overloading in C, this can also be a "compatible-type"
2213 // conversion.
2214 bool IncompatibleObjC = false;
2217 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2218 // The unqualified versions of the types are the same: there's no
2219 // conversion to do.
2220 SCS.Second = ICK_Identity;
2221 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2222 // Integral promotion (C++ 4.5).
2224 FromType = ToType.getUnqualifiedType();
2225 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2226 // Floating point promotion (C++ 4.6).
2228 FromType = ToType.getUnqualifiedType();
2229 } else if (S.IsComplexPromotion(FromType, ToType)) {
2230 // Complex promotion (Clang extension)
2232 FromType = ToType.getUnqualifiedType();
2233 } else if (ToType->isBooleanType() &&
2234 (FromType->isArithmeticType() ||
2235 FromType->isAnyPointerType() ||
2236 FromType->isBlockPointerType() ||
2237 FromType->isMemberPointerType())) {
2238 // Boolean conversions (C++ 4.12).
2240 FromType = S.Context.BoolTy;
2241 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2242 ToType->isIntegralType(S.Context)) {
2243 // Integral conversions (C++ 4.7).
2245 FromType = ToType.getUnqualifiedType();
2246 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2247 // Complex conversions (C99 6.3.1.6)
2249 FromType = ToType.getUnqualifiedType();
2250 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2251 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2252 // Complex-real conversions (C99 6.3.1.7)
2254 FromType = ToType.getUnqualifiedType();
2255 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2256 // Floating point conversions (C++ 4.8).
2258 FromType = ToType.getUnqualifiedType();
2259 } else if ((FromType->isRealFloatingType() &&
2260 ToType->isIntegralType(S.Context)) ||
2262 ToType->isRealFloatingType())) {
2263
2264 // Floating-integral conversions (C++ 4.9).
2266 FromType = ToType.getUnqualifiedType();
2267 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2269 } else if (AllowObjCWritebackConversion &&
2270 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2272 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2273 FromType, IncompatibleObjC)) {
2274 // Pointer conversions (C++ 4.10).
2276 SCS.IncompatibleObjC = IncompatibleObjC;
2277 FromType = FromType.getUnqualifiedType();
2278 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2279 InOverloadResolution, FromType)) {
2280 // Pointer to member conversions (4.11).
2282 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, ElementICK,
2283 From, InOverloadResolution, CStyle)) {
2284 SCS.Second = SecondICK;
2285 SCS.Element = ElementICK;
2286 FromType = ToType.getUnqualifiedType();
2287 } else if (!S.getLangOpts().CPlusPlus &&
2288 S.Context.typesAreCompatible(ToType, FromType)) {
2289 // Compatible conversions (Clang extension for C function overloading)
2291 FromType = ToType.getUnqualifiedType();
2293 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2295 FromType = ToType;
2296 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2297 CStyle)) {
2298 // tryAtomicConversion has updated the standard conversion sequence
2299 // appropriately.
2300 return true;
2301 } else if (ToType->isEventT() &&
2303 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2305 FromType = ToType;
2306 } else if (ToType->isQueueT() &&
2308 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2310 FromType = ToType;
2311 } else if (ToType->isSamplerT() &&
2314 FromType = ToType;
2315 } else if ((ToType->isFixedPointType() &&
2316 FromType->isConvertibleToFixedPointType()) ||
2317 (FromType->isFixedPointType() &&
2318 ToType->isConvertibleToFixedPointType())) {
2320 FromType = ToType;
2321 } else {
2322 // No second conversion required.
2323 SCS.Second = ICK_Identity;
2324 }
2325 SCS.setToType(1, FromType);
2326
2327 // The third conversion can be a function pointer conversion or a
2328 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2329 bool ObjCLifetimeConversion;
2330 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2331 // Function pointer conversions (removing 'noexcept') including removal of
2332 // 'noreturn' (Clang extension).
2334 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2335 ObjCLifetimeConversion)) {
2337 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2338 FromType = ToType;
2339 } else {
2340 // No conversion required
2341 SCS.Third = ICK_Identity;
2342 }
2343
2344 // C++ [over.best.ics]p6:
2345 // [...] Any difference in top-level cv-qualification is
2346 // subsumed by the initialization itself and does not constitute
2347 // a conversion. [...]
2348 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2349 QualType CanonTo = S.Context.getCanonicalType(ToType);
2350 if (CanonFrom.getLocalUnqualifiedType()
2351 == CanonTo.getLocalUnqualifiedType() &&
2352 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2353 FromType = ToType;
2354 CanonFrom = CanonTo;
2355 }
2356
2357 SCS.setToType(2, FromType);
2358
2359 if (CanonFrom == CanonTo)
2360 return true;
2361
2362 // If we have not converted the argument type to the parameter type,
2363 // this is a bad conversion sequence, unless we're resolving an overload in C.
2364 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2365 return false;
2366
2367 ExprResult ER = ExprResult{From};
2370 /*Diagnose=*/false,
2371 /*DiagnoseCFAudited=*/false,
2372 /*ConvertRHS=*/false);
2373 ImplicitConversionKind SecondConv;
2374 switch (Conv) {
2375 case Sema::Compatible:
2376 SecondConv = ICK_C_Only_Conversion;
2377 break;
2378 // For our purposes, discarding qualifiers is just as bad as using an
2379 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2380 // qualifiers, as well.
2385 break;
2386 default:
2387 return false;
2388 }
2389
2390 // First can only be an lvalue conversion, so we pretend that this was the
2391 // second conversion. First should already be valid from earlier in the
2392 // function.
2393 SCS.Second = SecondConv;
2394 SCS.setToType(1, ToType);
2395
2396 // Third is Identity, because Second should rank us worse than any other
2397 // conversion. This could also be ICK_Qualification, but it's simpler to just
2398 // lump everything in with the second conversion, and we don't gain anything
2399 // from making this ICK_Qualification.
2400 SCS.Third = ICK_Identity;
2401 SCS.setToType(2, ToType);
2402 return true;
2403}
2404
2405static bool
2407 QualType &ToType,
2408 bool InOverloadResolution,
2410 bool CStyle) {
2411
2412 const RecordType *UT = ToType->getAsUnionType();
2413 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2414 return false;
2415 // The field to initialize within the transparent union.
2416 RecordDecl *UD = UT->getDecl();
2417 // It's compatible if the expression matches any of the fields.
2418 for (const auto *it : UD->fields()) {
2419 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2420 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2421 ToType = it->getType();
2422 return true;
2423 }
2424 }
2425 return false;
2426}
2427
2428/// IsIntegralPromotion - Determines whether the conversion from the
2429/// expression From (whose potentially-adjusted type is FromType) to
2430/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2431/// sets PromotedType to the promoted type.
2432bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2433 const BuiltinType *To = ToType->getAs<BuiltinType>();
2434 // All integers are built-in.
2435 if (!To) {
2436 return false;
2437 }
2438
2439 // An rvalue of type char, signed char, unsigned char, short int, or
2440 // unsigned short int can be converted to an rvalue of type int if
2441 // int can represent all the values of the source type; otherwise,
2442 // the source rvalue can be converted to an rvalue of type unsigned
2443 // int (C++ 4.5p1).
2444 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2445 !FromType->isEnumeralType()) {
2446 if ( // We can promote any signed, promotable integer type to an int
2447 (FromType->isSignedIntegerType() ||
2448 // We can promote any unsigned integer type whose size is
2449 // less than int to an int.
2450 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2451 return To->getKind() == BuiltinType::Int;
2452 }
2453
2454 return To->getKind() == BuiltinType::UInt;
2455 }
2456
2457 // C++11 [conv.prom]p3:
2458 // A prvalue of an unscoped enumeration type whose underlying type is not
2459 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2460 // following types that can represent all the values of the enumeration
2461 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2462 // unsigned int, long int, unsigned long int, long long int, or unsigned
2463 // long long int. If none of the types in that list can represent all the
2464 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2465 // type can be converted to an rvalue a prvalue of the extended integer type
2466 // with lowest integer conversion rank (4.13) greater than the rank of long
2467 // long in which all the values of the enumeration can be represented. If
2468 // there are two such extended types, the signed one is chosen.
2469 // C++11 [conv.prom]p4:
2470 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2471 // can be converted to a prvalue of its underlying type. Moreover, if
2472 // integral promotion can be applied to its underlying type, a prvalue of an
2473 // unscoped enumeration type whose underlying type is fixed can also be
2474 // converted to a prvalue of the promoted underlying type.
2475 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2476 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2477 // provided for a scoped enumeration.
2478 if (FromEnumType->getDecl()->isScoped())
2479 return false;
2480
2481 // We can perform an integral promotion to the underlying type of the enum,
2482 // even if that's not the promoted type. Note that the check for promoting
2483 // the underlying type is based on the type alone, and does not consider
2484 // the bitfield-ness of the actual source expression.
2485 if (FromEnumType->getDecl()->isFixed()) {
2486 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2487 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2488 IsIntegralPromotion(nullptr, Underlying, ToType);
2489 }
2490
2491 // We have already pre-calculated the promotion type, so this is trivial.
2492 if (ToType->isIntegerType() &&
2493 isCompleteType(From->getBeginLoc(), FromType))
2494 return Context.hasSameUnqualifiedType(
2495 ToType, FromEnumType->getDecl()->getPromotionType());
2496
2497 // C++ [conv.prom]p5:
2498 // If the bit-field has an enumerated type, it is treated as any other
2499 // value of that type for promotion purposes.
2500 //
2501 // ... so do not fall through into the bit-field checks below in C++.
2502 if (getLangOpts().CPlusPlus)
2503 return false;
2504 }
2505
2506 // C++0x [conv.prom]p2:
2507 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2508 // to an rvalue a prvalue of the first of the following types that can
2509 // represent all the values of its underlying type: int, unsigned int,
2510 // long int, unsigned long int, long long int, or unsigned long long int.
2511 // If none of the types in that list can represent all the values of its
2512 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2513 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2514 // type.
2515 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2516 ToType->isIntegerType()) {
2517 // Determine whether the type we're converting from is signed or
2518 // unsigned.
2519 bool FromIsSigned = FromType->isSignedIntegerType();
2520 uint64_t FromSize = Context.getTypeSize(FromType);
2521
2522 // The types we'll try to promote to, in the appropriate
2523 // order. Try each of these types.
2524 QualType PromoteTypes[6] = {
2525 Context.IntTy, Context.UnsignedIntTy,
2526 Context.LongTy, Context.UnsignedLongTy ,
2527 Context.LongLongTy, Context.UnsignedLongLongTy
2528 };
2529 for (int Idx = 0; Idx < 6; ++Idx) {
2530 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2531 if (FromSize < ToSize ||
2532 (FromSize == ToSize &&
2533 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2534 // We found the type that we can promote to. If this is the
2535 // type we wanted, we have a promotion. Otherwise, no
2536 // promotion.
2537 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2538 }
2539 }
2540 }
2541
2542 // An rvalue for an integral bit-field (9.6) can be converted to an
2543 // rvalue of type int if int can represent all the values of the
2544 // bit-field; otherwise, it can be converted to unsigned int if
2545 // unsigned int can represent all the values of the bit-field. If
2546 // the bit-field is larger yet, no integral promotion applies to
2547 // it. If the bit-field has an enumerated type, it is treated as any
2548 // other value of that type for promotion purposes (C++ 4.5p3).
2549 // FIXME: We should delay checking of bit-fields until we actually perform the
2550 // conversion.
2551 //
2552 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2553 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2554 // bit-fields and those whose underlying type is larger than int) for GCC
2555 // compatibility.
2556 if (From) {
2557 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2558 std::optional<llvm::APSInt> BitWidth;
2559 if (FromType->isIntegralType(Context) &&
2560 (BitWidth =
2561 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2562 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2563 ToSize = Context.getTypeSize(ToType);
2564
2565 // Are we promoting to an int from a bitfield that fits in an int?
2566 if (*BitWidth < ToSize ||
2567 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2568 return To->getKind() == BuiltinType::Int;
2569 }
2570
2571 // Are we promoting to an unsigned int from an unsigned bitfield
2572 // that fits into an unsigned int?
2573 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2574 return To->getKind() == BuiltinType::UInt;
2575 }
2576
2577 return false;
2578 }
2579 }
2580 }
2581
2582 // An rvalue of type bool can be converted to an rvalue of type int,
2583 // with false becoming zero and true becoming one (C++ 4.5p4).
2584 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2585 return true;
2586 }
2587
2588 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2589 // integral type.
2590 if (Context.getLangOpts().HLSL)
2591 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2592
2593 return false;
2594}
2595
2596/// IsFloatingPointPromotion - Determines whether the conversion from
2597/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2598/// returns true and sets PromotedType to the promoted type.
2600 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2601 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2602 /// An rvalue of type float can be converted to an rvalue of type
2603 /// double. (C++ 4.6p1).
2604 if (FromBuiltin->getKind() == BuiltinType::Float &&
2605 ToBuiltin->getKind() == BuiltinType::Double)
2606 return true;
2607
2608 // C99 6.3.1.5p1:
2609 // When a float is promoted to double or long double, or a
2610 // double is promoted to long double [...].
2611 if (!getLangOpts().CPlusPlus &&
2612 (FromBuiltin->getKind() == BuiltinType::Float ||
2613 FromBuiltin->getKind() == BuiltinType::Double) &&
2614 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2615 ToBuiltin->getKind() == BuiltinType::Float128 ||
2616 ToBuiltin->getKind() == BuiltinType::Ibm128))
2617 return true;
2618
2619 // Half can be promoted to float.
2620 if (!getLangOpts().NativeHalfType &&
2621 FromBuiltin->getKind() == BuiltinType::Half &&
2622 ToBuiltin->getKind() == BuiltinType::Float)
2623 return true;
2624 }
2625
2626 return false;
2627}
2628
2629/// Determine if a conversion is a complex promotion.
2630///
2631/// A complex promotion is defined as a complex -> complex conversion
2632/// where the conversion between the underlying real types is a
2633/// floating-point or integral promotion.
2635 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2636 if (!FromComplex)
2637 return false;
2638
2639 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2640 if (!ToComplex)
2641 return false;
2642
2643 return IsFloatingPointPromotion(FromComplex->getElementType(),
2644 ToComplex->getElementType()) ||
2645 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2646 ToComplex->getElementType());
2647}
2648
2649/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2650/// the pointer type FromPtr to a pointer to type ToPointee, with the
2651/// same type qualifiers as FromPtr has on its pointee type. ToType,
2652/// if non-empty, will be a pointer to ToType that may or may not have
2653/// the right set of qualifiers on its pointee.
2654///
2655static QualType
2657 QualType ToPointee, QualType ToType,
2658 ASTContext &Context,
2659 bool StripObjCLifetime = false) {
2660 assert((FromPtr->getTypeClass() == Type::Pointer ||
2661 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2662 "Invalid similarly-qualified pointer type");
2663
2664 /// Conversions to 'id' subsume cv-qualifier conversions.
2665 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2666 return ToType.getUnqualifiedType();
2667
2668 QualType CanonFromPointee
2669 = Context.getCanonicalType(FromPtr->getPointeeType());
2670 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2671 Qualifiers Quals = CanonFromPointee.getQualifiers();
2672
2673 if (StripObjCLifetime)
2674 Quals.removeObjCLifetime();
2675
2676 // Exact qualifier match -> return the pointer type we're converting to.
2677 if (CanonToPointee.getLocalQualifiers() == Quals) {
2678 // ToType is exactly what we need. Return it.
2679 if (!ToType.isNull())
2680 return ToType.getUnqualifiedType();
2681
2682 // Build a pointer to ToPointee. It has the right qualifiers
2683 // already.
2684 if (isa<ObjCObjectPointerType>(ToType))
2685 return Context.getObjCObjectPointerType(ToPointee);
2686 return Context.getPointerType(ToPointee);
2687 }
2688
2689 // Just build a canonical type that has the right qualifiers.
2690 QualType QualifiedCanonToPointee
2691 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2692
2693 if (isa<ObjCObjectPointerType>(ToType))
2694 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2695 return Context.getPointerType(QualifiedCanonToPointee);
2696}
2697
2699 bool InOverloadResolution,
2700 ASTContext &Context) {
2701 // Handle value-dependent integral null pointer constants correctly.
2702 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2703 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2705 return !InOverloadResolution;
2706
2707 return Expr->isNullPointerConstant(Context,
2708 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2710}
2711
2712/// IsPointerConversion - Determines whether the conversion of the
2713/// expression From, which has the (possibly adjusted) type FromType,
2714/// can be converted to the type ToType via a pointer conversion (C++
2715/// 4.10). If so, returns true and places the converted type (that
2716/// might differ from ToType in its cv-qualifiers at some level) into
2717/// ConvertedType.
2718///
2719/// This routine also supports conversions to and from block pointers
2720/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2721/// pointers to interfaces. FIXME: Once we've determined the
2722/// appropriate overloading rules for Objective-C, we may want to
2723/// split the Objective-C checks into a different routine; however,
2724/// GCC seems to consider all of these conversions to be pointer
2725/// conversions, so for now they live here. IncompatibleObjC will be
2726/// set if the conversion is an allowed Objective-C conversion that
2727/// should result in a warning.
2729 bool InOverloadResolution,
2730 QualType& ConvertedType,
2731 bool &IncompatibleObjC) {
2732 IncompatibleObjC = false;
2733 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2734 IncompatibleObjC))
2735 return true;
2736
2737 // Conversion from a null pointer constant to any Objective-C pointer type.
2738 if (ToType->isObjCObjectPointerType() &&
2739 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2740 ConvertedType = ToType;
2741 return true;
2742 }
2743
2744 // Blocks: Block pointers can be converted to void*.
2745 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2746 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2747 ConvertedType = ToType;
2748 return true;
2749 }
2750 // Blocks: A null pointer constant can be converted to a block
2751 // pointer type.
2752 if (ToType->isBlockPointerType() &&
2753 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2754 ConvertedType = ToType;
2755 return true;
2756 }
2757
2758 // If the left-hand-side is nullptr_t, the right side can be a null
2759 // pointer constant.
2760 if (ToType->isNullPtrType() &&
2761 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2762 ConvertedType = ToType;
2763 return true;
2764 }
2765
2766 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2767 if (!ToTypePtr)
2768 return false;
2769
2770 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2771 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2772 ConvertedType = ToType;
2773 return true;
2774 }
2775
2776 // Beyond this point, both types need to be pointers
2777 // , including objective-c pointers.
2778 QualType ToPointeeType = ToTypePtr->getPointeeType();
2779 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2780 !getLangOpts().ObjCAutoRefCount) {
2781 ConvertedType = BuildSimilarlyQualifiedPointerType(
2782 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2783 Context);
2784 return true;
2785 }
2786 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2787 if (!FromTypePtr)
2788 return false;
2789
2790 QualType FromPointeeType = FromTypePtr->getPointeeType();
2791
2792 // If the unqualified pointee types are the same, this can't be a
2793 // pointer conversion, so don't do all of the work below.
2794 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2795 return false;
2796
2797 // An rvalue of type "pointer to cv T," where T is an object type,
2798 // can be converted to an rvalue of type "pointer to cv void" (C++
2799 // 4.10p2).
2800 if (FromPointeeType->isIncompleteOrObjectType() &&
2801 ToPointeeType->isVoidType()) {
2802 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2803 ToPointeeType,
2804 ToType, Context,
2805 /*StripObjCLifetime=*/true);
2806 return true;
2807 }
2808
2809 // MSVC allows implicit function to void* type conversion.
2810 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2811 ToPointeeType->isVoidType()) {
2812 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2813 ToPointeeType,
2814 ToType, Context);
2815 return true;
2816 }
2817
2818 // When we're overloading in C, we allow a special kind of pointer
2819 // conversion for compatible-but-not-identical pointee types.
2820 if (!getLangOpts().CPlusPlus &&
2821 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2822 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2823 ToPointeeType,
2824 ToType, Context);
2825 return true;
2826 }
2827
2828 // C++ [conv.ptr]p3:
2829 //
2830 // An rvalue of type "pointer to cv D," where D is a class type,
2831 // can be converted to an rvalue of type "pointer to cv B," where
2832 // B is a base class (clause 10) of D. If B is an inaccessible
2833 // (clause 11) or ambiguous (10.2) base class of D, a program that
2834 // necessitates this conversion is ill-formed. The result of the
2835 // conversion is a pointer to the base class sub-object of the
2836 // derived class object. The null pointer value is converted to
2837 // the null pointer value of the destination type.
2838 //
2839 // Note that we do not check for ambiguity or inaccessibility
2840 // here. That is handled by CheckPointerConversion.
2841 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2842 ToPointeeType->isRecordType() &&
2843 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2844 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2845 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2846 ToPointeeType,
2847 ToType, Context);
2848 return true;
2849 }
2850
2851 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2852 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2853 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2854 ToPointeeType,
2855 ToType, Context);
2856 return true;
2857 }
2858
2859 return false;
2860}
2861
2862/// Adopt the given qualifiers for the given type.
2864 Qualifiers TQs = T.getQualifiers();
2865
2866 // Check whether qualifiers already match.
2867 if (TQs == Qs)
2868 return T;
2869
2870 if (Qs.compatiblyIncludes(TQs))
2871 return Context.getQualifiedType(T, Qs);
2872
2873 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2874}
2875
2876/// isObjCPointerConversion - Determines whether this is an
2877/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2878/// with the same arguments and return values.
2880 QualType& ConvertedType,
2881 bool &IncompatibleObjC) {
2882 if (!getLangOpts().ObjC)
2883 return false;
2884
2885 // The set of qualifiers on the type we're converting from.
2886 Qualifiers FromQualifiers = FromType.getQualifiers();
2887
2888 // First, we handle all conversions on ObjC object pointer types.
2889 const ObjCObjectPointerType* ToObjCPtr =
2890 ToType->getAs<ObjCObjectPointerType>();
2891 const ObjCObjectPointerType *FromObjCPtr =
2892 FromType->getAs<ObjCObjectPointerType>();
2893
2894 if (ToObjCPtr && FromObjCPtr) {
2895 // If the pointee types are the same (ignoring qualifications),
2896 // then this is not a pointer conversion.
2897 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2898 FromObjCPtr->getPointeeType()))
2899 return false;
2900
2901 // Conversion between Objective-C pointers.
2902 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2903 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2904 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2905 if (getLangOpts().CPlusPlus && LHS && RHS &&
2907 FromObjCPtr->getPointeeType()))
2908 return false;
2909 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2910 ToObjCPtr->getPointeeType(),
2911 ToType, Context);
2912 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2913 return true;
2914 }
2915
2916 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2917 // Okay: this is some kind of implicit downcast of Objective-C
2918 // interfaces, which is permitted. However, we're going to
2919 // complain about it.
2920 IncompatibleObjC = true;
2921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2922 ToObjCPtr->getPointeeType(),
2923 ToType, Context);
2924 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2925 return true;
2926 }
2927 }
2928 // Beyond this point, both types need to be C pointers or block pointers.
2929 QualType ToPointeeType;
2930 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2931 ToPointeeType = ToCPtr->getPointeeType();
2932 else if (const BlockPointerType *ToBlockPtr =
2933 ToType->getAs<BlockPointerType>()) {
2934 // Objective C++: We're able to convert from a pointer to any object
2935 // to a block pointer type.
2936 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2937 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2938 return true;
2939 }
2940 ToPointeeType = ToBlockPtr->getPointeeType();
2941 }
2942 else if (FromType->getAs<BlockPointerType>() &&
2943 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2944 // Objective C++: We're able to convert from a block pointer type to a
2945 // pointer to any object.
2946 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2947 return true;
2948 }
2949 else
2950 return false;
2951
2952 QualType FromPointeeType;
2953 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2954 FromPointeeType = FromCPtr->getPointeeType();
2955 else if (const BlockPointerType *FromBlockPtr =
2956 FromType->getAs<BlockPointerType>())
2957 FromPointeeType = FromBlockPtr->getPointeeType();
2958 else
2959 return false;
2960
2961 // If we have pointers to pointers, recursively check whether this
2962 // is an Objective-C conversion.
2963 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2964 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2965 IncompatibleObjC)) {
2966 // We always complain about this conversion.
2967 IncompatibleObjC = true;
2968 ConvertedType = Context.getPointerType(ConvertedType);
2969 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2970 return true;
2971 }
2972 // Allow conversion of pointee being objective-c pointer to another one;
2973 // as in I* to id.
2974 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2975 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2976 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2977 IncompatibleObjC)) {
2978
2979 ConvertedType = Context.getPointerType(ConvertedType);
2980 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2981 return true;
2982 }
2983
2984 // If we have pointers to functions or blocks, check whether the only
2985 // differences in the argument and result types are in Objective-C
2986 // pointer conversions. If so, we permit the conversion (but
2987 // complain about it).
2988 const FunctionProtoType *FromFunctionType
2989 = FromPointeeType->getAs<FunctionProtoType>();
2990 const FunctionProtoType *ToFunctionType
2991 = ToPointeeType->getAs<FunctionProtoType>();
2992 if (FromFunctionType && ToFunctionType) {
2993 // If the function types are exactly the same, this isn't an
2994 // Objective-C pointer conversion.
2995 if (Context.getCanonicalType(FromPointeeType)
2996 == Context.getCanonicalType(ToPointeeType))
2997 return false;
2998
2999 // Perform the quick checks that will tell us whether these
3000 // function types are obviously different.
3001 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3002 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3003 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3004 return false;
3005
3006 bool HasObjCConversion = false;
3007 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3008 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3009 // Okay, the types match exactly. Nothing to do.
3010 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3011 ToFunctionType->getReturnType(),
3012 ConvertedType, IncompatibleObjC)) {
3013 // Okay, we have an Objective-C pointer conversion.
3014 HasObjCConversion = true;
3015 } else {
3016 // Function types are too different. Abort.
3017 return false;
3018 }
3019
3020 // Check argument types.
3021 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3022 ArgIdx != NumArgs; ++ArgIdx) {
3023 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3024 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3025 if (Context.getCanonicalType(FromArgType)
3026 == Context.getCanonicalType(ToArgType)) {
3027 // Okay, the types match exactly. Nothing to do.
3028 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3029 ConvertedType, IncompatibleObjC)) {
3030 // Okay, we have an Objective-C pointer conversion.
3031 HasObjCConversion = true;
3032 } else {
3033 // Argument types are too different. Abort.
3034 return false;
3035 }
3036 }
3037
3038 if (HasObjCConversion) {
3039 // We had an Objective-C conversion. Allow this pointer
3040 // conversion, but complain about it.
3041 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3042 IncompatibleObjC = true;
3043 return true;
3044 }
3045 }
3046
3047 return false;
3048}
3049
3050/// Determine whether this is an Objective-C writeback conversion,
3051/// used for parameter passing when performing automatic reference counting.
3052///
3053/// \param FromType The type we're converting form.
3054///
3055/// \param ToType The type we're converting to.
3056///
3057/// \param ConvertedType The type that will be produced after applying
3058/// this conversion.
3060 QualType &ConvertedType) {
3061 if (!getLangOpts().ObjCAutoRefCount ||
3062 Context.hasSameUnqualifiedType(FromType, ToType))
3063 return false;
3064
3065 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
3066 QualType ToPointee;
3067 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
3068 ToPointee = ToPointer->getPointeeType();
3069 else
3070 return false;
3071
3072 Qualifiers ToQuals = ToPointee.getQualifiers();
3073 if (!ToPointee->isObjCLifetimeType() ||
3075 !ToQuals.withoutObjCLifetime().empty())
3076 return false;
3077
3078 // Argument must be a pointer to __strong to __weak.
3079 QualType FromPointee;
3080 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
3081 FromPointee = FromPointer->getPointeeType();
3082 else
3083 return false;
3084
3085 Qualifiers FromQuals = FromPointee.getQualifiers();
3086 if (!FromPointee->isObjCLifetimeType() ||
3087 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
3088 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
3089 return false;
3090
3091 // Make sure that we have compatible qualifiers.
3093 if (!ToQuals.compatiblyIncludes(FromQuals))
3094 return false;
3095
3096 // Remove qualifiers from the pointee type we're converting from; they
3097 // aren't used in the compatibility check belong, and we'll be adding back
3098 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
3099 FromPointee = FromPointee.getUnqualifiedType();
3100
3101 // The unqualified form of the pointee types must be compatible.
3102 ToPointee = ToPointee.getUnqualifiedType();
3103 bool IncompatibleObjC;
3104 if (Context.typesAreCompatible(FromPointee, ToPointee))
3105 FromPointee = ToPointee;
3106 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
3107 IncompatibleObjC))
3108 return false;
3109
3110 /// Construct the type we're converting to, which is a pointer to
3111 /// __autoreleasing pointee.
3112 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
3113 ConvertedType = Context.getPointerType(FromPointee);
3114 return true;
3115}
3116
3118 QualType& ConvertedType) {
3119 QualType ToPointeeType;
3120 if (const BlockPointerType *ToBlockPtr =
3121 ToType->getAs<BlockPointerType>())
3122 ToPointeeType = ToBlockPtr->getPointeeType();
3123 else
3124 return false;
3125
3126 QualType FromPointeeType;
3127 if (const BlockPointerType *FromBlockPtr =
3128 FromType->getAs<BlockPointerType>())
3129 FromPointeeType = FromBlockPtr->getPointeeType();
3130 else
3131 return false;
3132 // We have pointer to blocks, check whether the only
3133 // differences in the argument and result types are in Objective-C
3134 // pointer conversions. If so, we permit the conversion.
3135
3136 const FunctionProtoType *FromFunctionType
3137 = FromPointeeType->getAs<FunctionProtoType>();
3138 const FunctionProtoType *ToFunctionType
3139 = ToPointeeType->getAs<FunctionProtoType>();
3140
3141 if (!FromFunctionType || !ToFunctionType)
3142 return false;
3143
3144 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3145 return true;
3146
3147 // Perform the quick checks that will tell us whether these
3148 // function types are obviously different.
3149 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3150 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3151 return false;
3152
3153 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3154 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3155 if (FromEInfo != ToEInfo)
3156 return false;
3157
3158 bool IncompatibleObjC = false;
3159 if (Context.hasSameType(FromFunctionType->getReturnType(),
3160 ToFunctionType->getReturnType())) {
3161 // Okay, the types match exactly. Nothing to do.
3162 } else {
3163 QualType RHS = FromFunctionType->getReturnType();
3164 QualType LHS = ToFunctionType->getReturnType();
3165 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3166 !RHS.hasQualifiers() && LHS.hasQualifiers())
3167 LHS = LHS.getUnqualifiedType();
3168
3169 if (Context.hasSameType(RHS,LHS)) {
3170 // OK exact match.
3171 } else if (isObjCPointerConversion(RHS, LHS,
3172 ConvertedType, IncompatibleObjC)) {
3173 if (IncompatibleObjC)
3174 return false;
3175 // Okay, we have an Objective-C pointer conversion.
3176 }
3177 else
3178 return false;
3179 }
3180
3181 // Check argument types.
3182 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3183 ArgIdx != NumArgs; ++ArgIdx) {
3184 IncompatibleObjC = false;
3185 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3186 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3187 if (Context.hasSameType(FromArgType, ToArgType)) {
3188 // Okay, the types match exactly. Nothing to do.
3189 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3190 ConvertedType, IncompatibleObjC)) {
3191 if (IncompatibleObjC)
3192 return false;
3193 // Okay, we have an Objective-C pointer conversion.
3194 } else
3195 // Argument types are too different. Abort.
3196 return false;
3197 }
3198
3200 bool CanUseToFPT, CanUseFromFPT;
3201 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3202 CanUseToFPT, CanUseFromFPT,
3203 NewParamInfos))
3204 return false;
3205
3206 ConvertedType = ToType;
3207 return true;
3208}
3209
3210enum {
3219
3220/// Attempts to get the FunctionProtoType from a Type. Handles
3221/// MemberFunctionPointers properly.
3223 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3224 return FPT;
3225
3226 if (auto *MPT = FromType->getAs<MemberPointerType>())
3227 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3228
3229 return nullptr;
3230}
3231
3232/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3233/// function types. Catches different number of parameter, mismatch in
3234/// parameter types, and different return types.
3236 QualType FromType, QualType ToType) {
3237 // If either type is not valid, include no extra info.
3238 if (FromType.isNull() || ToType.isNull()) {
3239 PDiag << ft_default;
3240 return;
3241 }
3242
3243 // Get the function type from the pointers.
3244 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3245 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3246 *ToMember = ToType->castAs<MemberPointerType>();
3247 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3248 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3249 << QualType(FromMember->getClass(), 0);
3250 return;
3251 }
3252 FromType = FromMember->getPointeeType();
3253 ToType = ToMember->getPointeeType();
3254 }
3255
3256 if (FromType->isPointerType())
3257 FromType = FromType->getPointeeType();
3258 if (ToType->isPointerType())
3259 ToType = ToType->getPointeeType();
3260
3261 // Remove references.
3262 FromType = FromType.getNonReferenceType();
3263 ToType = ToType.getNonReferenceType();
3264
3265 // Don't print extra info for non-specialized template functions.
3266 if (FromType->isInstantiationDependentType() &&
3267 !FromType->getAs<TemplateSpecializationType>()) {
3268 PDiag << ft_default;
3269 return;
3270 }
3271
3272 // No extra info for same types.
3273 if (Context.hasSameType(FromType, ToType)) {
3274 PDiag << ft_default;
3275 return;
3276 }
3277
3278 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3279 *ToFunction = tryGetFunctionProtoType(ToType);
3280
3281 // Both types need to be function types.
3282 if (!FromFunction || !ToFunction) {
3283 PDiag << ft_default;
3284 return;
3285 }
3286
3287 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3288 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3289 << FromFunction->getNumParams();
3290 return;
3291 }
3292
3293 // Handle different parameter types.
3294 unsigned ArgPos;
3295 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3296 PDiag << ft_parameter_mismatch << ArgPos + 1
3297 << ToFunction->getParamType(ArgPos)
3298 << FromFunction->getParamType(ArgPos);
3299 return;
3300 }
3301
3302 // Handle different return type.
3303 if (!Context.hasSameType(FromFunction->getReturnType(),
3304 ToFunction->getReturnType())) {
3305 PDiag << ft_return_type << ToFunction->getReturnType()
3306 << FromFunction->getReturnType();
3307 return;
3308 }
3309
3310 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3311 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3312 << FromFunction->getMethodQuals();
3313 return;
3314 }
3315
3316 // Handle exception specification differences on canonical type (in C++17
3317 // onwards).
3318 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3319 ->isNothrow() !=
3320 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3321 ->isNothrow()) {
3322 PDiag << ft_noexcept;
3323 return;
3324 }
3325
3326 // Unable to find a difference, so add no extra info.
3327 PDiag << ft_default;
3328}
3329
3330/// FunctionParamTypesAreEqual - This routine checks two function proto types
3331/// for equality of their parameter types. Caller has already checked that
3332/// they have same number of parameters. If the parameters are different,
3333/// ArgPos will have the parameter index of the first different parameter.
3334/// If `Reversed` is true, the parameters of `NewType` will be compared in
3335/// reverse order. That's useful if one of the functions is being used as a C++20
3336/// synthesized operator overload with a reversed parameter order.
3338 ArrayRef<QualType> New, unsigned *ArgPos,
3339 bool Reversed) {
3340 assert(llvm::size(Old) == llvm::size(New) &&
3341 "Can't compare parameters of functions with different number of "
3342 "parameters!");
3343
3344 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3345 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3346 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3347
3348 // Ignore address spaces in pointee type. This is to disallow overloading
3349 // on __ptr32/__ptr64 address spaces.
3350 QualType OldType =
3351 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3352 QualType NewType =
3353 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3354
3355 if (!Context.hasSameType(OldType, NewType)) {
3356 if (ArgPos)
3357 *ArgPos = Idx;
3358 return false;
3359 }
3360 }
3361 return true;
3362}
3363
3365 const FunctionProtoType *NewType,
3366 unsigned *ArgPos, bool Reversed) {
3367 return FunctionParamTypesAreEqual(OldType->param_types(),
3368 NewType->param_types(), ArgPos, Reversed);
3369}
3370
3372 const FunctionDecl *NewFunction,
3373 unsigned *ArgPos,
3374 bool Reversed) {
3375
3376 if (OldFunction->getNumNonObjectParams() !=
3377 NewFunction->getNumNonObjectParams())
3378 return false;
3379
3380 unsigned OldIgnore =
3382 unsigned NewIgnore =
3384
3385 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3386 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3387
3388 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3389 NewPT->param_types().slice(NewIgnore),
3390 ArgPos, Reversed);
3391}
3392
3393/// CheckPointerConversion - Check the pointer conversion from the
3394/// expression From to the type ToType. This routine checks for
3395/// ambiguous or inaccessible derived-to-base pointer
3396/// conversions for which IsPointerConversion has already returned
3397/// true. It returns true and produces a diagnostic if there was an
3398/// error, or returns false otherwise.
3400 CastKind &Kind,
3401 CXXCastPath& BasePath,
3402 bool IgnoreBaseAccess,
3403 bool Diagnose) {
3404 QualType FromType = From->getType();
3405 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3406
3407 Kind = CK_BitCast;
3408
3409 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3412 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3413 DiagRuntimeBehavior(From->getExprLoc(), From,
3414 PDiag(diag::warn_impcast_bool_to_null_pointer)
3415 << ToType << From->getSourceRange());
3416 else if (!isUnevaluatedContext())
3417 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3418 << ToType << From->getSourceRange();
3419 }
3420 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3421 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3422 QualType FromPointeeType = FromPtrType->getPointeeType(),
3423 ToPointeeType = ToPtrType->getPointeeType();
3424
3425 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3426 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3427 // We must have a derived-to-base conversion. Check an
3428 // ambiguous or inaccessible conversion.
3429 unsigned InaccessibleID = 0;
3430 unsigned AmbiguousID = 0;
3431 if (Diagnose) {
3432 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3433 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3434 }
3435 if (CheckDerivedToBaseConversion(
3436 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3437 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3438 &BasePath, IgnoreBaseAccess))
3439 return true;
3440
3441 // The conversion was successful.
3442 Kind = CK_DerivedToBase;
3443 }
3444
3445 if (Diagnose && !IsCStyleOrFunctionalCast &&
3446 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3447 assert(getLangOpts().MSVCCompat &&
3448 "this should only be possible with MSVCCompat!");
3449 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3450 << From->getSourceRange();
3451 }
3452 }
3453 } else if (const ObjCObjectPointerType *ToPtrType =
3454 ToType->getAs<ObjCObjectPointerType>()) {
3455 if (const ObjCObjectPointerType *FromPtrType =
3456 FromType->getAs<ObjCObjectPointerType>()) {
3457 // Objective-C++ conversions are always okay.
3458 // FIXME: We should have a different class of conversions for the
3459 // Objective-C++ implicit conversions.
3460 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3461 return false;
3462 } else if (FromType->isBlockPointerType()) {
3463 Kind = CK_BlockPointerToObjCPointerCast;
3464 } else {
3465 Kind = CK_CPointerToObjCPointerCast;
3466 }
3467 } else if (ToType->isBlockPointerType()) {
3468 if (!FromType->isBlockPointerType())
3469 Kind = CK_AnyPointerToBlockPointerCast;
3470 }
3471
3472 // We shouldn't fall into this case unless it's valid for other
3473 // reasons.
3475 Kind = CK_NullToPointer;
3476
3477 return false;
3478}
3479
3480/// IsMemberPointerConversion - Determines whether the conversion of the
3481/// expression From, which has the (possibly adjusted) type FromType, can be
3482/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3483/// If so, returns true and places the converted type (that might differ from
3484/// ToType in its cv-qualifiers at some level) into ConvertedType.
3486 QualType ToType,
3487 bool InOverloadResolution,
3488 QualType &ConvertedType) {
3489 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3490 if (!ToTypePtr)
3491 return false;
3492
3493 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3494 if (From->isNullPointerConstant(Context,
3495 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3497 ConvertedType = ToType;
3498 return true;
3499 }
3500
3501 // Otherwise, both types have to be member pointers.
3502 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3503 if (!FromTypePtr)
3504 return false;
3505
3506 // A pointer to member of B can be converted to a pointer to member of D,
3507 // where D is derived from B (C++ 4.11p2).
3508 QualType FromClass(FromTypePtr->getClass(), 0);
3509 QualType ToClass(ToTypePtr->getClass(), 0);
3510
3511 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3512 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3513 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3514 ToClass.getTypePtr());
3515 return true;
3516 }
3517
3518 return false;
3519}
3520
3521/// CheckMemberPointerConversion - Check the member pointer conversion from the
3522/// expression From to the type ToType. This routine checks for ambiguous or
3523/// virtual or inaccessible base-to-derived member pointer conversions
3524/// for which IsMemberPointerConversion has already returned true. It returns
3525/// true and produces a diagnostic if there was an error, or returns false
3526/// otherwise.
3528 CastKind &Kind,
3529 CXXCastPath &BasePath,
3530 bool IgnoreBaseAccess) {
3531 QualType FromType = From->getType();
3532 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3533 if (!FromPtrType) {
3534 // This must be a null pointer to member pointer conversion
3535 assert(From->isNullPointerConstant(Context,
3537 "Expr must be null pointer constant!");
3538 Kind = CK_NullToMemberPointer;
3539 return false;
3540 }
3541
3542 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3543 assert(ToPtrType && "No member pointer cast has a target type "
3544 "that is not a member pointer.");
3545
3546 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3547 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3548
3549 // FIXME: What about dependent types?
3550 assert(FromClass->isRecordType() && "Pointer into non-class.");
3551 assert(ToClass->isRecordType() && "Pointer into non-class.");
3552
3553 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3554 /*DetectVirtual=*/true);
3555 bool DerivationOkay =
3556 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3557 assert(DerivationOkay &&
3558 "Should not have been called if derivation isn't OK.");
3559 (void)DerivationOkay;
3560
3561 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3562 getUnqualifiedType())) {
3563 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3564 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3565 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3566 return true;
3567 }
3568
3569 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3570 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3571 << FromClass << ToClass << QualType(VBase, 0)
3572 << From->getSourceRange();
3573 return true;
3574 }
3575
3576 if (!IgnoreBaseAccess)
3577 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3578 Paths.front(),
3579 diag::err_downcast_from_inaccessible_base);
3580
3581 // Must be a base to derived member conversion.
3582 BuildBasePathArray(Paths, BasePath);
3583 Kind = CK_BaseToDerivedMemberPointer;
3584 return false;
3585}
3586
3587/// Determine whether the lifetime conversion between the two given
3588/// qualifiers sets is nontrivial.
3590 Qualifiers ToQuals) {
3591 // Converting anything to const __unsafe_unretained is trivial.
3592 if (ToQuals.hasConst() &&
3594 return false;
3595
3596 return true;
3597}
3598
3599/// Perform a single iteration of the loop for checking if a qualification
3600/// conversion is valid.
3601///
3602/// Specifically, check whether any change between the qualifiers of \p
3603/// FromType and \p ToType is permissible, given knowledge about whether every
3604/// outer layer is const-qualified.
3606 bool CStyle, bool IsTopLevel,
3607 bool &PreviousToQualsIncludeConst,
3608 bool &ObjCLifetimeConversion) {
3609 Qualifiers FromQuals = FromType.getQualifiers();
3610 Qualifiers ToQuals = ToType.getQualifiers();
3611
3612 // Ignore __unaligned qualifier.
3613 FromQuals.removeUnaligned();
3614
3615 // Objective-C ARC:
3616 // Check Objective-C lifetime conversions.
3617 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3618 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3619 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3620 ObjCLifetimeConversion = true;
3621 FromQuals.removeObjCLifetime();
3622 ToQuals.removeObjCLifetime();
3623 } else {
3624 // Qualification conversions cannot cast between different
3625 // Objective-C lifetime qualifiers.
3626 return false;
3627 }
3628 }
3629
3630 // Allow addition/removal of GC attributes but not changing GC attributes.
3631 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3632 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3633 FromQuals.removeObjCGCAttr();
3634 ToQuals.removeObjCGCAttr();
3635 }
3636
3637 // -- for every j > 0, if const is in cv 1,j then const is in cv
3638 // 2,j, and similarly for volatile.
3639 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3640 return false;
3641
3642 // If address spaces mismatch:
3643 // - in top level it is only valid to convert to addr space that is a
3644 // superset in all cases apart from C-style casts where we allow
3645 // conversions between overlapping address spaces.
3646 // - in non-top levels it is not a valid conversion.
3647 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3648 (!IsTopLevel ||
3649 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3650 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3651 return false;
3652
3653 // -- if the cv 1,j and cv 2,j are different, then const is in
3654 // every cv for 0 < k < j.
3655 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3656 !PreviousToQualsIncludeConst)
3657 return false;
3658
3659 // The following wording is from C++20, where the result of the conversion
3660 // is T3, not T2.
3661 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3662 // "array of unknown bound of"
3663 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3664 return false;
3665
3666 // -- if the resulting P3,i is different from P1,i [...], then const is
3667 // added to every cv 3_k for 0 < k < i.
3668 if (!CStyle && FromType->isConstantArrayType() &&
3669 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3670 return false;
3671
3672 // Keep track of whether all prior cv-qualifiers in the "to" type
3673 // include const.
3674 PreviousToQualsIncludeConst =
3675 PreviousToQualsIncludeConst && ToQuals.hasConst();
3676 return true;
3677}
3678
3679/// IsQualificationConversion - Determines whether the conversion from
3680/// an rvalue of type FromType to ToType is a qualification conversion
3681/// (C++ 4.4).
3682///
3683/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3684/// when the qualification conversion involves a change in the Objective-C
3685/// object lifetime.
3686bool
3688 bool CStyle, bool &ObjCLifetimeConversion) {
3689 FromType = Context.getCanonicalType(FromType);
3690 ToType = Context.getCanonicalType(ToType);
3691 ObjCLifetimeConversion = false;
3692
3693 // If FromType and ToType are the same type, this is not a
3694 // qualification conversion.
3695 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3696 return false;
3697
3698 // (C++ 4.4p4):
3699 // A conversion can add cv-qualifiers at levels other than the first
3700 // in multi-level pointers, subject to the following rules: [...]
3701 bool PreviousToQualsIncludeConst = true;
3702 bool UnwrappedAnyPointer = false;
3703 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3705 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3706 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3707 return false;
3708 UnwrappedAnyPointer = true;
3709 }
3710
3711 // We are left with FromType and ToType being the pointee types
3712 // after unwrapping the original FromType and ToType the same number
3713 // of times. If we unwrapped any pointers, and if FromType and
3714 // ToType have the same unqualified type (since we checked
3715 // qualifiers above), then this is a qualification conversion.
3716 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3717}
3718
3719/// - Determine whether this is a conversion from a scalar type to an
3720/// atomic type.
3721///
3722/// If successful, updates \c SCS's second and third steps in the conversion
3723/// sequence to finish the conversion.
3724static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3725 bool InOverloadResolution,
3727 bool CStyle) {
3728 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3729 if (!ToAtomic)
3730 return false;
3731
3733 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3734 InOverloadResolution, InnerSCS,
3735 CStyle, /*AllowObjCWritebackConversion=*/false))
3736 return false;
3737
3738 SCS.Second = InnerSCS.Second;
3739 SCS.setToType(1, InnerSCS.getToType(1));
3740 SCS.Third = InnerSCS.Third;
3743 SCS.setToType(2, InnerSCS.getToType(2));
3744 return true;
3745}
3746
3748 CXXConstructorDecl *Constructor,
3749 QualType Type) {
3750 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3751 if (CtorType->getNumParams() > 0) {
3752 QualType FirstArg = CtorType->getParamType(0);
3753 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3754 return true;
3755 }
3756 return false;
3757}
3758
3759static OverloadingResult
3761 CXXRecordDecl *To,
3763 OverloadCandidateSet &CandidateSet,
3764 bool AllowExplicit) {
3766 for (auto *D : S.LookupConstructors(To)) {
3767 auto Info = getConstructorInfo(D);
3768 if (!Info)
3769 continue;
3770
3771 bool Usable = !Info.Constructor->isInvalidDecl() &&
3772 S.isInitListConstructor(Info.Constructor);
3773 if (Usable) {
3774 bool SuppressUserConversions = false;
3775 if (Info.ConstructorTmpl)
3776 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3777 /*ExplicitArgs*/ nullptr, From,
3778 CandidateSet, SuppressUserConversions,
3779 /*PartialOverloading*/ false,
3780 AllowExplicit);
3781 else
3782 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3783 CandidateSet, SuppressUserConversions,
3784 /*PartialOverloading*/ false, AllowExplicit);
3785 }
3786 }
3787
3788 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3789
3791 switch (auto Result =
3792 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3793 case OR_Deleted:
3794 case OR_Success: {
3795 // Record the standard conversion we used and the conversion function.
3796 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3797 QualType ThisType = Constructor->getFunctionObjectParameterType();
3798 // Initializer lists don't have conversions as such.
3800 User.HadMultipleCandidates = HadMultipleCandidates;
3801 User.ConversionFunction = Constructor;
3802 User.FoundConversionFunction = Best->FoundDecl;
3804 User.After.setFromType(ThisType);
3805 User.After.setAllToTypes(ToType);
3806 return Result;
3807 }
3808
3810 return OR_No_Viable_Function;
3811 case OR_Ambiguous:
3812 return OR_Ambiguous;
3813 }
3814
3815 llvm_unreachable("Invalid OverloadResult!");
3816}
3817
3818/// Determines whether there is a user-defined conversion sequence
3819/// (C++ [over.ics.user]) that converts expression From to the type
3820/// ToType. If such a conversion exists, User will contain the
3821/// user-defined conversion sequence that performs such a conversion
3822/// and this routine will return true. Otherwise, this routine returns
3823/// false and User is unspecified.
3824///
3825/// \param AllowExplicit true if the conversion should consider C++0x
3826/// "explicit" conversion functions as well as non-explicit conversion
3827/// functions (C++0x [class.conv.fct]p2).
3828///
3829/// \param AllowObjCConversionOnExplicit true if the conversion should
3830/// allow an extra Objective-C pointer conversion on uses of explicit
3831/// constructors. Requires \c AllowExplicit to also be set.
3832static OverloadingResult
3835 OverloadCandidateSet &CandidateSet,
3836 AllowedExplicit AllowExplicit,
3837 bool AllowObjCConversionOnExplicit) {
3838 assert(AllowExplicit != AllowedExplicit::None ||
3839 !AllowObjCConversionOnExplicit);
3841
3842 // Whether we will only visit constructors.
3843 bool ConstructorsOnly = false;
3844
3845 // If the type we are conversion to is a class type, enumerate its
3846 // constructors.
3847 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3848 // C++ [over.match.ctor]p1:
3849 // When objects of class type are direct-initialized (8.5), or
3850 // copy-initialized from an expression of the same or a
3851 // derived class type (8.5), overload resolution selects the
3852 // constructor. [...] For copy-initialization, the candidate
3853 // functions are all the converting constructors (12.3.1) of
3854 // that class. The argument list is the expression-list within
3855 // the parentheses of the initializer.
3856 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3857 (From->getType()->getAs<RecordType>() &&
3858 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3859 ConstructorsOnly = true;
3860
3861 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3862 // We're not going to find any constructors.
3863 } else if (CXXRecordDecl *ToRecordDecl
3864 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3865
3866 Expr **Args = &From;
3867 unsigned NumArgs = 1;
3868 bool ListInitializing = false;
3869 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3870 // But first, see if there is an init-list-constructor that will work.
3872 S, From, ToType, ToRecordDecl, User, CandidateSet,
3873 AllowExplicit == AllowedExplicit::All);
3875 return Result;
3876 // Never mind.
3877 CandidateSet.clear(
3879
3880 // If we're list-initializing, we pass the individual elements as
3881 // arguments, not the entire list.
3882 Args = InitList->getInits();
3883 NumArgs = InitList->getNumInits();
3884 ListInitializing = true;
3885 }
3886
3887 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3888 auto Info = getConstructorInfo(D);
3889 if (!Info)
3890 continue;
3891
3892 bool Usable = !Info.Constructor->isInvalidDecl();
3893 if (!ListInitializing)
3894 Usable = Usable && Info.Constructor->isConvertingConstructor(
3895 /*AllowExplicit*/ true);
3896 if (Usable) {
3897 bool SuppressUserConversions = !ConstructorsOnly;
3898 // C++20 [over.best.ics.general]/4.5:
3899 // if the target is the first parameter of a constructor [of class
3900 // X] and the constructor [...] is a candidate by [...] the second
3901 // phase of [over.match.list] when the initializer list has exactly
3902 // one element that is itself an initializer list, [...] and the
3903 // conversion is to X or reference to cv X, user-defined conversion
3904 // sequences are not cnosidered.
3905 if (SuppressUserConversions && ListInitializing) {
3906 SuppressUserConversions =
3907 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3908 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3909 ToType);
3910 }
3911 if (Info.ConstructorTmpl)
3913 Info.ConstructorTmpl, Info.FoundDecl,
3914 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3915 CandidateSet, SuppressUserConversions,
3916 /*PartialOverloading*/ false,
3917 AllowExplicit == AllowedExplicit::All);
3918 else
3919 // Allow one user-defined conversion when user specifies a
3920 // From->ToType conversion via an static cast (c-style, etc).
3921 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3922 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3923 SuppressUserConversions,
3924 /*PartialOverloading*/ false,
3925 AllowExplicit == AllowedExplicit::All);
3926 }
3927 }
3928 }
3929 }
3930
3931 // Enumerate conversion functions, if we're allowed to.
3932 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3933 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3934 // No conversion functions from incomplete types.
3935 } else if (const RecordType *FromRecordType =
3936 From->getType()->getAs<RecordType>()) {
3937 if (CXXRecordDecl *FromRecordDecl
3938 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3939 // Add all of the conversion functions as candidates.
3940 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3941 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3942 DeclAccessPair FoundDecl = I.getPair();
3943 NamedDecl *D = FoundDecl.getDecl();
3944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3945 if (isa<UsingShadowDecl>(D))
3946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3947
3948 CXXConversionDecl *Conv;
3949 FunctionTemplateDecl *ConvTemplate;
3950 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3951 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3952 else
3953 Conv = cast<CXXConversionDecl>(D);
3954
3955 if (ConvTemplate)
3957 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3958 CandidateSet, AllowObjCConversionOnExplicit,
3959 AllowExplicit != AllowedExplicit::None);
3960 else
3961 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3962 CandidateSet, AllowObjCConversionOnExplicit,
3963 AllowExplicit != AllowedExplicit::None);
3964 }
3965 }
3966 }
3967
3968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3969
3971 switch (auto Result =
3972 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3973 case OR_Success:
3974 case OR_Deleted:
3975 // Record the standard conversion we used and the conversion function.
3976 if (CXXConstructorDecl *Constructor
3977 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3978 // C++ [over.ics.user]p1:
3979 // If the user-defined conversion is specified by a
3980 // constructor (12.3.1), the initial standard conversion
3981 // sequence converts the source type to the type required by
3982 // the argument of the constructor.
3983 //
3984 if (isa<InitListExpr>(From)) {
3985 // Initializer lists don't have conversions as such.
3987 } else {
3988 if (Best->Conversions[0].isEllipsis())
3989 User.EllipsisConversion = true;
3990 else {
3991 User.Before = Best->Conversions[0].Standard;
3992 User.EllipsisConversion = false;
3993 }
3994 }
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3996 User.ConversionFunction = Constructor;
3997 User.FoundConversionFunction = Best->FoundDecl;
3999 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003 if (CXXConversionDecl *Conversion
4004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4005 // C++ [over.ics.user]p1:
4006 //
4007 // [...] If the user-defined conversion is specified by a
4008 // conversion function (12.3.2), the initial standard
4009 // conversion sequence converts the source type to the
4010 // implicit object parameter of the conversion function.
4011 User.Before = Best->Conversions[0].Standard;
4012 User.HadMultipleCandidates = HadMultipleCandidates;
4013 User.ConversionFunction = Conversion;
4014 User.FoundConversionFunction = Best->FoundDecl;
4015 User.EllipsisConversion = false;
4016
4017 // C++ [over.ics.user]p2:
4018 // The second standard conversion sequence converts the
4019 // result of the user-defined conversion to the target type
4020 // for the sequence. Since an implicit conversion sequence
4021 // is an initialization, the special rules for
4022 // initialization by user-defined conversion apply when
4023 // selecting the best user-defined conversion for a
4024 // user-defined conversion sequence (see 13.3.3 and
4025 // 13.3.3.1).
4026 User.After = Best->FinalConversion;
4027 return Result;
4028 }
4029 llvm_unreachable("Not a constructor or conversion function?");
4030
4032 return OR_No_Viable_Function;
4033
4034 case OR_Ambiguous:
4035 return OR_Ambiguous;
4036 }
4037
4038 llvm_unreachable("Invalid OverloadResult!");
4039}
4040
4041bool
4044 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4046 OverloadingResult OvResult =
4047 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4048 CandidateSet, AllowedExplicit::None, false);
4049
4050 if (!(OvResult == OR_Ambiguous ||
4051 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4052 return false;
4053
4054 auto Cands = CandidateSet.CompleteCandidates(
4055 *this,
4057 From);
4058 if (OvResult == OR_Ambiguous)
4059 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4060 << From->getType() << ToType << From->getSourceRange();
4061 else { // OR_No_Viable_Function && !CandidateSet.empty()
4062 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4063 diag::err_typecheck_nonviable_condition_incomplete,
4064 From->getType(), From->getSourceRange()))
4065 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4066 << false << From->getType() << From->getSourceRange() << ToType;
4067 }
4068
4069 CandidateSet.NoteCandidates(
4070 *this, From, Cands);
4071 return true;
4072}
4073
4074// Helper for compareConversionFunctions that gets the FunctionType that the
4075// conversion-operator return value 'points' to, or nullptr.
4076static const FunctionType *
4078 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4079 const PointerType *RetPtrTy =
4080 ConvFuncTy->getReturnType()->getAs<PointerType>();
4081
4082 if (!RetPtrTy)
4083 return nullptr;
4084
4085 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4086}
4087
4088/// Compare the user-defined conversion functions or constructors
4089/// of two user-defined conversion sequences to determine whether any ordering
4090/// is possible.
4093 FunctionDecl *Function2) {
4094 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4095 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4096 if (!Conv1 || !Conv2)
4098
4099 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4101
4102 // Objective-C++:
4103 // If both conversion functions are implicitly-declared conversions from
4104 // a lambda closure type to a function pointer and a block pointer,
4105 // respectively, always prefer the conversion to a function pointer,
4106 // because the function pointer is more lightweight and is more likely
4107 // to keep code working.
4108 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4109 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4110 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4111 if (Block1 != Block2)
4112 return Block1 ? ImplicitConversionSequence::Worse
4114 }
4115
4116 // In order to support multiple calling conventions for the lambda conversion
4117 // operator (such as when the free and member function calling convention is
4118 // different), prefer the 'free' mechanism, followed by the calling-convention
4119 // of operator(). The latter is in place to support the MSVC-like solution of
4120 // defining ALL of the possible conversions in regards to calling-convention.
4121 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4122 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4123
4124 if (Conv1FuncRet && Conv2FuncRet &&
4125 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4126 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4127 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4128
4129 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4130 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4131
4132 CallingConv CallOpCC =
4133 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4135 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4137 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4138
4139 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4140 for (CallingConv CC : PrefOrder) {
4141 if (Conv1CC == CC)
4143 if (Conv2CC == CC)
4145 }
4146 }
4147
4149}
4150
4152 const ImplicitConversionSequence &ICS) {
4154 (ICS.isUserDefined() &&
4156}
4157
4158/// CompareImplicitConversionSequences - Compare two implicit
4159/// conversion sequences to determine whether one is better than the
4160/// other or if they are indistinguishable (C++ 13.3.3.2).
4163 const ImplicitConversionSequence& ICS1,
4164 const ImplicitConversionSequence& ICS2)
4165{
4166 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4167 // conversion sequences (as defined in 13.3.3.1)
4168 // -- a standard conversion sequence (13.3.3.1.1) is a better
4169 // conversion sequence than a user-defined conversion sequence or
4170 // an ellipsis conversion sequence, and
4171 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4172 // conversion sequence than an ellipsis conversion sequence
4173 // (13.3.3.1.3).
4174 //
4175 // C++0x [over.best.ics]p10:
4176 // For the purpose of ranking implicit conversion sequences as
4177 // described in 13.3.3.2, the ambiguous conversion sequence is
4178 // treated as a user-defined sequence that is indistinguishable
4179 // from any other user-defined conversion sequence.
4180
4181 // String literal to 'char *' conversion has been deprecated in C++03. It has
4182 // been removed from C++11. We still accept this conversion, if it happens at
4183 // the best viable function. Otherwise, this conversion is considered worse
4184 // than ellipsis conversion. Consider this as an extension; this is not in the
4185 // standard. For example:
4186 //
4187 // int &f(...); // #1
4188 // void f(char*); // #2
4189 // void g() { int &r = f("foo"); }
4190 //
4191 // In C++03, we pick #2 as the best viable function.
4192 // In C++11, we pick #1 as the best viable function, because ellipsis
4193 // conversion is better than string-literal to char* conversion (since there
4194 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4195 // convert arguments, #2 would be the best viable function in C++11.
4196 // If the best viable function has this conversion, a warning will be issued
4197 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4198
4199 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4202 // Ill-formedness must not differ
4203 ICS1.isBad() == ICS2.isBad())
4207
4208 if (ICS1.getKindRank() < ICS2.getKindRank())
4210 if (ICS2.getKindRank() < ICS1.getKindRank())
4212
4213 // The following checks require both conversion sequences to be of
4214 // the same kind.
4215 if (ICS1.getKind() != ICS2.getKind())
4217
4220
4221 // Two implicit conversion sequences of the same form are
4222 // indistinguishable conversion sequences unless one of the
4223 // following rules apply: (C++ 13.3.3.2p3):
4224
4225 // List-initialization sequence L1 is a better conversion sequence than
4226 // list-initialization sequence L2 if:
4227 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4228 // if not that,
4229 // — L1 and L2 convert to arrays of the same element type, and either the
4230 // number of elements n_1 initialized by L1 is less than the number of
4231 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4232 // an array of unknown bound and L1 does not,
4233 // even if one of the other rules in this paragraph would otherwise apply.
4234 if (!ICS1.isBad()) {
4235 bool StdInit1 = false, StdInit2 = false;
4238 nullptr);
4241 nullptr);
4242 if (StdInit1 != StdInit2)
4243 return StdInit1 ? ImplicitConversionSequence::Better
4245
4248 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4250 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4252 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4253 CAT2->getElementType())) {
4254 // Both to arrays of the same element type
4255 if (CAT1->getSize() != CAT2->getSize())
4256 // Different sized, the smaller wins
4257 return CAT1->getSize().ult(CAT2->getSize())
4262 // One is incomplete, it loses
4266 }
4267 }
4268 }
4269
4270 if (ICS1.isStandard())
4271 // Standard conversion sequence S1 is a better conversion sequence than
4272 // standard conversion sequence S2 if [...]
4274 ICS1.Standard, ICS2.Standard);
4275 else if (ICS1.isUserDefined()) {
4276 // User-defined conversion sequence U1 is a better conversion
4277 // sequence than another user-defined conversion sequence U2 if
4278 // they contain the same user-defined conversion function or
4279 // constructor and if the second standard conversion sequence of
4280 // U1 is better than the second standard conversion sequence of
4281 // U2 (C++ 13.3.3.2p3).
4285 ICS1.UserDefined.After,
4286 ICS2.UserDefined.After);
4287 else
4291 }
4292
4293 return Result;
4294}
4295
4296// Per 13.3.3.2p3, compare the given standard conversion sequences to
4297// determine if one is a proper subset of the other.
4300 const StandardConversionSequence& SCS1,
4301 const StandardConversionSequence& SCS2) {
4304
4305 // the identity conversion sequence is considered to be a subsequence of
4306 // any non-identity conversion sequence
4307 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4309 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4311
4312 if (SCS1.Second != SCS2.Second) {
4313 if (SCS1.Second == ICK_Identity)
4315 else if (SCS2.Second == ICK_Identity)
4317 else
4319 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4321
4322 if (SCS1.Third == SCS2.Third) {
4323 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4325 }
4326
4327 if (SCS1.Third == ICK_Identity)
4331
4332 if (SCS2.Third == ICK_Identity)
4336
4338}
4339
4340/// Determine whether one of the given reference bindings is better
4341/// than the other based on what kind of bindings they are.
4342static bool
4344 const StandardConversionSequence &SCS2) {
4345 // C++0x [over.ics.rank]p3b4:
4346 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4347 // implicit object parameter of a non-static member function declared
4348 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4349 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4350 // lvalue reference to a function lvalue and S2 binds an rvalue
4351 // reference*.
4352 //
4353 // FIXME: Rvalue references. We're going rogue with the above edits,
4354 // because the semantics in the current C++0x working paper (N3225 at the
4355 // time of this writing) break the standard definition of std::forward
4356 // and std::reference_wrapper when dealing with references to functions.
4357 // Proposed wording changes submitted to CWG for consideration.
4360 return false;
4361
4362 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4363 SCS2.IsLvalueReference) ||
4366}
4367
4369 None,
4372};
4373
4374/// Returns kind of fixed enum promotion the \a SCS uses.
4375static FixedEnumPromotion
4377
4378 if (SCS.Second != ICK_Integral_Promotion)
4379 return FixedEnumPromotion::None;
4380
4381 QualType FromType = SCS.getFromType();
4382 if (!FromType->isEnumeralType())
4383 return FixedEnumPromotion::None;
4384
4385 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4386 if (!Enum->isFixed())
4387 return FixedEnumPromotion::None;
4388
4389 QualType UnderlyingType = Enum->getIntegerType();
4390 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4391 return FixedEnumPromotion::ToUnderlyingType;
4392
4393 return FixedEnumPromotion::ToPromotedUnderlyingType;
4394}
4395
4396/// CompareStandardConversionSequences - Compare two standard
4397/// conversion sequences to determine whether one is better than the
4398/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4401 const StandardConversionSequence& SCS1,
4402 const StandardConversionSequence& SCS2)
4403{
4404 // Standard conversion sequence S1 is a better conversion sequence
4405 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4406
4407 // -- S1 is a proper subsequence of S2 (comparing the conversion
4408 // sequences in the canonical form defined by 13.3.3.1.1,
4409 // excluding any Lvalue Transformation; the identity conversion
4410 // sequence is considered to be a subsequence of any
4411 // non-identity conversion sequence) or, if not that,
4414 return CK;
4415
4416 // -- the rank of S1 is better than the rank of S2 (by the rules
4417 // defined below), or, if not that,
4418 ImplicitConversionRank Rank1 = SCS1.getRank();
4419 ImplicitConversionRank Rank2 = SCS2.getRank();
4420 if (Rank1 < Rank2)
4422 else if (Rank2 < Rank1)
4424
4425 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4426 // are indistinguishable unless one of the following rules
4427 // applies:
4428
4429 // A conversion that is not a conversion of a pointer, or
4430 // pointer to member, to bool is better than another conversion
4431 // that is such a conversion.
4433 return SCS2.isPointerConversionToBool()
4436
4437 // C++14 [over.ics.rank]p4b2:
4438 // This is retroactively applied to C++11 by CWG 1601.
4439 //
4440 // A conversion that promotes an enumeration whose underlying type is fixed
4441 // to its underlying type is better than one that promotes to the promoted
4442 // underlying type, if the two are different.
4445 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4446 FEP1 != FEP2)
4447 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4450
4451 // C++ [over.ics.rank]p4b2:
4452 //
4453 // If class B is derived directly or indirectly from class A,
4454 // conversion of B* to A* is better than conversion of B* to
4455 // void*, and conversion of A* to void* is better than conversion
4456 // of B* to void*.
4457 bool SCS1ConvertsToVoid
4459 bool SCS2ConvertsToVoid
4461 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4462 // Exactly one of the conversion sequences is a conversion to
4463 // a void pointer; it's the worse conversion.
4464 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4466 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4467 // Neither conversion sequence converts to a void pointer; compare
4468 // their derived-to-base conversions.
4470 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4471 return DerivedCK;
4472 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4473 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4474 // Both conversion sequences are conversions to void
4475 // pointers. Compare the source types to determine if there's an
4476 // inheritance relationship in their sources.
4477 QualType FromType1 = SCS1.getFromType();
4478 QualType FromType2 = SCS2.getFromType();
4479
4480 // Adjust the types we're converting from via the array-to-pointer
4481 // conversion, if we need to.
4482 if (SCS1.First == ICK_Array_To_Pointer)
4483 FromType1 = S.Context.getArrayDecayedType(FromType1);
4484 if (SCS2.First == ICK_Array_To_Pointer)
4485 FromType2 = S.Context.getArrayDecayedType(FromType2);
4486
4487 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4488 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4489
4490 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4492 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4494
4495 // Objective-C++: If one interface is more specific than the
4496 // other, it is the better one.
4497 const ObjCObjectPointerType* FromObjCPtr1
4498 = FromType1->getAs<ObjCObjectPointerType>();
4499 const ObjCObjectPointerType* FromObjCPtr2
4500 = FromType2->getAs<ObjCObjectPointerType>();
4501 if (FromObjCPtr1 && FromObjCPtr2) {
4502 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4503 FromObjCPtr2);
4504 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4505 FromObjCPtr1);
4506 if (AssignLeft != AssignRight) {
4507 return AssignLeft? ImplicitConversionSequence::Better
4509 }
4510 }
4511 }
4512
4513 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4514 // Check for a better reference binding based on the kind of bindings.
4515 if (isBetterReferenceBindingKind(SCS1, SCS2))
4517 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4519 }
4520
4521 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4522 // bullet 3).
4524 = CompareQualificationConversions(S, SCS1, SCS2))
4525 return QualCK;
4526
4527 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4528 // C++ [over.ics.rank]p3b4:
4529 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4530 // which the references refer are the same type except for
4531 // top-level cv-qualifiers, and the type to which the reference
4532 // initialized by S2 refers is more cv-qualified than the type
4533 // to which the reference initialized by S1 refers.
4534 QualType T1 = SCS1.getToType(2);
4535 QualType T2 = SCS2.getToType(2);
4536 T1 = S.Context.getCanonicalType(T1);
4537 T2 = S.Context.getCanonicalType(T2);
4538 Qualifiers T1Quals, T2Quals;
4539 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4540 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4541 if (UnqualT1 == UnqualT2) {
4542 // Objective-C++ ARC: If the references refer to objects with different
4543 // lifetimes, prefer bindings that don't change lifetime.
4549 }
4550
4551 // If the type is an array type, promote the element qualifiers to the
4552 // type for comparison.
4553 if (isa<ArrayType>(T1) && T1Quals)
4554 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4555 if (isa<ArrayType>(T2) && T2Quals)
4556 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4557 if (T2.isMoreQualifiedThan(T1))
4559 if (T1.isMoreQualifiedThan(T2))
4561 }
4562 }
4563
4564 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4565 // floating-to-integral conversion if the integral conversion
4566 // is between types of the same size.
4567 // For example:
4568 // void f(float);
4569 // void f(int);
4570 // int main {
4571 // long a;
4572 // f(a);
4573 // }
4574 // Here, MSVC will call f(int) instead of generating a compile error
4575 // as clang will do in standard mode.
4576 if (S.getLangOpts().MSVCCompat &&
4579 SCS2.Second == ICK_Floating_Integral &&
4580 S.Context.getTypeSize(SCS1.getFromType()) ==
4581 S.Context.getTypeSize(SCS1.getToType(2)))
4583
4584 // Prefer a compatible vector conversion over a lax vector conversion
4585 // For example:
4586 //
4587 // typedef float __v4sf __attribute__((__vector_size__(16)));
4588 // void f(vector float);
4589 // void f(vector signed int);
4590 // int main() {
4591 // __v4sf a;
4592 // f(a);
4593 // }
4594 // Here, we'd like to choose f(vector float) and not
4595 // report an ambiguous call error
4596 if (SCS1.Second == ICK_Vector_Conversion &&
4597 SCS2.Second == ICK_Vector_Conversion) {
4598 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 SCS1.getFromType(), SCS1.getToType(2));
4600 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4601 SCS2.getFromType(), SCS2.getToType(2));
4602
4603 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4604 return SCS1IsCompatibleVectorConversion
4607 }
4608
4609 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4611 bool SCS1IsCompatibleSVEVectorConversion =
4613 bool SCS2IsCompatibleSVEVectorConversion =
4615
4616 if (SCS1IsCompatibleSVEVectorConversion !=
4617 SCS2IsCompatibleSVEVectorConversion)
4618 return SCS1IsCompatibleSVEVectorConversion
4621 }
4622
4623 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4625 bool SCS1IsCompatibleRVVVectorConversion =
4627 bool SCS2IsCompatibleRVVVectorConversion =
4629
4630 if (SCS1IsCompatibleRVVVectorConversion !=
4631 SCS2IsCompatibleRVVVectorConversion)
4632 return SCS1IsCompatibleRVVVectorConversion
4635 }
4636
4638}
4639
4640/// CompareQualificationConversions - Compares two standard conversion
4641/// sequences to determine whether they can be ranked based on their
4642/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4645 const StandardConversionSequence& SCS1,
4646 const StandardConversionSequence& SCS2) {
4647 // C++ [over.ics.rank]p3:
4648 // -- S1 and S2 differ only in their qualification conversion and
4649 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4650 // [C++98]
4651 // [...] and the cv-qualification signature of type T1 is a proper subset
4652 // of the cv-qualification signature of type T2, and S1 is not the
4653 // deprecated string literal array-to-pointer conversion (4.2).
4654 // [C++2a]
4655 // [...] where T1 can be converted to T2 by a qualification conversion.
4656 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4657 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4659
4660 // FIXME: the example in the standard doesn't use a qualification
4661 // conversion (!)
4662 QualType T1 = SCS1.getToType(2);
4663 QualType T2 = SCS2.getToType(2);
4664 T1 = S.Context.getCanonicalType(T1);
4665 T2 = S.Context.getCanonicalType(T2);
4666 assert(!T1->isReferenceType() && !T2->isReferenceType());
4667 Qualifiers T1Quals, T2Quals;
4668 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4669 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4670
4671 // If the types are the same, we won't learn anything by unwrapping
4672 // them.
4673 if (UnqualT1 == UnqualT2)
4675
4676 // Don't ever prefer a standard conversion sequence that uses the deprecated
4677 // string literal array to pointer conversion.
4678 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4679 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4680
4681 // Objective-C++ ARC:
4682 // Prefer qualification conversions not involving a change in lifetime
4683 // to qualification conversions that do change lifetime.
4686 CanPick1 = false;
4689 CanPick2 = false;
4690
4691 bool ObjCLifetimeConversion;
4692 if (CanPick1 &&
4693 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4694 CanPick1 = false;
4695 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4696 // directions, so we can't short-cut this second check in general.
4697 if (CanPick2 &&
4698 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4699 CanPick2 = false;
4700
4701 if (CanPick1 != CanPick2)
4702 return CanPick1 ? ImplicitConversionSequence::Better
4705}
4706
4707/// CompareDerivedToBaseConversions - Compares two standard conversion
4708/// sequences to determine whether they can be ranked based on their
4709/// various kinds of derived-to-base conversions (C++
4710/// [over.ics.rank]p4b3). As part of these checks, we also look at
4711/// conversions between Objective-C interface types.
4714 const StandardConversionSequence& SCS1,
4715 const StandardConversionSequence& SCS2) {
4716 QualType FromType1 = SCS1.getFromType();
4717 QualType ToType1 = SCS1.getToType(1);
4718 QualType FromType2 = SCS2.getFromType();
4719 QualType ToType2 = SCS2.getToType(1);
4720
4721 // Adjust the types we're converting from via the array-to-pointer
4722 // conversion, if we need to.
4723 if (SCS1.First == ICK_Array_To_Pointer)
4724 FromType1 = S.Context.getArrayDecayedType(FromType1);
4725 if (SCS2.First == ICK_Array_To_Pointer)
4726 FromType2 = S.Context.getArrayDecayedType(FromType2);
4727
4728 // Canonicalize all of the types.
4729 FromType1 = S.Context.getCanonicalType(FromType1);
4730 ToType1 = S.Context.getCanonicalType(ToType1);
4731 FromType2 = S.Context.getCanonicalType(FromType2);
4732 ToType2 = S.Context.getCanonicalType(ToType2);
4733
4734 // C++ [over.ics.rank]p4b3:
4735 //
4736 // If class B is derived directly or indirectly from class A and
4737 // class C is derived directly or indirectly from B,
4738 //
4739 // Compare based on pointer conversions.
4740 if (SCS1.Second == ICK_Pointer_Conversion &&
4742 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4743 FromType1->isPointerType() && FromType2->isPointerType() &&
4744 ToType1->isPointerType() && ToType2->isPointerType()) {
4745 QualType FromPointee1 =
4746 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4747 QualType ToPointee1 =
4748 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4749 QualType FromPointee2 =
4750 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4751 QualType ToPointee2 =
4752 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4753
4754 // -- conversion of C* to B* is better than conversion of C* to A*,
4755 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4756 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4758 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4760 }
4761
4762 // -- conversion of B* to A* is better than conversion of C* to A*,
4763 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4764 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4766 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4768 }
4769 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4771 const ObjCObjectPointerType *FromPtr1
4772 = FromType1->getAs<ObjCObjectPointerType>();
4773 const ObjCObjectPointerType *FromPtr2
4774 = FromType2->getAs<ObjCObjectPointerType>();
4775 const ObjCObjectPointerType *ToPtr1
4776 = ToType1->getAs<ObjCObjectPointerType>();
4777 const ObjCObjectPointerType *ToPtr2
4778 = ToType2->getAs<ObjCObjectPointerType>();
4779
4780 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4781 // Apply the same conversion ranking rules for Objective-C pointer types
4782 // that we do for C++ pointers to class types. However, we employ the
4783 // Objective-C pseudo-subtyping relationship used for assignment of
4784 // Objective-C pointer types.
4785 bool FromAssignLeft
4786 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4787 bool FromAssignRight
4788 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4789 bool ToAssignLeft
4790 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4791 bool ToAssignRight
4792 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4793
4794 // A conversion to an a non-id object pointer type or qualified 'id'
4795 // type is better than a conversion to 'id'.
4796 if (ToPtr1->isObjCIdType() &&
4797 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4799 if (ToPtr2->isObjCIdType() &&
4800 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4802
4803 // A conversion to a non-id object pointer type is better than a
4804 // conversion to a qualified 'id' type
4805 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4807 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4809
4810 // A conversion to an a non-Class object pointer type or qualified 'Class'
4811 // type is better than a conversion to 'Class'.
4812 if (ToPtr1->isObjCClassType() &&
4813 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4815 if (ToPtr2->isObjCClassType() &&
4816 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4818
4819 // A conversion to a non-Class object pointer type is better than a
4820 // conversion to a qualified 'Class' type.
4821 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4823 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4825
4826 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4827 if (S.Context.hasSameType(FromType1, FromType2) &&
4828 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4829 (ToAssignLeft != ToAssignRight)) {
4830 if (FromPtr1->isSpecialized()) {
4831 // "conversion of B<A> * to B * is better than conversion of B * to
4832 // C *.
4833 bool IsFirstSame =
4834 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4835 bool IsSecondSame =
4836 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4837 if (IsFirstSame) {
4838 if (!IsSecondSame)
4840 } else if (IsSecondSame)
4842 }
4843 return ToAssignLeft? ImplicitConversionSequence::Worse
4845 }
4846
4847 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4848 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4849 (FromAssignLeft != FromAssignRight))
4850 return FromAssignLeft? ImplicitConversionSequence::Better
4852 }
4853 }
4854
4855 // Ranking of member-pointer types.
4856 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4857 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4858 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4859 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4860 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4861 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4862 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4863 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4864 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4865 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4866 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4867 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4868 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4869 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4870 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4871 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4872 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4873 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4875 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4877 }
4878 // conversion of B::* to C::* is better than conversion of A::* to C::*
4879 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4880 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4882 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4884 }
4885 }
4886
4887 if (SCS1.Second == ICK_Derived_To_Base) {
4888 // -- conversion of C to B is better than conversion of C to A,
4889 // -- binding of an expression of type C to a reference of type
4890 // B& is better than binding an expression of type C to a
4891 // reference of type A&,
4892 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4893 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4894 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4896 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4898 }
4899
4900 // -- conversion of B to A is better than conversion of C to A.
4901 // -- binding of an expression of type B to a reference of type
4902 // A& is better than binding an expression of type C to a
4903 // reference of type A&,
4904 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4905 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4906 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4908 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4910 }
4911 }
4912
4914}
4915
4917 if (!T.getQualifiers().hasUnaligned())
4918 return T;
4919
4920 Qualifiers Q;
4921 T = Ctx.getUnqualifiedArrayType(T, Q);
4922 Q.removeUnaligned();
4923 return Ctx.getQualifiedType(T, Q);
4924}
4925
4926/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4927/// determine whether they are reference-compatible,
4928/// reference-related, or incompatible, for use in C++ initialization by
4929/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4930/// type, and the first type (T1) is the pointee type of the reference
4931/// type being initialized.
4934 QualType OrigT1, QualType OrigT2,
4935 ReferenceConversions *ConvOut) {
4936 assert(!OrigT1->isReferenceType() &&
4937 "T1 must be the pointee type of the reference type");
4938 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4939
4940 QualType T1 = Context.getCanonicalType(OrigT1);
4941 QualType T2 = Context.getCanonicalType(OrigT2);
4942 Qualifiers T1Quals, T2Quals;
4943 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4944 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4945
4946 ReferenceConversions ConvTmp;
4947 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4948 Conv = ReferenceConversions();
4949
4950 // C++2a [dcl.init.ref]p4:
4951 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4952 // reference-related to "cv2 T2" if T1 is similar to T2, or
4953 // T1 is a base class of T2.
4954 // "cv1 T1" is reference-compatible with "cv2 T2" if
4955 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4956 // "pointer to cv1 T1" via a standard conversion sequence.
4957
4958 // Check for standard conversions we can apply to pointers: derived-to-base
4959 // conversions, ObjC pointer conversions, and function pointer conversions.
4960 // (Qualification conversions are checked last.)
4961 QualType ConvertedT2;
4962 if (UnqualT1 == UnqualT2) {
4963 // Nothing to do.
4964 } else if (isCompleteType(Loc, OrigT2) &&
4965 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4966 Conv |= ReferenceConversions::DerivedToBase;
4967 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4968 UnqualT2->isObjCObjectOrInterfaceType() &&
4969 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4970 Conv |= ReferenceConversions::ObjC;
4971 else if (UnqualT2->isFunctionType() &&
4972 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4973 Conv |= ReferenceConversions::Function;
4974 // No need to check qualifiers; function types don't have them.
4975 return Ref_Compatible;
4976 }
4977 bool ConvertedReferent = Conv != 0;
4978
4979 // We can have a qualification conversion. Compute whether the types are
4980 // similar at the same time.
4981 bool PreviousToQualsIncludeConst = true;
4982 bool TopLevel = true;
4983 do {
4984 if (T1 == T2)
4985 break;
4986
4987 // We will need a qualification conversion.
4988 Conv |= ReferenceConversions::Qualification;
4989
4990 // Track whether we performed a qualification conversion anywhere other
4991 // than the top level. This matters for ranking reference bindings in
4992 // overload resolution.
4993 if (!TopLevel)
4994 Conv |= ReferenceConversions::NestedQualification;
4995
4996 // MS compiler ignores __unaligned qualifier for references; do the same.
4997 T1 = withoutUnaligned(Context, T1);
4998 T2 = withoutUnaligned(Context, T2);
4999
5000 // If we find a qualifier mismatch, the types are not reference-compatible,
5001 // but are still be reference-related if they're similar.
5002 bool ObjCLifetimeConversion = false;
5003 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5004 PreviousToQualsIncludeConst,
5005 ObjCLifetimeConversion))
5006 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5007 ? Ref_Related
5008 : Ref_Incompatible;
5009
5010 // FIXME: Should we track this for any level other than the first?
5011 if (ObjCLifetimeConversion)
5012 Conv |= ReferenceConversions::ObjCLifetime;
5013
5014 TopLevel = false;
5015 } while (Context.UnwrapSimilarTypes(T1, T2));
5016
5017 // At this point, if the types are reference-related, we must either have the
5018 // same inner type (ignoring qualifiers), or must have already worked out how
5019 // to convert the referent.
5020 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5021 ? Ref_Compatible
5022 : Ref_Incompatible;
5023}
5024
5025/// Look for a user-defined conversion to a value reference-compatible
5026/// with DeclType. Return true if something definite is found.
5027static bool
5029 QualType DeclType, SourceLocation DeclLoc,
5030 Expr *Init, QualType T2, bool AllowRvalues,
5031 bool AllowExplicit) {
5032 assert(T2->isRecordType() && "Can only find conversions of record types.");
5033 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5034
5035 OverloadCandidateSet CandidateSet(
5037 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5038 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5039 NamedDecl *D = *I;
5040 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5041 if (isa<UsingShadowDecl>(D))
5042 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5043
5044 FunctionTemplateDecl *ConvTemplate
5045 = dyn_cast<FunctionTemplateDecl>(D);
5046 CXXConversionDecl *Conv;
5047 if (ConvTemplate)
5048 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5049 else
5050 Conv = cast<CXXConversionDecl>(D);
5051
5052 if (AllowRvalues) {
5053 // If we are initializing an rvalue reference, don't permit conversion
5054 // functions that return lvalues.
5055 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5056 const ReferenceType *RefType
5058 if (RefType && !RefType->getPointeeType()->isFunctionType())
5059 continue;
5060 }
5061
5062 if (!ConvTemplate &&
5064 DeclLoc,
5065 Conv->getConversionType()
5070 continue;
5071 } else {
5072 // If the conversion function doesn't return a reference type,
5073 // it can't be considered for this conversion. An rvalue reference
5074 // is only acceptable if its referencee is a function type.
5075
5076 const ReferenceType *RefType =
5078 if (!RefType ||
5079 (!RefType->isLValueReferenceType() &&
5080 !RefType->getPointeeType()->isFunctionType()))
5081 continue;
5082 }
5083
5084 if (ConvTemplate)
5086 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5087 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5088 else
5090 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5091 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5092 }
5093
5094 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5095
5097 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5098 case OR_Success:
5099 // C++ [over.ics.ref]p1:
5100 //
5101 // [...] If the parameter binds directly to the result of
5102 // applying a conversion function to the argument
5103 // expression, the implicit conversion sequence is a
5104 // user-defined conversion sequence (13.3.3.1.2), with the
5105 // second standard conversion sequence either an identity
5106 // conversion or, if the conversion function returns an
5107 // entity of a type that is a derived class of the parameter
5108 // type, a derived-to-base Conversion.
5109 if (!Best->FinalConversion.DirectBinding)
5110 return false;
5111
5112 ICS.setUserDefined();
5113 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5114 ICS.UserDefined.After = Best->FinalConversion;
5115 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5116 ICS.UserDefined.ConversionFunction = Best->Function;
5117 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5118 ICS.UserDefined.EllipsisConversion = false;
5119 assert(ICS.UserDefined.After.ReferenceBinding &&
5121 "Expected a direct reference binding!");
5122 return true;
5123
5124 case OR_Ambiguous:
5125 ICS.setAmbiguous();
5126 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5127 Cand != CandidateSet.end(); ++Cand)
5128 if (Cand->Best)
5129 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5130 return true;
5131
5133 case OR_Deleted:
5134 // There was no suitable conversion, or we found a deleted
5135 // conversion; continue with other checks.
5136 return false;
5137 }
5138
5139 llvm_unreachable("Invalid OverloadResult!");
5140}
5141
5142/// Compute an implicit conversion sequence for reference
5143/// initialization.
5146 SourceLocation DeclLoc,
5147 bool SuppressUserConversions,
5148 bool AllowExplicit) {
5149 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5150
5151 // Most paths end in a failed conversion.
5154
5155 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5156 QualType T2 = Init->getType();
5157
5158 // If the initializer is the address of an overloaded function, try
5159 // to resolve the overloaded function. If all goes well, T2 is the
5160 // type of the resulting function.
5161 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5162 DeclAccessPair Found;
5164 false, Found))
5165 T2 = Fn->getType();
5166 }
5167
5168 // Compute some basic properties of the types and the initializer.
5169 bool isRValRef = DeclType->isRValueReferenceType();
5170 Expr::Classification InitCategory = Init->Classify(S.Context);
5171
5173 Sema::ReferenceCompareResult RefRelationship =
5174 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5175
5176 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5177 ICS.setStandard();
5179 // FIXME: A reference binding can be a function conversion too. We should
5180 // consider that when ordering reference-to-function bindings.
5181 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5183 : (RefConv & Sema::ReferenceConversions::ObjC)
5185 : ICK_Identity;
5187 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5188 // a reference binding that performs a non-top-level qualification
5189 // conversion as a qualification conversion, not as an identity conversion.
5190 ICS.Standard.Third = (RefConv &
5191 Sema::ReferenceConversions::NestedQualification)
5193 : ICK_Identity;
5194 ICS.Standard.setFromType(T2);
5195 ICS.Standard.setToType(0, T2);
5196 ICS.Standard.setToType(1, T1);
5197 ICS.Standard.setToType(2, T1);
5198 ICS.Standard.ReferenceBinding = true;
5199 ICS.Standard.DirectBinding = BindsDirectly;
5200 ICS.Standard.IsLvalueReference = !isRValRef;
5202 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5205 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5206 ICS.Standard.CopyConstructor = nullptr;
5208 };
5209
5210 // C++0x [dcl.init.ref]p5:
5211 // A reference to type "cv1 T1" is initialized by an expression
5212 // of type "cv2 T2" as follows:
5213
5214 // -- If reference is an lvalue reference and the initializer expression
5215 if (!isRValRef) {
5216 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5217 // reference-compatible with "cv2 T2," or
5218 //
5219 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5220 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5221 // C++ [over.ics.ref]p1:
5222 // When a parameter of reference type binds directly (8.5.3)
5223 // to an argument expression, the implicit conversion sequence
5224 // is the identity conversion, unless the argument expression
5225 // has a type that is a derived class of the parameter type,
5226 // in which case the implicit conversion sequence is a
5227 // derived-to-base Conversion (13.3.3.1).
5228 SetAsReferenceBinding(/*BindsDirectly=*/true);
5229
5230 // Nothing more to do: the inaccessibility/ambiguity check for
5231 // derived-to-base conversions is suppressed when we're
5232 // computing the implicit conversion sequence (C++
5233 // [over.best.ics]p2).
5234 return ICS;
5235 }
5236
5237 // -- has a class type (i.e., T2 is a class type), where T1 is
5238 // not reference-related to T2, and can be implicitly
5239 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5240 // is reference-compatible with "cv3 T3" 92) (this
5241 // conversion is selected by enumerating the applicable
5242 // conversion functions (13.3.1.6) and choosing the best
5243 // one through overload resolution (13.3)),
5244 if (!SuppressUserConversions && T2->isRecordType() &&
5245 S.isCompleteType(DeclLoc, T2) &&
5246 RefRelationship == Sema::Ref_Incompatible) {
5247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5248 Init, T2, /*AllowRvalues=*/false,
5249 AllowExplicit))
5250 return ICS;
5251 }
5252 }
5253
5254 // -- Otherwise, the reference shall be an lvalue reference to a
5255 // non-volatile const type (i.e., cv1 shall be const), or the reference
5256 // shall be an rvalue reference.
5257 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5258 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5260 return ICS;
5261 }
5262
5263 // -- If the initializer expression
5264 //
5265 // -- is an xvalue, class prvalue, array prvalue or function
5266 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5267 if (RefRelationship == Sema::Ref_Compatible &&
5268 (InitCategory.isXValue() ||
5269 (InitCategory.isPRValue() &&
5270 (T2->isRecordType() || T2->isArrayType())) ||
5271 (InitCategory.isLValue() && T2->isFunctionType()))) {
5272 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5273 // binding unless we're binding to a class prvalue.
5274 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5275 // allow the use of rvalue references in C++98/03 for the benefit of
5276 // standard library implementors; therefore, we need the xvalue check here.
5277 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5278 !(InitCategory.isPRValue() || T2->isRecordType()));
5279 return ICS;
5280 }
5281
5282 // -- has a class type (i.e., T2 is a class type), where T1 is not
5283 // reference-related to T2, and can be implicitly converted to
5284 // an xvalue, class prvalue, or function lvalue of type
5285 // "cv3 T3", where "cv1 T1" is reference-compatible with
5286 // "cv3 T3",
5287 //
5288 // then the reference is bound to the value of the initializer
5289 // expression in the first case and to the result of the conversion
5290 // in the second case (or, in either case, to an appropriate base
5291 // class subobject).
5292 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5293 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5294 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5295 Init, T2, /*AllowRvalues=*/true,
5296 AllowExplicit)) {
5297 // In the second case, if the reference is an rvalue reference
5298 // and the second standard conversion sequence of the
5299 // user-defined conversion sequence includes an lvalue-to-rvalue
5300 // conversion, the program is ill-formed.
5301 if (ICS.isUserDefined() && isRValRef &&
5304
5305 return ICS;
5306 }
5307
5308 // A temporary of function type cannot be created; don't even try.
5309 if (T1->isFunctionType())
5310 return ICS;
5311
5312 // -- Otherwise, a temporary of type "cv1 T1" is created and
5313 // initialized from the initializer expression using the
5314 // rules for a non-reference copy initialization (8.5). The
5315 // reference is then bound to the temporary. If T1 is
5316 // reference-related to T2, cv1 must be the same
5317 // cv-qualification as, or greater cv-qualification than,
5318 // cv2; otherwise, the program is ill-formed.
5319 if (RefRelationship == Sema::Ref_Related) {
5320 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5321 // we would be reference-compatible or reference-compatible with
5322 // added qualification. But that wasn't the case, so the reference
5323 // initialization fails.
5324 //
5325 // Note that we only want to check address spaces and cvr-qualifiers here.
5326 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5327 Qualifiers T1Quals = T1.getQualifiers();
5328 Qualifiers T2Quals = T2.getQualifiers();
5329 T1Quals.removeObjCGCAttr();
5330 T1Quals.removeObjCLifetime();
5331 T2Quals.removeObjCGCAttr();
5332 T2Quals.removeObjCLifetime();
5333 // MS compiler ignores __unaligned qualifier for references; do the same.
5334 T1Quals.removeUnaligned();
5335 T2Quals.removeUnaligned();
5336 if (!T1Quals.compatiblyIncludes(T2Quals))
5337 return ICS;
5338 }
5339
5340 // If at least one of the types is a class type, the types are not
5341 // related, and we aren't allowed any user conversions, the
5342 // reference binding fails. This case is important for breaking
5343 // recursion, since TryImplicitConversion below will attempt to
5344 // create a temporary through the use of a copy constructor.
5345 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5346 (T1->isRecordType() || T2->isRecordType()))
5347 return ICS;
5348
5349 // If T1 is reference-related to T2 and the reference is an rvalue
5350 // reference, the initializer expression shall not be an lvalue.
5351 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5352 Init->Classify(S.Context).isLValue()) {
5354 return ICS;
5355 }
5356
5357 // C++ [over.ics.ref]p2:
5358 // When a parameter of reference type is not bound directly to
5359 // an argument expression, the conversion sequence is the one
5360 // required to convert the argument expression to the
5361 // underlying type of the reference according to
5362 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5363 // to copy-initializing a temporary of the underlying type with
5364 // the argument expression. Any difference in top-level
5365 // cv-qualification is subsumed by the initialization itself
5366 // and does not constitute a conversion.
5367 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5368 AllowedExplicit::None,
5369 /*InOverloadResolution=*/false,
5370 /*CStyle=*/false,
5371 /*AllowObjCWritebackConversion=*/false,
5372 /*AllowObjCConversionOnExplicit=*/false);
5373
5374 // Of course, that's still a reference binding.
5375 if (ICS.isStandard()) {
5376 ICS.Standard.ReferenceBinding = true;
5377 ICS.Standard.IsLvalueReference = !isRValRef;
5378 ICS.Standard.BindsToFunctionLvalue = false;
5379 ICS.Standard.BindsToRvalue = true;
5382 } else if (ICS.isUserDefined()) {
5383 const ReferenceType *LValRefType =
5386
5387 // C++ [over.ics.ref]p3:
5388 // Except for an implicit object parameter, for which see 13.3.1, a
5389 // standard conversion sequence cannot be formed if it requires [...]
5390 // binding an rvalue reference to an lvalue other than a function
5391 // lvalue.
5392 // Note that the function case is not possible here.
5393 if (isRValRef && LValRefType) {
5395 return ICS;
5396 }
5397
5399 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5401 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5404 }
5405
5406 return ICS;
5407}
5408
5410TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5411 bool SuppressUserConversions,
5412 bool InOverloadResolution,
5413 bool AllowObjCWritebackConversion,
5414 bool AllowExplicit = false);
5415
5416/// TryListConversion - Try to copy-initialize a value of type ToType from the
5417/// initializer list From.
5420 bool SuppressUserConversions,
5421 bool InOverloadResolution,
5422 bool AllowObjCWritebackConversion) {
5423 // C++11 [over.ics.list]p1:
5424 // When an argument is an initializer list, it is not an expression and
5425 // special rules apply for converting it to a parameter type.
5426
5428 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5429
5430 // We need a complete type for what follows. With one C++20 exception,
5431 // incomplete types can never be initialized from init lists.
5432 QualType InitTy = ToType;
5433 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5434 if (AT && S.getLangOpts().CPlusPlus20)
5435 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5436 // C++20 allows list initialization of an incomplete array type.
5437 InitTy = IAT->getElementType();
5438 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5439 return Result;
5440
5441 // C++20 [over.ics.list]/2:
5442 // If the initializer list is a designated-initializer-list, a conversion
5443 // is only possible if the parameter has an aggregate type
5444 //
5445 // FIXME: The exception for reference initialization here is not part of the
5446 // language rules, but follow other compilers in adding it as a tentative DR
5447 // resolution.
5448 bool IsDesignatedInit = From->hasDesignatedInit();
5449 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5450 IsDesignatedInit)
5451 return Result;
5452
5453 // Per DR1467:
5454 // If the parameter type is a class X and the initializer list has a single
5455 // element of type cv U, where U is X or a class derived from X, the
5456 // implicit conversion sequence is the one required to convert the element
5457 // to the parameter type.
5458 //
5459 // Otherwise, if the parameter type is a character array [... ]
5460 // and the initializer list has a single element that is an
5461 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5462 // implicit conversion sequence is the identity conversion.
5463 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5464 if (ToType->isRecordType()) {
5465 QualType InitType = From->getInit(0)->getType();
5466 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5467 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5468 return TryCopyInitialization(S, From->getInit(0), ToType,
5469 SuppressUserConversions,
5470 InOverloadResolution,
5471 AllowObjCWritebackConversion);
5472 }
5473
5474 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5475 InitializedEntity Entity =
5477 /*Consumed=*/false);
5478 if (S.CanPerformCopyInitialization(Entity, From)) {
5479 Result.setStandard();
5480 Result.Standard.setAsIdentityConversion();
5481 Result.Standard.setFromType(ToType);
5482 Result.Standard.setAllToTypes(ToType);
5483 return Result;
5484 }
5485 }
5486 }
5487
5488 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5489 // C++11 [over.ics.list]p2:
5490 // If the parameter type is std::initializer_list<X> or "array of X" and
5491 // all the elements can be implicitly converted to X, the implicit
5492 // conversion sequence is the worst conversion necessary to convert an
5493 // element of the list to X.
5494 //
5495 // C++14 [over.ics.list]p3:
5496 // Otherwise, if the parameter type is "array of N X", if the initializer
5497 // list has exactly N elements or if it has fewer than N elements and X is
5498 // default-constructible, and if all the elements of the initializer list
5499 // can be implicitly converted to X, the implicit conversion sequence is
5500 // the worst conversion necessary to convert an element of the list to X.
5501 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5502 unsigned e = From->getNumInits();
5505 QualType());
5506 QualType ContTy = ToType;
5507 bool IsUnbounded = false;
5508 if (AT) {
5509 InitTy = AT->getElementType();
5510 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5511 if (CT->getSize().ult(e)) {
5512 // Too many inits, fatally bad
5514 ToType);
5515 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5516 return Result;
5517 }
5518 if (CT->getSize().ugt(e)) {
5519 // Need an init from empty {}, is there one?
5520 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5521 From->getEndLoc());
5522 EmptyList.setType(S.Context.VoidTy);
5523 DfltElt = TryListConversion(
5524 S, &EmptyList, InitTy, SuppressUserConversions,
5525 InOverloadResolution, AllowObjCWritebackConversion);
5526 if (DfltElt.isBad()) {
5527 // No {} init, fatally bad
5529 ToType);
5530 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5531 return Result;
5532 }
5533 }
5534 } else {
5535 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5536 IsUnbounded = true;
5537 if (!e) {
5538 // Cannot convert to zero-sized.
5540 ToType);
5541 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5542 return Result;
5543 }
5544 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5545 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5547 }
5548 }
5549
5550 Result.setStandard();
5551 Result.Standard.setAsIdentityConversion();
5552 Result.Standard.setFromType(InitTy);
5553 Result.Standard.setAllToTypes(InitTy);
5554 for (unsigned i = 0; i < e; ++i) {
5555 Expr *Init = From->getInit(i);
5557 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5558 AllowObjCWritebackConversion);
5559
5560 // Keep the worse conversion seen so far.
5561 // FIXME: Sequences are not totally ordered, so 'worse' can be
5562 // ambiguous. CWG has been informed.
5564 Result) ==
5566 Result = ICS;
5567 // Bail as soon as we find something unconvertible.
5568 if (Result.isBad()) {
5569 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5570 return Result;
5571 }
5572 }
5573 }
5574
5575 // If we needed any implicit {} initialization, compare that now.
5576 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5577 // has been informed that this might not be the best thing.
5578 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5579 S, From->getEndLoc(), DfltElt, Result) ==
5581 Result = DfltElt;
5582 // Record the type being initialized so that we may compare sequences
5583 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5584 return Result;
5585 }
5586
5587 // C++14 [over.ics.list]p4:
5588 // C++11 [over.ics.list]p3:
5589 // Otherwise, if the parameter is a non-aggregate class X and overload
5590 // resolution chooses a single best constructor [...] the implicit
5591 // conversion sequence is a user-defined conversion sequence. If multiple
5592 // constructors are viable but none is better than the others, the
5593 // implicit conversion sequence is a user-defined conversion sequence.
5594 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5595 // This function can deal with initializer lists.
5596 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5597 AllowedExplicit::None,
5598 InOverloadResolution, /*CStyle=*/false,
5599 AllowObjCWritebackConversion,
5600 /*AllowObjCConversionOnExplicit=*/false);
5601 }
5602
5603 // C++14 [over.ics.list]p5:
5604 // C++11 [over.ics.list]p4:
5605 // Otherwise, if the parameter has an aggregate type which can be
5606 // initialized from the initializer list [...] the implicit conversion
5607 // sequence is a user-defined conversion sequence.
5608 if (ToType->isAggregateType()) {
5609 // Type is an aggregate, argument is an init list. At this point it comes
5610 // down to checking whether the initialization works.
5611 // FIXME: Find out whether this parameter is consumed or not.
5612 InitializedEntity Entity =
5614 /*Consumed=*/false);
5616 From)) {
5617 Result.setUserDefined();
5618 Result.UserDefined.Before.setAsIdentityConversion();
5619 // Initializer lists don't have a type.
5620 Result.UserDefined.Before.setFromType(QualType());
5621 Result.UserDefined.Before.setAllToTypes(QualType());
5622
5623 Result.UserDefined.After.setAsIdentityConversion();
5624 Result.UserDefined.After.setFromType(ToType);
5625 Result.UserDefined.After.setAllToTypes(ToType);
5626 Result.UserDefined.ConversionFunction = nullptr;
5627 }
5628 return Result;
5629 }
5630
5631 // C++14 [over.ics.list]p6:
5632 // C++11 [over.ics.list]p5:
5633 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5634 if (ToType->isReferenceType()) {
5635 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5636 // mention initializer lists in any way. So we go by what list-
5637 // initialization would do and try to extrapolate from that.
5638
5639 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5640
5641 // If the initializer list has a single element that is reference-related
5642 // to the parameter type, we initialize the reference from that.
5643 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5644 Expr *Init = From->getInit(0);
5645
5646 QualType T2 = Init->getType();
5647
5648 // If the initializer is the address of an overloaded function, try
5649 // to resolve the overloaded function. If all goes well, T2 is the
5650 // type of the resulting function.
5651 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5652 DeclAccessPair Found;
5654 Init, ToType, false, Found))
5655 T2 = Fn->getType();
5656 }
5657
5658 // Compute some basic properties of the types and the initializer.
5659 Sema::ReferenceCompareResult RefRelationship =
5660 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5661
5662 if (RefRelationship >= Sema::Ref_Related) {
5663 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5664 SuppressUserConversions,
5665 /*AllowExplicit=*/false);
5666 }
5667 }
5668
5669 // Otherwise, we bind the reference to a temporary created from the
5670 // initializer list.
5671 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5672 InOverloadResolution,
5673 AllowObjCWritebackConversion);
5674 if (Result.isFailure())
5675 return Result;
5676 assert(!Result.isEllipsis() &&
5677 "Sub-initialization cannot result in ellipsis conversion.");
5678
5679 // Can we even bind to a temporary?
5680 if (ToType->isRValueReferenceType() ||
5681 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5682 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5683 Result.UserDefined.After;
5684 SCS.ReferenceBinding = true;
5686 SCS.BindsToRvalue = true;
5687 SCS.BindsToFunctionLvalue = false;
5690 } else
5692 From, ToType);
5693 return Result;
5694 }
5695
5696 // C++14 [over.ics.list]p7:
5697 // C++11 [over.ics.list]p6:
5698 // Otherwise, if the parameter type is not a class:
5699 if (!ToType->isRecordType()) {
5700 // - if the initializer list has one element that is not itself an
5701 // initializer list, the implicit conversion sequence is the one
5702 // required to convert the element to the parameter type.
5703 unsigned NumInits = From->getNumInits();
5704 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5705 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5706 SuppressUserConversions,
5707 InOverloadResolution,
5708 AllowObjCWritebackConversion);
5709 // - if the initializer list has no elements, the implicit conversion
5710 // sequence is the identity conversion.
5711 else if (NumInits == 0) {
5712 Result.setStandard();
5713 Result.Standard.setAsIdentityConversion();
5714 Result.Standard.setFromType(ToType);
5715 Result.Standard.setAllToTypes(ToType);
5716 }
5717 return Result;
5718 }
5719
5720 // C++14 [over.ics.list]p8:
5721 // C++11 [over.ics.list]p7:
5722 // In all cases other than those enumerated above, no conversion is possible
5723 return Result;
5724}
5725
5726/// TryCopyInitialization - Try to copy-initialize a value of type
5727/// ToType from the expression From. Return the implicit conversion
5728/// sequence required to pass this argument, which may be a bad
5729/// conversion sequence (meaning that the argument cannot be passed to
5730/// a parameter of this type). If @p SuppressUserConversions, then we
5731/// do not permit any user-defined conversion sequences.
5734 bool SuppressUserConversions,
5735 bool InOverloadResolution,
5736 bool AllowObjCWritebackConversion,
5737 bool AllowExplicit) {
5738 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5739 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5740 InOverloadResolution,AllowObjCWritebackConversion);
5741
5742 if (ToType->isReferenceType())
5743 return TryReferenceInit(S, From, ToType,
5744 /*FIXME:*/ From->getBeginLoc(),
5745 SuppressUserConversions, AllowExplicit);
5746
5747 return TryImplicitConversion(S, From, ToType,
5748 SuppressUserConversions,
5749 AllowedExplicit::None,
5750 InOverloadResolution,
5751 /*CStyle=*/false,
5752 AllowObjCWritebackConversion,
5753 /*AllowObjCConversionOnExplicit=*/false);
5754}
5755
5756static bool TryCopyInitialization(const CanQualType FromQTy,
5757 const CanQualType ToQTy,
5758 Sema &S,
5759 SourceLocation Loc,
5760 ExprValueKind FromVK) {
5761 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5763 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5764
5765 return !ICS.isBad();
5766}
5767
5768/// TryObjectArgumentInitialization - Try to initialize the object
5769/// parameter of the given member function (@c Method) from the
5770/// expression @p From.
5772 Sema &S, SourceLocation Loc, QualType FromType,
5773 Expr::Classification FromClassification, CXXMethodDecl *Method,
5774 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5775 QualType ExplicitParameterType = QualType(),
5776 bool SuppressUserConversion = false) {
5777
5778 // We need to have an object of class type.
5779 if (const auto *PT = FromType->getAs<PointerType>()) {
5780 FromType = PT->getPointeeType();
5781
5782 // When we had a pointer, it's implicitly dereferenced, so we
5783 // better have an lvalue.
5784 assert(FromClassification.isLValue());
5785 }
5786
5787 auto ValueKindFromClassification = [](Expr::Classification C) {
5788 if (C.isPRValue())
5789 return clang::VK_PRValue;
5790 if (C.isXValue())
5791 return VK_XValue;
5792 return clang::VK_LValue;
5793 };
5794
5795 if (Method->isExplicitObjectMemberFunction()) {
5796 if (ExplicitParameterType.isNull())
5797 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5798 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5799 ValueKindFromClassification(FromClassification));
5801 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5802 /*InOverloadResolution=*/true, false);
5803 if (ICS.isBad())
5804 ICS.Bad.FromExpr = nullptr;
5805 return ICS;
5806 }
5807
5808 assert(FromType->isRecordType());
5809
5810 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5811 // C++98 [class.dtor]p2:
5812 // A destructor can be invoked for a const, volatile or const volatile
5813 // object.
5814 // C++98 [over.match.funcs]p4:
5815 // For static member functions, the implicit object parameter is considered
5816 // to match any object (since if the function is selected, the object is
5817 // discarded).
5818 Qualifiers Quals = Method->getMethodQualifiers();
5819 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5820 Quals.addConst();
5821 Quals.addVolatile();
5822 }
5823
5824 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5825
5826 // Set up the conversion sequence as a "bad" conversion, to allow us
5827 // to exit early.
5829
5830 // C++0x [over.match.funcs]p4:
5831 // For non-static member functions, the type of the implicit object
5832 // parameter is
5833 //
5834 // - "lvalue reference to cv X" for functions declared without a
5835 // ref-qualifier or with the & ref-qualifier
5836 // - "rvalue reference to cv X" for functions declared with the &&
5837 // ref-qualifier
5838 //
5839 // where X is the class of which the function is a member and cv is the
5840 // cv-qualification on the member function declaration.
5841 //
5842 // However, when finding an implicit conversion sequence for the argument, we
5843 // are not allowed to perform user-defined conversions
5844 // (C++ [over.match.funcs]p5). We perform a simplified version of
5845 // reference binding here, that allows class rvalues to bind to
5846 // non-constant references.
5847
5848 // First check the qualifiers.
5849 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5850 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5851 if (ImplicitParamType.getCVRQualifiers() !=
5852 FromTypeCanon.getLocalCVRQualifiers() &&
5853 !ImplicitParamType.isAtLeastAsQualifiedAs(
5854 withoutUnaligned(S.Context, FromTypeCanon))) {
5856 FromType, ImplicitParamType);
5857 return ICS;
5858 }
5859
5860 if (FromTypeCanon.hasAddressSpace()) {
5861 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5862 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5863 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5865 FromType, ImplicitParamType);
5866 return ICS;
5867 }
5868 }
5869
5870 // Check that we have either the same type or a derived type. It
5871 // affects the conversion rank.
5872 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5873 ImplicitConversionKind SecondKind;
5874 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5875 SecondKind = ICK_Identity;
5876 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5877 SecondKind = ICK_Derived_To_Base;
5878 } else if (!Method->isExplicitObjectMemberFunction()) {
5880 FromType, ImplicitParamType);
5881 return ICS;
5882 }
5883
5884 // Check the ref-qualifier.
5885 switch (Method->getRefQualifier()) {
5886 case RQ_None:
5887 // Do nothing; we don't care about lvalueness or rvalueness.
5888 break;
5889
5890 case RQ_LValue:
5891 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5892 // non-const lvalue reference cannot bind to an rvalue
5894 ImplicitParamType);
5895 return ICS;
5896 }
5897 break;
5898
5899 case RQ_RValue:
5900 if (!FromClassification.isRValue()) {
5901 // rvalue reference cannot bind to an lvalue
5903 ImplicitParamType);
5904 return ICS;
5905 }
5906 break;
5907 }
5908
5909 // Success. Mark this as a reference binding.
5910 ICS.setStandard();
5912 ICS.Standard.Second = SecondKind;
5913 ICS.Standard.setFromType(FromType);
5914 ICS.Standard.setAllToTypes(ImplicitParamType);
5915 ICS.Standard.ReferenceBinding = true;
5916 ICS.Standard.DirectBinding = true;
5918 ICS.Standard.BindsToFunctionLvalue = false;
5919 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5921 = (Method->getRefQualifier() == RQ_None);
5922 return ICS;
5923}
5924
5925/// PerformObjectArgumentInitialization - Perform initialization of
5926/// the implicit object parameter for the given Method with the given
5927/// expression.
5929 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5930 CXXMethodDecl *Method) {
5931 QualType FromRecordType, DestType;
5932 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5933
5934 Expr::Classification FromClassification;
5935 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5936 FromRecordType = PT->getPointeeType();
5937 DestType = Method->getThisType();
5938 FromClassification = Expr::Classification::makeSimpleLValue();
5939 } else {
5940 FromRecordType = From->getType();
5941 DestType = ImplicitParamRecordType;
5942 FromClassification = From->Classify(Context);
5943
5944 // When performing member access on a prvalue, materialize a temporary.
5945 if (From->isPRValue()) {
5946 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5947 Method->getRefQualifier() !=
5949 }
5950 }
5951
5952 // Note that we always use the true parent context when performing
5953 // the actual argument initialization.
5955 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5956 Method->getParent());
5957 if (ICS.isBad()) {
5958 switch (ICS.Bad.Kind) {
5960 Qualifiers FromQs = FromRecordType.getQualifiers();
5961 Qualifiers ToQs = DestType.getQualifiers();
5962 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5963 if (CVR) {
5964 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5965 << Method->getDeclName() << FromRecordType << (CVR - 1)
5966 << From->getSourceRange();
5967 Diag(Method->getLocation(), diag::note_previous_decl)
5968 << Method->getDeclName();
5969 return ExprError();
5970 }
5971 break;
5972 }
5973
5976 bool IsRValueQualified =
5978 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5979 << Method->getDeclName() << FromClassification.isRValue()
5980 << IsRValueQualified;
5981 Diag(Method->getLocation(), diag::note_previous_decl)
5982 << Method->getDeclName();
5983 return ExprError();
5984 }
5985
5988 break;
5989
5992 llvm_unreachable("Lists are not objects");
5993 }
5994
5995 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5996 << ImplicitParamRecordType << FromRecordType
5997 << From->getSourceRange();
5998 }
5999
6000 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6001 ExprResult FromRes =
6002 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6003 if (FromRes.isInvalid())
6004 return ExprError();
6005 From = FromRes.get();
6006 }
6007
6008 if (!Context.hasSameType(From->getType(), DestType)) {
6009 CastKind CK;
6010 QualType PteeTy = DestType->getPointeeType();
6011 LangAS DestAS =
6012 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6013 if (FromRecordType.getAddressSpace() != DestAS)
6014 CK = CK_AddressSpaceConversion;
6015 else
6016 CK = CK_NoOp;
6017 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6018 }
6019 return From;
6020}
6021
6022/// TryContextuallyConvertToBool - Attempt to contextually convert the
6023/// expression From to bool (C++0x [conv]p3).
6026 // C++ [dcl.init]/17.8:
6027 // - Otherwise, if the initialization is direct-initialization, the source
6028 // type is std::nullptr_t, and the destination type is bool, the initial
6029 // value of the object being initialized is false.
6030 if (From->getType()->isNullPtrType())
6032 S.Context.BoolTy,
6033 From->isGLValue());
6034
6035 // All other direct-initialization of bool is equivalent to an implicit
6036 // conversion to bool in which explicit conversions are permitted.
6037 return TryImplicitConversion(S, From, S.Context.BoolTy,
6038 /*SuppressUserConversions=*/false,
6039 AllowedExplicit::Conversions,
6040 /*InOverloadResolution=*/false,
6041 /*CStyle=*/false,
6042 /*AllowObjCWritebackConversion=*/false,
6043 /*AllowObjCConversionOnExplicit=*/false);
6044}
6045
6046/// PerformContextuallyConvertToBool - Perform a contextual conversion
6047/// of the expression From to bool (C++0x [conv]p3).
6049 if (checkPlaceholderForOverload(*this, From))
6050 return ExprError();
6051
6053 if (!ICS.isBad())
6054 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
6055
6056 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6057 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6058 << From->getType() << From->getSourceRange();
6059 return ExprError();
6060}
6061
6062/// Check that the specified conversion is permitted in a converted constant
6063/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6064/// is acceptable.
6067 // Since we know that the target type is an integral or unscoped enumeration
6068 // type, most conversion kinds are impossible. All possible First and Third
6069 // conversions are fine.
6070 switch (SCS.Second) {
6071 case ICK_Identity:
6073 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6075 return true;
6076
6078 // Conversion from an integral or unscoped enumeration type to bool is
6079 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6080 // conversion, so we allow it in a converted constant expression.
6081 //
6082 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6083 // a lot of popular code. We should at least add a warning for this
6084 // (non-conforming) extension.
6086 SCS.getToType(2)->isBooleanType();
6087
6089 case ICK_Pointer_Member:
6090 // C++1z: null pointer conversions and null member pointer conversions are
6091 // only permitted if the source type is std::nullptr_t.
6092 return SCS.getFromType()->isNullPtrType();
6093
6104 case ICK_Vector_Splat:
6105 case ICK_Complex_Real:
6114 return false;
6115
6120 llvm_unreachable("found a first conversion kind in Second");
6121
6123 case ICK_Qualification:
6124 llvm_unreachable("found a third conversion kind in Second");
6125
6127 break;
6128 }
6129
6130 llvm_unreachable("unknown conversion kind");
6131}
6132
6133/// BuildConvertedConstantExpression - Check that the expression From is a
6134/// converted constant expression of type T, perform the conversion but
6135/// does not evaluate the expression
6137 QualType T,
6138 Sema::CCEKind CCE,
6139 NamedDecl *Dest,
6140 APValue &PreNarrowingValue) {
6141 assert(S.getLangOpts().CPlusPlus11 &&
6142 "converted constant expression outside C++11");
6143
6144 if (checkPlaceholderForOverload(S, From))
6145 return ExprError();
6146
6147 // C++1z [expr.const]p3:
6148 // A converted constant expression of type T is an expression,
6149 // implicitly converted to type T, where the converted
6150 // expression is a constant expression and the implicit conversion
6151 // sequence contains only [... list of conversions ...].
6155 : TryCopyInitialization(S, From, T,
6156 /*SuppressUserConversions=*/false,
6157 /*InOverloadResolution=*/false,
6158 /*AllowObjCWritebackConversion=*/false,
6159 /*AllowExplicit=*/false);
6160 StandardConversionSequence *SCS = nullptr;
6161 switch (ICS.getKind()) {
6163 SCS = &ICS.Standard;
6164 break;
6166 if (T->isRecordType())
6167 SCS = &ICS.UserDefined.Before;
6168 else
6169 SCS = &ICS.UserDefined.After;
6170 break;
6174 return S.Diag(From->getBeginLoc(),
6175 diag::err_typecheck_converted_constant_expression)
6176 << From->getType() << From->getSourceRange() << T;
6177 return ExprError();
6178
6181 llvm_unreachable("bad conversion in converted constant expression");
6182 }
6183
6184 // Check that we would only use permitted conversions.
6185 if (!CheckConvertedConstantConversions(S, *SCS)) {
6186 return S.Diag(From->getBeginLoc(),
6187 diag::err_typecheck_converted_constant_expression_disallowed)
6188 << From->getType() << From->getSourceRange() << T;
6189 }
6190 // [...] and where the reference binding (if any) binds directly.
6191 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6192 return S.Diag(From->getBeginLoc(),
6193 diag::err_typecheck_converted_constant_expression_indirect)
6194 << From->getType() << From->getSourceRange() << T;
6195 }
6196 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6197 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6198 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6199 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6200 // case explicitly.
6201 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6202 return S.Diag(From->getBeginLoc(),
6203 diag::err_reference_bind_to_bitfield_in_cce)
6204 << From->getSourceRange();
6205 }
6206
6207 // Usually we can simply apply the ImplicitConversionSequence we formed
6208 // earlier, but that's not guaranteed to work when initializing an object of
6209 // class type.
6211 if (T->isRecordType()) {
6212 assert(CCE == Sema::CCEK_TemplateArg &&
6213 "unexpected class type converted constant expr");
6216 T, cast<NonTypeTemplateParmDecl>(Dest)),
6217 SourceLocation(), From);
6218 } else {
6220 }
6221 if (Result.isInvalid())
6222 return Result;
6223
6224 // C++2a [intro.execution]p5:
6225 // A full-expression is [...] a constant-expression [...]
6226 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6227 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6229 if (Result.isInvalid())
6230 return Result;
6231
6232 // Check for a narrowing implicit conversion.
6233 bool ReturnPreNarrowingValue = false;
6234 QualType PreNarrowingType;
6235 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6236 PreNarrowingType)) {
6238 // Implicit conversion to a narrower type, but the expression is
6239 // value-dependent so we can't tell whether it's actually narrowing.
6241 // Implicit conversion to a narrower type, and the value is not a constant
6242 // expression. We'll diagnose this in a moment.
6243 case NK_Not_Narrowing:
6244 break;
6245
6247 if (CCE == Sema::CCEK_ArrayBound &&
6248 PreNarrowingType->isIntegralOrEnumerationType() &&
6249 PreNarrowingValue.isInt()) {
6250 // Don't diagnose array bound narrowing here; we produce more precise
6251 // errors by allowing the un-narrowed value through.
6252 ReturnPreNarrowingValue = true;
6253 break;
6254 }
6255 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6256 << CCE << /*Constant*/ 1
6257 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6258 break;
6259
6260 case NK_Type_Narrowing:
6261 // FIXME: It would be better to diagnose that the expression is not a
6262 // constant expression.
6263 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6264 << CCE << /*Constant*/ 0 << From->getType() << T;
6265 break;
6266 }
6267 if (!ReturnPreNarrowingValue)
6268 PreNarrowingValue = {};
6269
6270 return Result;
6271}
6272
6273/// CheckConvertedConstantExpression - Check that the expression From is a
6274/// converted constant expression of type T, perform the conversion and produce
6275/// the converted expression, per C++11 [expr.const]p3.
6278 Sema::CCEKind CCE,
6279 bool RequireInt,
6280 NamedDecl *Dest) {
6281
6282 APValue PreNarrowingValue;
6284 PreNarrowingValue);
6285 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6286 Value = APValue();
6287 return Result;
6288 }
6289 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6290 RequireInt, PreNarrowingValue);
6291}
6292
6294 CCEKind CCE,
6295 NamedDecl *Dest) {
6296 APValue PreNarrowingValue;
6297 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6298 PreNarrowingValue);
6299}
6300
6302 APValue &Value, CCEKind CCE,
6303 NamedDecl *Dest) {
6304 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6305 Dest);
6306}
6307
6309 llvm::APSInt &Value,
6310 CCEKind CCE) {
6311 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6312
6313 APValue V;
6314 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6315 /*Dest=*/nullptr);
6316 if (!R.isInvalid() && !R.get()->isValueDependent())
6317 Value = V.getInt();
6318 return R;
6319}
6320
6321/// EvaluateConvertedConstantExpression - Evaluate an Expression
6322/// That is a converted constant expression
6323/// (which was built with BuildConvertedConstantExpression)
6326 Sema::CCEKind CCE, bool RequireInt,
6327 const APValue &PreNarrowingValue) {
6328
6329 ExprResult Result = E;
6330 // Check the expression is a constant expression.
6332 Expr::EvalResult Eval;
6333 Eval.Diag = &Notes;
6334
6335 ConstantExprKind Kind;
6336 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6337 Kind = ConstantExprKind::ClassTemplateArgument;
6338 else if (CCE == Sema::CCEK_TemplateArg)
6339 Kind = ConstantExprKind::NonClassTemplateArgument;
6340 else
6341 Kind = ConstantExprKind::Normal;
6342
6343 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6344 (RequireInt && !Eval.Val.isInt())) {
6345 // The expression can't be folded, so we can't keep it at this position in
6346 // the AST.
6347 Result = ExprError();
6348 } else {
6349 Value = Eval.Val;
6350
6351 if (Notes.empty()) {
6352 // It's a constant expression.
6353 Expr *E = Result.get();
6354 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6355 // We expect a ConstantExpr to have a value associated with it
6356 // by this point.
6357 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6358 "ConstantExpr has no value associated with it");
6359 (void)CE;
6360 } else {
6361 E = ConstantExpr::Create(Context, Result.get(), Value);
6362 }
6363 if (!PreNarrowingValue.isAbsent())
6364 Value = std::move(PreNarrowingValue);
6365 return E;
6366 }
6367 }
6368
6369 // It's not a constant expression. Produce an appropriate diagnostic.
6370 if (Notes.size() == 1 &&
6371 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6372 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6373 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6374 diag::note_constexpr_invalid_template_arg) {
6375 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6376 for (unsigned I = 0; I < Notes.size(); ++I)
6377 Diag(Notes[I].first, Notes[I].second);
6378 } else {
6379 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6380 << CCE << E->getSourceRange();
6381 for (unsigned I = 0; I < Notes.size(); ++I)
6382 Diag(Notes[I].first, Notes[I].second);
6383 }
6384 return ExprError();
6385}
6386
6387/// dropPointerConversions - If the given standard conversion sequence
6388/// involves any pointer conversions, remove them. This may change
6389/// the result type of the conversion sequence.
6391 if (SCS.Second == ICK_Pointer_Conversion) {
6392 SCS.Second = ICK_Identity;
6393 SCS.Element = ICK_Identity;
6394 SCS.Third = ICK_Identity;
6395 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6396 }
6397}
6398
6399/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6400/// convert the expression From to an Objective-C pointer type.
6403 // Do an implicit conversion to 'id'.
6406 = TryImplicitConversion(S, From, Ty,
6407 // FIXME: Are these flags correct?
6408 /*SuppressUserConversions=*/false,
6409 AllowedExplicit::Conversions,
6410 /*InOverloadResolution=*/false,
6411 /*CStyle=*/false,
6412 /*AllowObjCWritebackConversion=*/false,
6413 /*AllowObjCConversionOnExplicit=*/true);
6414
6415 // Strip off any final conversions to 'id'.
6416 switch (ICS.getKind()) {
6421 break;
6422
6425 break;
6426
6429 break;
6430 }
6431
6432 return ICS;
6433}
6434
6435/// PerformContextuallyConvertToObjCPointer - Perform a contextual
6436/// conversion of the expression From to an Objective-C pointer type.
6437/// Returns a valid but null ExprResult if no conversion sequence exists.
6439 if (checkPlaceholderForOverload(*this, From))
6440 return ExprError();
6441
6442 QualType Ty = Context.getObjCIdType();
6445 if (!ICS.isBad())
6446 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6447 return ExprResult();
6448}
6449
6450static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6451 const Expr *Base = nullptr;
6452 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6453 "expected a member expression");
6454
6455 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6456 M && !M->isImplicitAccess())
6457 Base = M->getBase();
6458 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6459 M && !M->isImplicitAccess())
6460 Base = M->getBase();
6461
6462 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6463
6464 if (T->isPointerType())
6465 T = T->getPointeeType();
6466
6467 return T;
6468}
6469
6471 const FunctionDecl *Fun) {
6472 QualType ObjType = Obj->getType();
6473 if (ObjType->isPointerType()) {
6474 ObjType = ObjType->getPointeeType();
6475 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6477 /*CanOverflow=*/false, FPOptionsOverride());
6478 }
6479 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6481 ObjType, Obj,
6483 }
6484 return Obj;
6485}
6486
6488 FunctionDecl *Fun) {
6489 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6492 Obj->getExprLoc(), Obj);
6493}
6494
6496 Expr *Object, MultiExprArg &Args,
6497 SmallVectorImpl<Expr *> &NewArgs) {
6498 assert(Method->isExplicitObjectMemberFunction() &&
6499 "Method is not an explicit member function");
6500 assert(NewArgs.empty() && "NewArgs should be empty");
6501 NewArgs.reserve(Args.size() + 1);
6502 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6503 NewArgs.push_back(This);
6504 NewArgs.append(Args.begin(), Args.end());
6505 Args = NewArgs;
6506}
6507
6508/// Determine whether the provided type is an integral type, or an enumeration
6509/// type of a permitted flavor.
6511 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6513}
6514
6515static ExprResult
6518 QualType T, UnresolvedSetImpl &ViableConversions) {
6519
6520 if (Converter.Suppress)
6521 return ExprError();
6522
6523 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6524 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6525 CXXConversionDecl *Conv =
6526 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6528 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6529 }
6530 return From;
6531}
6532
6533static bool
6536 QualType T, bool HadMultipleCandidates,
6537 UnresolvedSetImpl &ExplicitConversions) {
6538 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6539 DeclAccessPair Found = ExplicitConversions[0];
6540 CXXConversionDecl *Conversion =
6541 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6542
6543 // The user probably meant to invoke the given explicit
6544 // conversion; use it.
6545 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6546 std::string TypeStr;
6547 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6548
6549 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6551 "static_cast<" + TypeStr + ">(")
6553 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6554 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6555
6556 // If we aren't in a SFINAE context, build a call to the
6557 // explicit conversion function.
6558 if (SemaRef.isSFINAEContext())
6559 return true;
6560
6561 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6562 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6563 HadMultipleCandidates);
6564 if (Result.isInvalid())
6565 return true;
6566
6567 // Replace the conversion with a RecoveryExpr, so we don't try to
6568 // instantiate it later, but can further diagnose here.
6569 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6570 From, Result.get()->getType());
6571 if (Result.isInvalid())
6572 return true;
6573 From = Result.get();
6574 }
6575 return false;
6576}
6577
6578static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6580 QualType T, bool HadMultipleCandidates,
6581 DeclAccessPair &Found) {
6582 CXXConversionDecl *Conversion =
6583 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6584 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6585
6586 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6587 if (!Converter.SuppressConversion) {
6588 if (SemaRef.isSFINAEContext())
6589 return true;
6590
6591 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6592 << From->getSourceRange();
6593 }
6594
6595 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6596 HadMultipleCandidates);
6597 if (Result.isInvalid())
6598 return true;
6599 // Record usage of conversion in an implicit cast.
6600 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6601 CK_UserDefinedConversion, Result.get(),
6602 nullptr, Result.get()->getValueKind(),
6603 SemaRef.CurFPFeatureOverrides());
6604 return false;
6605}
6606
6608 Sema &SemaRef, SourceLocation Loc, Expr *From,
6610 if (!Converter.match(From->getType()) && !Converter.Suppress)
6611 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6612 << From->getSourceRange();
6613
6614 return SemaRef.DefaultLvalueConversion(From);
6615}
6616
6617static void
6619 UnresolvedSetImpl &ViableConversions,
6620 OverloadCandidateSet &CandidateSet) {
6621 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6622 DeclAccessPair FoundDecl = ViableConversions[I];
6623 NamedDecl *D = FoundDecl.getDecl();
6624 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6625 if (isa<UsingShadowDecl>(D))
6626 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6627
6628 CXXConversionDecl *Conv;
6629 FunctionTemplateDecl *ConvTemplate;
6630 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6631 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6632 else
6633 Conv = cast<CXXConversionDecl>(D);
6634
6635 if (ConvTemplate)
6637 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6638 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6639 else
6640 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6641 ToType, CandidateSet,
6642 /*AllowObjCConversionOnExplicit=*/false,
6643 /*AllowExplicit*/ true);
6644 }
6645}
6646
6647/// Attempt to convert the given expression to a type which is accepted
6648/// by the given converter.
6649///
6650/// This routine will attempt to convert an expression of class type to a
6651/// type accepted by the specified converter. In C++11 and before, the class
6652/// must have a single non-explicit conversion function converting to a matching
6653/// type. In C++1y, there can be multiple such conversion functions, but only
6654/// one target type.
6655///
6656/// \param Loc The source location of the construct that requires the
6657/// conversion.
6658///
6659/// \param From The expression we're converting from.
6660///
6661/// \param Converter Used to control and diagnose the conversion process.
6662///
6663/// \returns The expression, converted to an integral or enumeration type if
6664/// successful.
6666 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6667 // We can't perform any more checking for type-dependent expressions.
6668 if (From->isTypeDependent())
6669 return From;
6670
6671 // Process placeholders immediately.
6672 if (From->hasPlaceholderType()) {
6673 ExprResult result = CheckPlaceholderExpr(From);
6674 if (result.isInvalid())
6675 return result;
6676 From = result.get();
6677 }
6678
6679 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6680 ExprResult Converted = DefaultLvalueConversion(From);
6681 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6682 // If the expression already has a matching type, we're golden.
6683 if (Converter.match(T))
6684 return Converted;
6685
6686 // FIXME: Check for missing '()' if T is a function type?
6687
6688 // We can only perform contextual implicit conversions on objects of class
6689 // type.
6690 const RecordType *RecordTy = T->getAs<RecordType>();
6691 if (!RecordTy || !getLangOpts().CPlusPlus) {
6692 if (!Converter.Suppress)
6693 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6694 return From;
6695 }
6696
6697 // We must have a complete class type.
6698 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6699 ContextualImplicitConverter &Converter;
6700 Expr *From;
6701
6702 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6703 : Converter(Converter), From(From) {}
6704
6705 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6706 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6707 }
6708 } IncompleteDiagnoser(Converter, From);
6709
6710 if (Converter.Suppress ? !isCompleteType(Loc, T)
6711 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6712 return From;
6713
6714 // Look for a conversion to an integral or enumeration type.
6716 ViableConversions; // These are *potentially* viable in C++1y.
6717 UnresolvedSet<4> ExplicitConversions;
6718 const auto &Conversions =
6719 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6720
6721 bool HadMultipleCandidates =
6722 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6723
6724 // To check that there is only one target type, in C++1y:
6725 QualType ToType;
6726 bool HasUniqueTargetType = true;
6727
6728 // Collect explicit or viable (potentially in C++1y) conversions.
6729 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6730 NamedDecl *D = (*I)->getUnderlyingDecl();
6731 CXXConversionDecl *Conversion;
6732 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6733 if (ConvTemplate) {
6734 if (getLangOpts().CPlusPlus14)
6735 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6736 else
6737 continue; // C++11 does not consider conversion operator templates(?).
6738 } else
6739 Conversion = cast<CXXConversionDecl>(D);
6740
6741 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6742 "Conversion operator templates are considered potentially "
6743 "viable in C++1y");
6744
6745 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6746 if (Converter.match(CurToType) || ConvTemplate) {
6747
6748 if (Conversion->isExplicit()) {
6749 // FIXME: For C++1y, do we need this restriction?
6750 // cf. diagnoseNoViableConversion()
6751 if (!ConvTemplate)
6752 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6753 } else {
6754 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6755 if (ToType.isNull())
6756 ToType = CurToType.getUnqualifiedType();
6757 else if (HasUniqueTargetType &&
6758 (CurToType.getUnqualifiedType() != ToType))
6759 HasUniqueTargetType = false;
6760 }
6761 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6762 }
6763 }
6764 }
6765
6766 if (getLangOpts().CPlusPlus14) {
6767 // C++1y [conv]p6:
6768 // ... An expression e of class type E appearing in such a context
6769 // is said to be contextually implicitly converted to a specified
6770 // type T and is well-formed if and only if e can be implicitly
6771 // converted to a type T that is determined as follows: E is searched
6772 // for conversion functions whose return type is cv T or reference to
6773 // cv T such that T is allowed by the context. There shall be
6774 // exactly one such T.
6775
6776 // If no unique T is found:
6777 if (ToType.isNull()) {
6778 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6779 HadMultipleCandidates,
6780 ExplicitConversions))
6781 return ExprError();
6782 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6783 }
6784
6785 // If more than one unique Ts are found:
6786 if (!HasUniqueTargetType)
6787 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6788 ViableConversions);
6789
6790 // If one unique T is found:
6791 // First, build a candidate set from the previously recorded
6792 // potentially viable conversions.
6794 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6795 CandidateSet);
6796
6797 // Then, perform overload resolution over the candidate set.
6799 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6800 case OR_Success: {
6801 // Apply this conversion.
6802 DeclAccessPair Found =
6803 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6804 if (recordConversion(*this, Loc, From, Converter, T,
6805 HadMultipleCandidates, Found))
6806 return ExprError();
6807 break;
6808 }
6809 case OR_Ambiguous:
6810 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6811 ViableConversions);
6813 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6814 HadMultipleCandidates,
6815 ExplicitConversions))
6816 return ExprError();
6817 [[fallthrough]];
6818 case OR_Deleted:
6819 // We'll complain below about a non-integral condition type.
6820 break;
6821 }
6822 } else {
6823 switch (ViableConversions.size()) {
6824 case 0: {
6825 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6826 HadMultipleCandidates,
6827 ExplicitConversions))
6828 return ExprError();
6829
6830 // We'll complain below about a non-integral condition type.
6831 break;
6832 }
6833 case 1: {
6834 // Apply this conversion.
6835 DeclAccessPair Found = ViableConversions[0];
6836 if (recordConversion(*this, Loc, From, Converter, T,
6837 HadMultipleCandidates, Found))
6838 return ExprError();
6839 break;
6840 }
6841 default:
6842 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6843 ViableConversions);
6844 }
6845 }
6846
6847 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6848}
6849
6850/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6851/// an acceptable non-member overloaded operator for a call whose
6852/// arguments have types T1 (and, if non-empty, T2). This routine
6853/// implements the check in C++ [over.match.oper]p3b2 concerning
6854/// enumeration types.
6856 FunctionDecl *Fn,
6857 ArrayRef<Expr *> Args) {
6858 QualType T1 = Args[0]->getType();
6859 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6860
6861 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6862 return true;
6863
6864 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6865 return true;
6866
6867 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6868 if (Proto->getNumParams() < 1)
6869 return false;
6870
6871 if (T1->isEnumeralType()) {
6872 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6873 if (Context.hasSameUnqualifiedType(T1, ArgType))
6874 return true;
6875 }
6876
6877 if (Proto->getNumParams() < 2)
6878 return false;
6879
6880 if (!T2.isNull() && T2->isEnumeralType()) {
6881 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6882 if (Context.hasSameUnqualifiedType(T2, ArgType))
6883 return true;
6884 }
6885
6886 return false;
6887}
6888
6891 return false;
6892
6893 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6894 return FD->isTargetMultiVersion();
6895
6896 if (!FD->isMultiVersion())
6897 return false;
6898
6899 // Among multiple target versions consider either the default,
6900 // or the first non-default in the absence of default version.
6901 unsigned SeenAt = 0;
6902 unsigned I = 0;
6903 bool HasDefault = false;
6905 FD, [&](const FunctionDecl *CurFD) {
6906 if (FD == CurFD)
6907 SeenAt = I;
6908 else if (CurFD->isTargetMultiVersionDefault())
6909 HasDefault = true;
6910 ++I;
6911 });
6912 return HasDefault || SeenAt != 0;
6913}
6914
6915/// AddOverloadCandidate - Adds the given function to the set of
6916/// candidate functions, using the given function call arguments. If
6917/// @p SuppressUserConversions, then don't allow user-defined
6918/// conversions via constructors or conversion operators.
6919///
6920/// \param PartialOverloading true if we are performing "partial" overloading
6921/// based on an incomplete set of function arguments. This feature is used by
6922/// code completion.
6925 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6926 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6927 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6928 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6929 const FunctionProtoType *Proto
6930 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6931 assert(Proto && "Functions without a prototype cannot be overloaded");
6932 assert(!Function->getDescribedFunctionTemplate() &&
6933 "Use AddTemplateOverloadCandidate for function templates");
6934
6935 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6936 if (!isa<CXXConstructorDecl>(Method)) {
6937 // If we get here, it's because we're calling a member function
6938 // that is named without a member access expression (e.g.,
6939 // "this->f") that was either written explicitly or created
6940 // implicitly. This can happen with a qualified call to a member
6941 // function, e.g., X::f(). We use an empty type for the implied
6942 // object argument (C++ [over.call.func]p3), and the acting context
6943 // is irrelevant.
6944 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6946 CandidateSet, SuppressUserConversions,
6947 PartialOverloading, EarlyConversions, PO);
6948 return;
6949 }
6950 // We treat a constructor like a non-member function, since its object
6951 // argument doesn't participate in overload resolution.
6952 }
6953
6954 if (!CandidateSet.isNewCandidate(Function, PO))
6955 return;
6956
6957 // C++11 [class.copy]p11: [DR1402]
6958 // A defaulted move constructor that is defined as deleted is ignored by
6959 // overload resolution.
6960 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6961 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6962 Constructor->isMoveConstructor())
6963 return;
6964
6965 // Overload resolution is always an unevaluated context.
6968
6969 // C++ [over.match.oper]p3:
6970 // if no operand has a class type, only those non-member functions in the
6971 // lookup set that have a first parameter of type T1 or "reference to
6972 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6973 // is a right operand) a second parameter of type T2 or "reference to
6974 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6975 // candidate functions.
6976 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6978 return;
6979
6980 // Add this candidate
6981 OverloadCandidate &Candidate =
6982 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6983 Candidate.FoundDecl = FoundDecl;
6984 Candidate.Function = Function;
6985 Candidate.Viable = true;
6986 Candidate.RewriteKind =
6987 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6988 Candidate.IsSurrogate = false;
6989 Candidate.IsADLCandidate = IsADLCandidate;
6990 Candidate.IgnoreObjectArgument = false;
6991 Candidate.ExplicitCallArguments = Args.size();
6992
6993 // Explicit functions are not actually candidates at all if we're not
6994 // allowing them in this context, but keep them around so we can point
6995 // to them in diagnostics.
6996 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6997 Candidate.Viable = false;
6998 Candidate.FailureKind = ovl_fail_explicit;
6999 return;
7000 }
7001
7002 // Functions with internal linkage are only viable in the same module unit.
7003 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7004 /// FIXME: Currently, the semantics of linkage in clang is slightly
7005 /// different from the semantics in C++ spec. In C++ spec, only names
7006 /// have linkage. So that all entities of the same should share one
7007 /// linkage. But in clang, different entities of the same could have
7008 /// different linkage.
7009 NamedDecl *ND = Function;
7010 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
7011 ND = SpecInfo->getTemplate();
7012
7013 if (ND->getFormalLinkage() == Linkage::Internal) {
7014 Candidate.Viable = false;
7016 return;
7017 }
7018 }
7019
7021 Candidate.Viable = false;
7023 return;
7024 }
7025
7026 if (Constructor) {
7027 // C++ [class.copy]p3:
7028 // A member function template is never instantiated to perform the copy
7029 // of a class object to an object of its class type.
7030 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7031 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7032 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7033 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7034 ClassType))) {
7035 Candidate.Viable = false;
7037 return;
7038 }
7039
7040 // C++ [over.match.funcs]p8: (proposed DR resolution)
7041 // A constructor inherited from class type C that has a first parameter
7042 // of type "reference to P" (including such a constructor instantiated
7043 // from a template) is excluded from the set of candidate functions when
7044 // constructing an object of type cv D if the argument list has exactly
7045 // one argument and D is reference-related to P and P is reference-related
7046 // to C.
7047 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7048 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7049 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7050 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7051 QualType C = Context.getRecordType(Constructor->getParent());
7052 QualType D = Context.getRecordType(Shadow->getParent());
7053 SourceLocation Loc = Args.front()->getExprLoc();
7054 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7055 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7056 Candidate.Viable = false;
7058 return;
7059 }
7060 }
7061
7062 // Check that the constructor is capable of constructing an object in the
7063 // destination address space.
7065 Constructor->getMethodQualifiers().getAddressSpace(),
7066 CandidateSet.getDestAS())) {
7067 Candidate.Viable = false;
7069 }
7070 }
7071
7072 unsigned NumParams = Proto->getNumParams();
7073
7074 // (C++ 13.3.2p2): A candidate function having fewer than m
7075 // parameters is viable only if it has an ellipsis in its parameter
7076 // list (8.3.5).
7077 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7078 !Proto->isVariadic() &&
7079 shouldEnforceArgLimit(PartialOverloading, Function)) {
7080 Candidate.Viable = false;
7082 return;
7083 }
7084
7085 // (C++ 13.3.2p2): A candidate function having more than m parameters
7086 // is viable only if the (m+1)st parameter has a default argument
7087 // (8.3.6). For the purposes of overload resolution, the
7088 // parameter list is truncated on the right, so that there are
7089 // exactly m parameters.
7090 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7091 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7092 !PartialOverloading) {
7093 // Not enough arguments.
7094 Candidate.Viable = false;
7096 return;
7097 }
7098
7099 // (CUDA B.1): Check for invalid calls between targets.
7100 if (getLangOpts().CUDA) {
7101 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7102 // Skip the check for callers that are implicit members, because in this
7103 // case we may not yet know what the member's target is; the target is
7104 // inferred for the member automatically, based on the bases and fields of
7105 // the class.
7106 if (!(Caller && Caller->isImplicit()) &&
7107 !CUDA().IsAllowedCall(Caller, Function)) {
7108 Candidate.Viable = false;
7109 Candidate.FailureKind = ovl_fail_bad_target;
7110 return;
7111 }
7112 }
7113
7114 if (Function->getTrailingRequiresClause()) {
7115 ConstraintSatisfaction Satisfaction;
7116 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7117 /*ForOverloadResolution*/ true) ||
7118 !Satisfaction.IsSatisfied) {
7119 Candidate.Viable = false;
7121 return;
7122 }
7123 }
7124
7125 // Determine the implicit conversion sequences for each of the
7126 // arguments.
7127 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7128 unsigned ConvIdx =
7129 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7130 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7131 // We already formed a conversion sequence for this parameter during
7132 // template argument deduction.
7133 } else if (ArgIdx < NumParams) {
7134 // (C++ 13.3.2p3): for F to be a viable function, there shall
7135 // exist for each argument an implicit conversion sequence
7136 // (13.3.3.1) that converts that argument to the corresponding
7137 // parameter of F.
7138 QualType ParamType = Proto->getParamType(ArgIdx);
7139 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7140 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7141 /*InOverloadResolution=*/true,
7142 /*AllowObjCWritebackConversion=*/
7143 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7144 if (Candidate.Conversions[ConvIdx].isBad()) {
7145 Candidate.Viable = false;
7147 return;
7148 }
7149 } else {
7150 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7151 // argument for which there is no corresponding parameter is
7152 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7153 Candidate.Conversions[ConvIdx].setEllipsis();
7154 }
7155 }
7156
7157 if (EnableIfAttr *FailedAttr =
7158 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7159 Candidate.Viable = false;
7160 Candidate.FailureKind = ovl_fail_enable_if;
7161 Candidate.DeductionFailure.Data = FailedAttr;
7162 return;
7163 }
7164}
7165
7167Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7169 if (Methods.size() <= 1)
7170 return nullptr;
7171
7172 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7173 bool Match = true;
7174 ObjCMethodDecl *Method = Methods[b];
7175 unsigned NumNamedArgs = Sel.getNumArgs();
7176 // Method might have more arguments than selector indicates. This is due
7177 // to addition of c-style arguments in method.
7178 if (Method->param_size() > NumNamedArgs)
7179 NumNamedArgs = Method->param_size();
7180 if (Args.size() < NumNamedArgs)
7181 continue;
7182
7183 for (unsigned i = 0; i < NumNamedArgs; i++) {
7184 // We can't do any type-checking on a type-dependent argument.
7185 if (Args[i]->isTypeDependent()) {
7186 Match = false;
7187 break;
7188 }
7189
7190 ParmVarDecl *param = Method->parameters()[i];
7191 Expr *argExpr = Args[i];
7192 assert(argExpr && "SelectBestMethod(): missing expression");
7193
7194 // Strip the unbridged-cast placeholder expression off unless it's
7195 // a consumed argument.
7196 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7197 !param->hasAttr<CFConsumedAttr>())
7198 argExpr = stripARCUnbridgedCast(argExpr);
7199
7200 // If the parameter is __unknown_anytype, move on to the next method.
7201 if (param->getType() == Context.UnknownAnyTy) {
7202 Match = false;
7203 break;
7204 }
7205
7206 ImplicitConversionSequence ConversionState
7207 = TryCopyInitialization(*this, argExpr, param->getType(),
7208 /*SuppressUserConversions*/false,
7209 /*InOverloadResolution=*/true,
7210 /*AllowObjCWritebackConversion=*/
7211 getLangOpts().ObjCAutoRefCount,
7212 /*AllowExplicit*/false);
7213 // This function looks for a reasonably-exact match, so we consider
7214 // incompatible pointer conversions to be a failure here.
7215 if (ConversionState.isBad() ||
7216 (ConversionState.isStandard() &&
7217 ConversionState.Standard.Second ==
7219 Match = false;
7220 break;
7221 }
7222 }
7223 // Promote additional arguments to variadic methods.
7224 if (Match && Method->isVariadic()) {
7225 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7226 if (Args[i]->isTypeDependent()) {
7227 Match = false;
7228 break;
7229 }
7230 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7231 nullptr);
7232 if (Arg.isInvalid()) {
7233 Match = false;
7234 break;
7235 }
7236 }
7237 } else {
7238 // Check for extra arguments to non-variadic methods.
7239 if (Args.size() != NumNamedArgs)
7240 Match = false;
7241 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7242 // Special case when selectors have no argument. In this case, select
7243 // one with the most general result type of 'id'.
7244 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7245 QualType ReturnT = Methods[b]->getReturnType();
7246 if (ReturnT->isObjCIdType())
7247 return Methods[b];
7248 }
7249 }
7250 }
7251
7252 if (Match)
7253 return Method;
7254 }
7255 return nullptr;
7256}
7257
7259 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7260 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7261 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7262 if (ThisArg) {
7263 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7264 assert(!isa<CXXConstructorDecl>(Method) &&
7265 "Shouldn't have `this` for ctors!");
7266 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7268 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7269 if (R.isInvalid())
7270 return false;
7271 ConvertedThis = R.get();
7272 } else {
7273 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7274 (void)MD;
7275 assert((MissingImplicitThis || MD->isStatic() ||
7276 isa<CXXConstructorDecl>(MD)) &&
7277 "Expected `this` for non-ctor instance methods");
7278 }
7279 ConvertedThis = nullptr;
7280 }
7281
7282 // Ignore any variadic arguments. Converting them is pointless, since the
7283 // user can't refer to them in the function condition.
7284 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7285
7286 // Convert the arguments.
7287 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7288 ExprResult R;
7290 S.Context, Function->getParamDecl(I)),
7291 SourceLocation(), Args[I]);
7292
7293 if (R.isInvalid())
7294 return false;
7295
7296 ConvertedArgs.push_back(R.get());
7297 }
7298
7299 if (Trap.hasErrorOccurred())
7300 return false;
7301
7302 // Push default arguments if needed.
7303 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7304 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7305 ParmVarDecl *P = Function->getParamDecl(i);
7306 if (!P->hasDefaultArg())
7307 return false;
7309 if (R.isInvalid())
7310 return false;
7311 ConvertedArgs.push_back(R.get());
7312 }
7313
7314 if (Trap.hasErrorOccurred())
7315 return false;
7316 }
7317 return true;
7318}
7319
7321 SourceLocation CallLoc,
7322 ArrayRef<Expr *> Args,
7323 bool MissingImplicitThis) {
7324 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7325 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7326 return nullptr;
7327
7328 SFINAETrap Trap(*this);
7329 SmallVector<Expr *, 16> ConvertedArgs;
7330 // FIXME: We should look into making enable_if late-parsed.
7331 Expr *DiscardedThis;
7333 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7334 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7335 return *EnableIfAttrs.begin();
7336
7337 for (auto *EIA : EnableIfAttrs) {
7339 // FIXME: This doesn't consider value-dependent cases, because doing so is
7340 // very difficult. Ideally, we should handle them more gracefully.
7341 if (EIA->getCond()->isValueDependent() ||
7342 !EIA->getCond()->EvaluateWithSubstitution(
7343 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7344 return EIA;
7345
7346 if (!Result.isInt() || !Result.getInt().getBoolValue())
7347 return EIA;
7348 }
7349 return nullptr;
7350}
7351
7352template <typename CheckFn>
7354 bool ArgDependent, SourceLocation Loc,
7355 CheckFn &&IsSuccessful) {
7357 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7358 if (ArgDependent == DIA->getArgDependent())
7359 Attrs.push_back(DIA);
7360 }
7361
7362 // Common case: No diagnose_if attributes, so we can quit early.
7363 if (Attrs.empty())
7364 return false;
7365
7366 auto WarningBegin = std::stable_partition(
7367 Attrs.begin(), Attrs.end(),
7368 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7369
7370 // Note that diagnose_if attributes are late-parsed, so they appear in the
7371 // correct order (unlike enable_if attributes).
7372 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7373 IsSuccessful);
7374 if (ErrAttr != WarningBegin) {
7375 const DiagnoseIfAttr *DIA = *ErrAttr;
7376 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7377 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7378 << DIA->getParent() << DIA->getCond()->getSourceRange();
7379 return true;
7380 }
7381
7382 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7383 if (IsSuccessful(DIA)) {
7384 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7385 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7386 << DIA->getParent() << DIA->getCond()->getSourceRange();
7387 }
7388
7389 return false;
7390}
7391
7393 const Expr *ThisArg,
7395 SourceLocation Loc) {
7397 *this, Function, /*ArgDependent=*/true, Loc,
7398 [&](const DiagnoseIfAttr *DIA) {
7400 // It's sane to use the same Args for any redecl of this function, since
7401 // EvaluateWithSubstitution only cares about the position of each
7402 // argument in the arg list, not the ParmVarDecl* it maps to.
7403 if (!DIA->getCond()->EvaluateWithSubstitution(
7404 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7405 return false;
7406 return Result.isInt() && Result.getInt().getBoolValue();
7407 });
7408}
7409
7411 SourceLocation Loc) {
7413 *this, ND, /*ArgDependent=*/false, Loc,
7414 [&](const DiagnoseIfAttr *DIA) {
7415 bool Result;
7416 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7417 Result;
7418 });
7419}
7420
7421/// Add all of the function declarations in the given function set to
7422/// the overload candidate set.
7424 ArrayRef<Expr *> Args,
7425 OverloadCandidateSet &CandidateSet,
7426 TemplateArgumentListInfo *ExplicitTemplateArgs,
7427 bool SuppressUserConversions,
7428 bool PartialOverloading,
7429 bool FirstArgumentIsBase) {
7430 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7431 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7432 ArrayRef<Expr *> FunctionArgs = Args;
7433
7434 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7435 FunctionDecl *FD =
7436 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7437
7438 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7439 QualType ObjectType;
7440 Expr::Classification ObjectClassification;
7441 if (Args.size() > 0) {
7442 if (Expr *E = Args[0]) {
7443 // Use the explicit base to restrict the lookup:
7444 ObjectType = E->getType();
7445 // Pointers in the object arguments are implicitly dereferenced, so we
7446 // always classify them as l-values.
7447 if (!ObjectType.isNull() && ObjectType->isPointerType())
7448 ObjectClassification = Expr::Classification::makeSimpleLValue();
7449 else
7450 ObjectClassification = E->Classify(Context);
7451 } // .. else there is an implicit base.
7452 FunctionArgs = Args.slice(1);
7453 }
7454 if (FunTmpl) {
7455 AddMethodTemplateCandidate(
7456 FunTmpl, F.getPair(),
7457 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7458 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7459 FunctionArgs, CandidateSet, SuppressUserConversions,
7460 PartialOverloading);
7461 } else {
7462 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7463 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7464 ObjectClassification, FunctionArgs, CandidateSet,
7465 SuppressUserConversions, PartialOverloading);
7466 }
7467 } else {
7468 // This branch handles both standalone functions and static methods.
7469
7470 // Slice the first argument (which is the base) when we access
7471 // static method as non-static.
7472 if (Args.size() > 0 &&
7473 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7474 !isa<CXXConstructorDecl>(FD)))) {
7475 assert(cast<CXXMethodDecl>(FD)->isStatic());
7476 FunctionArgs = Args.slice(1);
7477 }
7478 if (FunTmpl) {
7479 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7480 ExplicitTemplateArgs, FunctionArgs,
7481 CandidateSet, SuppressUserConversions,
7482 PartialOverloading);
7483 } else {
7484 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7485 SuppressUserConversions, PartialOverloading);
7486 }
7487 }
7488 }
7489}
7490
7491/// AddMethodCandidate - Adds a named decl (which is some kind of
7492/// method) as a method candidate to the given overload set.
7494 Expr::Classification ObjectClassification,
7495 ArrayRef<Expr *> Args,
7496 OverloadCandidateSet &CandidateSet,
7497 bool SuppressUserConversions,
7499 NamedDecl *Decl = FoundDecl.getDecl();
7500 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7501
7502 if (isa<UsingShadowDecl>(Decl))
7503 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7504
7505 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7506 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7507 "Expected a member function template");
7508 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7509 /*ExplicitArgs*/ nullptr, ObjectType,
7510 ObjectClassification, Args, CandidateSet,
7511 SuppressUserConversions, false, PO);
7512 } else {
7513 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7514 ObjectType, ObjectClassification, Args, CandidateSet,
7515 SuppressUserConversions, false, std::nullopt, PO);
7516 }
7517}
7518
7519/// AddMethodCandidate - Adds the given C++ member function to the set
7520/// of candidate functions, using the given function call arguments
7521/// and the object argument (@c Object). For example, in a call
7522/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7523/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7524/// allow user-defined conversions via constructors or conversion
7525/// operators.
7526void
7528 CXXRecordDecl *ActingContext, QualType ObjectType,
7529 Expr::Classification ObjectClassification,
7530 ArrayRef<Expr *> Args,
7531 OverloadCandidateSet &CandidateSet,
7532 bool SuppressUserConversions,
7533 bool PartialOverloading,
7534 ConversionSequenceList EarlyConversions,
7536 const FunctionProtoType *Proto
7537 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7538 assert(Proto && "Methods without a prototype cannot be overloaded");
7539 assert(!isa<CXXConstructorDecl>(Method) &&
7540 "Use AddOverloadCandidate for constructors");
7541
7542 if (!CandidateSet.isNewCandidate(Method, PO))
7543 return;
7544
7545 // C++11 [class.copy]p23: [DR1402]
7546 // A defaulted move assignment operator that is defined as deleted is
7547 // ignored by overload resolution.
7548 if (Method->isDefaulted() && Method->isDeleted() &&
7549 Method->isMoveAssignmentOperator())
7550 return;
7551
7552 // Overload resolution is always an unevaluated context.
7555
7556 // Add this candidate
7557 OverloadCandidate &Candidate =
7558 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7559 Candidate.FoundDecl = FoundDecl;
7560 Candidate.Function = Method;
7561 Candidate.RewriteKind =
7562 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7563 Candidate.IsSurrogate = false;
7564 Candidate.IgnoreObjectArgument = false;
7565 Candidate.ExplicitCallArguments = Args.size();
7566
7567 unsigned NumParams = Method->getNumExplicitParams();
7568 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7569
7570 // (C++ 13.3.2p2): A candidate function having fewer than m
7571 // parameters is viable only if it has an ellipsis in its parameter
7572 // list (8.3.5).
7573 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7574 !Proto->isVariadic() &&
7575 shouldEnforceArgLimit(PartialOverloading, Method)) {
7576 Candidate.Viable = false;
7578 return;
7579 }
7580
7581 // (C++ 13.3.2p2): A candidate function having more than m parameters
7582 // is viable only if the (m+1)st parameter has a default argument
7583 // (8.3.6). For the purposes of overload resolution, the
7584 // parameter list is truncated on the right, so that there are
7585 // exactly m parameters.
7586 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7587 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7588 // Not enough arguments.
7589 Candidate.Viable = false;
7591 return;
7592 }
7593
7594 Candidate.Viable = true;
7595
7596 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7597 if (ObjectType.isNull())
7598 Candidate.IgnoreObjectArgument = true;
7599 else if (Method->isStatic()) {
7600 // [over.best.ics.general]p8
7601 // When the parameter is the implicit object parameter of a static member
7602 // function, the implicit conversion sequence is a standard conversion
7603 // sequence that is neither better nor worse than any other standard
7604 // conversion sequence.
7605 //
7606 // This is a rule that was introduced in C++23 to support static lambdas. We
7607 // apply it retroactively because we want to support static lambdas as an
7608 // extension and it doesn't hurt previous code.
7609 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7610 } else {
7611 // Determine the implicit conversion sequence for the object
7612 // parameter.
7613 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7614 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7615 Method, ActingContext, /*InOverloadResolution=*/true);
7616 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7617 Candidate.Viable = false;
7619 return;
7620 }
7621 }
7622
7623 // (CUDA B.1): Check for invalid calls between targets.
7624 if (getLangOpts().CUDA)
7625 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7626 Method)) {
7627 Candidate.Viable = false;
7628 Candidate.FailureKind = ovl_fail_bad_target;
7629 return;
7630 }
7631
7632 if (Method->getTrailingRequiresClause()) {
7633 ConstraintSatisfaction Satisfaction;
7634 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7635 /*ForOverloadResolution*/ true) ||
7636 !Satisfaction.IsSatisfied) {
7637 Candidate.Viable = false;
7639 return;
7640 }
7641 }
7642
7643 // Determine the implicit conversion sequences for each of the
7644 // arguments.
7645 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7646 unsigned ConvIdx =
7647 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7648 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7649 // We already formed a conversion sequence for this parameter during
7650 // template argument deduction.
7651 } else if (ArgIdx < NumParams) {
7652 // (C++ 13.3.2p3): for F to be a viable function, there shall
7653 // exist for each argument an implicit conversion sequence
7654 // (13.3.3.1) that converts that argument to the corresponding
7655 // parameter of F.
7656 QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7657 Candidate.Conversions[ConvIdx]
7658 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7659 SuppressUserConversions,
7660 /*InOverloadResolution=*/true,
7661 /*AllowObjCWritebackConversion=*/
7662 getLangOpts().ObjCAutoRefCount);
7663 if (Candidate.Conversions[ConvIdx].isBad()) {
7664 Candidate.Viable = false;
7666 return;
7667 }
7668 } else {
7669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7670 // argument for which there is no corresponding parameter is
7671 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7672 Candidate.Conversions[ConvIdx].setEllipsis();
7673 }
7674 }
7675
7676 if (EnableIfAttr *FailedAttr =
7677 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7678 Candidate.Viable = false;
7679 Candidate.FailureKind = ovl_fail_enable_if;
7680 Candidate.DeductionFailure.Data = FailedAttr;
7681 return;
7682 }
7683
7684 if (isNonViableMultiVersionOverload(Method)) {
7685 Candidate.Viable = false;
7687 }
7688}
7689
7690/// Add a C++ member function template as a candidate to the candidate
7691/// set, using template argument deduction to produce an appropriate member
7692/// function template specialization.
7694 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7695 CXXRecordDecl *ActingContext,
7696 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7697 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7698 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7699 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7700 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7701 return;
7702
7703 // C++ [over.match.funcs]p7:
7704 // In each case where a candidate is a function template, candidate
7705 // function template specializations are generated using template argument
7706 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7707 // candidate functions in the usual way.113) A given name can refer to one
7708 // or more function templates and also to a set of overloaded non-template
7709 // functions. In such a case, the candidate functions generated from each
7710 // function template are combined with the set of non-template candidate
7711 // functions.
7712 TemplateDeductionInfo Info(CandidateSet.getLocation());
7713 FunctionDecl *Specialization = nullptr;
7714 ConversionSequenceList Conversions;
7716 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7717 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7718 ObjectClassification,
7719 [&](ArrayRef<QualType> ParamTypes) {
7720 return CheckNonDependentConversions(
7721 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7722 SuppressUserConversions, ActingContext, ObjectType,
7723 ObjectClassification, PO);
7724 });
7726 OverloadCandidate &Candidate =
7727 CandidateSet.addCandidate(Conversions.size(), Conversions);
7728 Candidate.FoundDecl = FoundDecl;
7729 Candidate.Function = MethodTmpl->getTemplatedDecl();
7730 Candidate.Viable = false;
7731 Candidate.RewriteKind =
7732 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7733 Candidate.IsSurrogate = false;
7734 Candidate.IgnoreObjectArgument =
7735 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7736 ObjectType.isNull();
7737 Candidate.ExplicitCallArguments = Args.size();
7740 else {
7743 Info);
7744 }
7745 return;
7746 }
7747
7748 // Add the function template specialization produced by template argument
7749 // deduction as a candidate.
7750 assert(Specialization && "Missing member function template specialization?");
7751 assert(isa<CXXMethodDecl>(Specialization) &&
7752 "Specialization is not a member function?");
7753 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7754 ActingContext, ObjectType, ObjectClassification, Args,
7755 CandidateSet, SuppressUserConversions, PartialOverloading,
7756 Conversions, PO);
7757}
7758
7759/// Determine whether a given function template has a simple explicit specifier
7760/// or a non-value-dependent explicit-specification that evaluates to true.
7763}
7764
7765/// Add a C++ function template specialization as a candidate
7766/// in the candidate set, using template argument deduction to produce
7767/// an appropriate function template specialization.
7769 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7770 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7771 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7772 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7773 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7774 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7775 return;
7776
7777 // If the function template has a non-dependent explicit specification,
7778 // exclude it now if appropriate; we are not permitted to perform deduction
7779 // and substitution in this case.
7780 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7781 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7782 Candidate.FoundDecl = FoundDecl;
7783 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7784 Candidate.Viable = false;
7785 Candidate.FailureKind = ovl_fail_explicit;
7786 return;
7787 }
7788
7789 // C++ [over.match.funcs]p7:
7790 // In each case where a candidate is a function template, candidate
7791 // function template specializations are generated using template argument
7792 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7793 // candidate functions in the usual way.113) A given name can refer to one
7794 // or more function templates and also to a set of overloaded non-template
7795 // functions. In such a case, the candidate functions generated from each
7796 // function template are combined with the set of non-template candidate
7797 // functions.
7798 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7799 FunctionTemplate->getTemplateDepth());
7800 FunctionDecl *Specialization = nullptr;
7801 ConversionSequenceList Conversions;
7803 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7804 PartialOverloading, AggregateCandidateDeduction,
7805 /*ObjectType=*/QualType(),
7806 /*ObjectClassification=*/Expr::Classification(),
7807 [&](ArrayRef<QualType> ParamTypes) {
7808 return CheckNonDependentConversions(
7809 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7810 SuppressUserConversions, nullptr, QualType(), {}, PO);
7811 });
7813 OverloadCandidate &Candidate =
7814 CandidateSet.addCandidate(Conversions.size(), Conversions);
7815 Candidate.FoundDecl = FoundDecl;
7816 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7817 Candidate.Viable = false;
7818 Candidate.RewriteKind =
7819 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7820 Candidate.IsSurrogate = false;
7821 Candidate.IsADLCandidate = IsADLCandidate;
7822 // Ignore the object argument if there is one, since we don't have an object
7823 // type.
7824 Candidate.IgnoreObjectArgument =
7825 isa<CXXMethodDecl>(Candidate.Function) &&
7826 !isa<CXXConstructorDecl>(Candidate.Function);
7827 Candidate.ExplicitCallArguments = Args.size();
7830 else {
7833 Info);
7834 }
7835 return;
7836 }
7837
7838 // Add the function template specialization produced by template argument
7839 // deduction as a candidate.
7840 assert(Specialization && "Missing function template specialization?");
7841 AddOverloadCandidate(
7842 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7843 PartialOverloading, AllowExplicit,
7844 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7846}
7847
7848/// Check that implicit conversion sequences can be formed for each argument
7849/// whose corresponding parameter has a non-dependent type, per DR1391's
7850/// [temp.deduct.call]p10.
7852 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7853 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7854 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7855 CXXRecordDecl *ActingContext, QualType ObjectType,
7856 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7857 // FIXME: The cases in which we allow explicit conversions for constructor
7858 // arguments never consider calling a constructor template. It's not clear
7859 // that is correct.
7860 const bool AllowExplicit = false;
7861
7862 auto *FD = FunctionTemplate->getTemplatedDecl();
7863 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7864 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7865 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7866
7867 Conversions =
7868 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7869
7870 // Overload resolution is always an unevaluated context.
7873
7874 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7875 // require that, but this check should never result in a hard error, and
7876 // overload resolution is permitted to sidestep instantiations.
7877 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7878 !ObjectType.isNull()) {
7879 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7880 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7881 !ParamTypes[0]->isDependentType()) {
7882 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7883 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7884 Method, ActingContext, /*InOverloadResolution=*/true,
7885 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7886 : QualType());
7887 if (Conversions[ConvIdx].isBad())
7888 return true;
7889 }
7890 }
7891
7892 unsigned Offset =
7893 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7894
7895 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7896 I != N; ++I) {
7897 QualType ParamType = ParamTypes[I + Offset];
7898 if (!ParamType->isDependentType()) {
7899 unsigned ConvIdx;
7901 ConvIdx = Args.size() - 1 - I;
7902 assert(Args.size() + ThisConversions == 2 &&
7903 "number of args (including 'this') must be exactly 2 for "
7904 "reversed order");
7905 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7906 // would also be 0. 'this' got ConvIdx = 1 previously.
7907 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7908 } else {
7909 // For members, 'this' got ConvIdx = 0 previously.
7910 ConvIdx = ThisConversions + I;
7911 }
7912 Conversions[ConvIdx]
7913 = TryCopyInitialization(*this, Args[I], ParamType,
7914 SuppressUserConversions,
7915 /*InOverloadResolution=*/true,
7916 /*AllowObjCWritebackConversion=*/
7917 getLangOpts().ObjCAutoRefCount,
7918 AllowExplicit);
7919 if (Conversions[ConvIdx].isBad())
7920 return true;
7921 }
7922 }
7923
7924 return false;
7925}
7926
7927/// Determine whether this is an allowable conversion from the result
7928/// of an explicit conversion operator to the expected type, per C++
7929/// [over.match.conv]p1 and [over.match.ref]p1.
7930///
7931/// \param ConvType The return type of the conversion function.
7932///
7933/// \param ToType The type we are converting to.
7934///
7935/// \param AllowObjCPointerConversion Allow a conversion from one
7936/// Objective-C pointer to another.
7937///
7938/// \returns true if the conversion is allowable, false otherwise.
7940 QualType ConvType, QualType ToType,
7941 bool AllowObjCPointerConversion) {
7942 QualType ToNonRefType = ToType.getNonReferenceType();
7943
7944 // Easy case: the types are the same.
7945 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7946 return true;
7947
7948 // Allow qualification conversions.
7949 bool ObjCLifetimeConversion;
7950 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7951 ObjCLifetimeConversion))
7952 return true;
7953
7954 // If we're not allowed to consider Objective-C pointer conversions,
7955 // we're done.
7956 if (!AllowObjCPointerConversion)
7957 return false;
7958
7959 // Is this an Objective-C pointer conversion?
7960 bool IncompatibleObjC = false;
7961 QualType ConvertedType;
7962 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7963 IncompatibleObjC);
7964}
7965
7966/// AddConversionCandidate - Add a C++ conversion function as a
7967/// candidate in the candidate set (C++ [over.match.conv],
7968/// C++ [over.match.copy]). From is the expression we're converting from,
7969/// and ToType is the type that we're eventually trying to convert to
7970/// (which may or may not be the same type as the type that the
7971/// conversion function produces).
7973 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7974 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7975 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7976 bool AllowExplicit, bool AllowResultConversion) {
7977 assert(!Conversion->getDescribedFunctionTemplate() &&
7978 "Conversion function templates use AddTemplateConversionCandidate");
7979 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7980 if (!CandidateSet.isNewCandidate(Conversion))
7981 return;
7982
7983 // If the conversion function has an undeduced return type, trigger its
7984 // deduction now.
7985 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7986 if (DeduceReturnType(Conversion, From->getExprLoc()))
7987 return;
7988 ConvType = Conversion->getConversionType().getNonReferenceType();
7989 }
7990
7991 // If we don't allow any conversion of the result type, ignore conversion
7992 // functions that don't convert to exactly (possibly cv-qualified) T.
7993 if (!AllowResultConversion &&
7994 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7995 return;
7996
7997 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7998 // operator is only a candidate if its return type is the target type or
7999 // can be converted to the target type with a qualification conversion.
8000 //
8001 // FIXME: Include such functions in the candidate list and explain why we
8002 // can't select them.
8003 if (Conversion->isExplicit() &&
8004 !isAllowableExplicitConversion(*this, ConvType, ToType,
8005 AllowObjCConversionOnExplicit))
8006 return;
8007
8008 // Overload resolution is always an unevaluated context.
8011
8012 // Add this candidate
8013 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8014 Candidate.FoundDecl = FoundDecl;
8015 Candidate.Function = Conversion;
8016 Candidate.IsSurrogate = false;
8017 Candidate.IgnoreObjectArgument = false;
8019 Candidate.FinalConversion.setFromType(ConvType);
8020 Candidate.FinalConversion.setAllToTypes(ToType);
8021 Candidate.Viable = true;
8022 Candidate.ExplicitCallArguments = 1;
8023
8024 // Explicit functions are not actually candidates at all if we're not
8025 // allowing them in this context, but keep them around so we can point
8026 // to them in diagnostics.
8027 if (!AllowExplicit && Conversion->isExplicit()) {
8028 Candidate.Viable = false;
8029 Candidate.FailureKind = ovl_fail_explicit;
8030 return;
8031 }
8032
8033 // C++ [over.match.funcs]p4:
8034 // For conversion functions, the function is considered to be a member of
8035 // the class of the implicit implied object argument for the purpose of
8036 // defining the type of the implicit object parameter.
8037 //
8038 // Determine the implicit conversion sequence for the implicit
8039 // object parameter.
8040 QualType ObjectType = From->getType();
8041 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8042 ObjectType = FromPtrType->getPointeeType();
8043 const auto *ConversionContext =
8044 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8045
8046 // C++23 [over.best.ics.general]
8047 // However, if the target is [...]
8048 // - the object parameter of a user-defined conversion function
8049 // [...] user-defined conversion sequences are not considered.
8051 *this, CandidateSet.getLocation(), From->getType(),
8052 From->Classify(Context), Conversion, ConversionContext,
8053 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8054 /*SuppressUserConversion*/ true);
8055
8056 if (Candidate.Conversions[0].isBad()) {
8057 Candidate.Viable = false;
8059 return;
8060 }
8061
8062 if (Conversion->getTrailingRequiresClause()) {
8063 ConstraintSatisfaction Satisfaction;
8064 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8065 !Satisfaction.IsSatisfied) {
8066 Candidate.Viable = false;
8068 return;
8069 }
8070 }
8071
8072 // We won't go through a user-defined type conversion function to convert a
8073 // derived to base as such conversions are given Conversion Rank. They only
8074 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8075 QualType FromCanon
8076 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8077 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8078 if (FromCanon == ToCanon ||
8079 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8080 Candidate.Viable = false;
8082 return;
8083 }
8084
8085 // To determine what the conversion from the result of calling the
8086 // conversion function to the type we're eventually trying to
8087 // convert to (ToType), we need to synthesize a call to the
8088 // conversion function and attempt copy initialization from it. This
8089 // makes sure that we get the right semantics with respect to
8090 // lvalues/rvalues and the type. Fortunately, we can allocate this
8091 // call on the stack and we don't need its arguments to be
8092 // well-formed.
8093 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8094 VK_LValue, From->getBeginLoc());
8096 Context.getPointerType(Conversion->getType()),
8097 CK_FunctionToPointerDecay, &ConversionRef,
8099
8100 QualType ConversionType = Conversion->getConversionType();
8101 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8102 Candidate.Viable = false;
8104 return;
8105 }
8106
8107 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8108
8109 // Note that it is safe to allocate CallExpr on the stack here because
8110 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8111 // allocator).
8112 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8113
8114 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8115 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8116 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8117
8119 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8120 /*SuppressUserConversions=*/true,
8121 /*InOverloadResolution=*/false,
8122 /*AllowObjCWritebackConversion=*/false);
8123
8124 switch (ICS.getKind()) {
8126 Candidate.FinalConversion = ICS.Standard;
8127
8128 // C++ [over.ics.user]p3:
8129 // If the user-defined conversion is specified by a specialization of a
8130 // conversion function template, the second standard conversion sequence
8131 // shall have exact match rank.
8132 if (Conversion->getPrimaryTemplate() &&
8134 Candidate.Viable = false;
8136 return;
8137 }
8138
8139 // C++0x [dcl.init.ref]p5:
8140 // In the second case, if the reference is an rvalue reference and
8141 // the second standard conversion sequence of the user-defined
8142 // conversion sequence includes an lvalue-to-rvalue conversion, the
8143 // program is ill-formed.
8144 if (ToType->isRValueReferenceType() &&
8146 Candidate.Viable = false;
8148 return;
8149 }
8150 break;
8151
8153 Candidate.Viable = false;
8155 return;
8156
8157 default:
8158 llvm_unreachable(
8159 "Can only end up with a standard conversion sequence or failure");
8160 }
8161
8162 if (EnableIfAttr *FailedAttr =
8163 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8164 Candidate.Viable = false;
8165 Candidate.FailureKind = ovl_fail_enable_if;
8166 Candidate.DeductionFailure.Data = FailedAttr;
8167 return;
8168 }
8169
8170 if (isNonViableMultiVersionOverload(Conversion)) {
8171 Candidate.Viable = false;
8173 }
8174}
8175
8176/// Adds a conversion function template specialization
8177/// candidate to the overload set, using template argument deduction
8178/// to deduce the template arguments of the conversion function
8179/// template from the type that we are converting to (C++
8180/// [temp.deduct.conv]).
8182 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8183 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8184 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8185 bool AllowExplicit, bool AllowResultConversion) {
8186 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8187 "Only conversion function templates permitted here");
8188
8189 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8190 return;
8191
8192 // If the function template has a non-dependent explicit specification,
8193 // exclude it now if appropriate; we are not permitted to perform deduction
8194 // and substitution in this case.
8195 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8196 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8197 Candidate.FoundDecl = FoundDecl;
8198 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8199 Candidate.Viable = false;
8200 Candidate.FailureKind = ovl_fail_explicit;
8201 return;
8202 }
8203
8204 QualType ObjectType = From->getType();
8205 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8206
8207 TemplateDeductionInfo Info(CandidateSet.getLocation());
8210 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8211 Specialization, Info);
8213 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8214 Candidate.FoundDecl = FoundDecl;
8215 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8216 Candidate.Viable = false;
8218 Candidate.IsSurrogate = false;
8219 Candidate.IgnoreObjectArgument = false;
8220 Candidate.ExplicitCallArguments = 1;
8222 Info);
8223 return;
8224 }
8225
8226 // Add the conversion function template specialization produced by
8227 // template argument deduction as a candidate.
8228 assert(Specialization && "Missing function template specialization?");
8229 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8230 CandidateSet, AllowObjCConversionOnExplicit,
8231 AllowExplicit, AllowResultConversion);
8232}
8233
8234/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8235/// converts the given @c Object to a function pointer via the
8236/// conversion function @c Conversion, and then attempts to call it
8237/// with the given arguments (C++ [over.call.object]p2-4). Proto is
8238/// the type of function that we'll eventually be calling.
8240 DeclAccessPair FoundDecl,
8241 CXXRecordDecl *ActingContext,
8242 const FunctionProtoType *Proto,
8243 Expr *Object,
8244 ArrayRef<Expr *> Args,
8245 OverloadCandidateSet& CandidateSet) {
8246 if (!CandidateSet.isNewCandidate(Conversion))
8247 return;
8248
8249 // Overload resolution is always an unevaluated context.
8252
8253 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8254 Candidate.FoundDecl = FoundDecl;
8255 Candidate.Function = nullptr;
8256 Candidate.Surrogate = Conversion;
8257 Candidate.Viable = true;
8258 Candidate.IsSurrogate = true;
8259 Candidate.IgnoreObjectArgument = false;
8260 Candidate.ExplicitCallArguments = Args.size();
8261
8262 // Determine the implicit conversion sequence for the implicit
8263 // object parameter.
8264 ImplicitConversionSequence ObjectInit;
8265 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8266 ObjectInit = TryCopyInitialization(*this, Object,
8267 Conversion->getParamDecl(0)->getType(),
8268 /*SuppressUserConversions=*/false,
8269 /*InOverloadResolution=*/true, false);
8270 } else {
8272 *this, CandidateSet.getLocation(), Object->getType(),
8273 Object->Classify(Context), Conversion, ActingContext);
8274 }
8275
8276 if (ObjectInit.isBad()) {
8277 Candidate.Viable = false;
8279 Candidate.Conversions[0] = ObjectInit;
8280 return;
8281 }
8282
8283 // The first conversion is actually a user-defined conversion whose
8284 // first conversion is ObjectInit's standard conversion (which is
8285 // effectively a reference binding). Record it as such.
8286 Candidate.Conversions[0].setUserDefined();
8287 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8288 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8289 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8290 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8291 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8292 Candidate.Conversions[0].UserDefined.After
8293 = Candidate.Conversions[0].UserDefined.Before;
8294 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8295
8296 // Find the
8297 unsigned NumParams = Proto->getNumParams();
8298
8299 // (C++ 13.3.2p2): A candidate function having fewer than m
8300 // parameters is viable only if it has an ellipsis in its parameter
8301 // list (8.3.5).
8302 if (Args.size() > NumParams && !Proto->isVariadic()) {
8303 Candidate.Viable = false;
8305 return;
8306 }
8307
8308 // Function types don't have any default arguments, so just check if
8309 // we have enough arguments.
8310 if (Args.size() < NumParams) {
8311 // Not enough arguments.
8312 Candidate.Viable = false;
8314 return;
8315 }
8316
8317 // Determine the implicit conversion sequences for each of the
8318 // arguments.
8319 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8320 if (ArgIdx < NumParams) {
8321 // (C++ 13.3.2p3): for F to be a viable function, there shall
8322 // exist for each argument an implicit conversion sequence
8323 // (13.3.3.1) that converts that argument to the corresponding
8324 // parameter of F.
8325 QualType ParamType = Proto->getParamType(ArgIdx);
8326 Candidate.Conversions[ArgIdx + 1]
8327 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8328 /*SuppressUserConversions=*/false,
8329 /*InOverloadResolution=*/false,
8330 /*AllowObjCWritebackConversion=*/
8331 getLangOpts().ObjCAutoRefCount);
8332 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8333 Candidate.Viable = false;
8335 return;
8336 }
8337 } else {
8338 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8339 // argument for which there is no corresponding parameter is
8340 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8341 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8342 }
8343 }
8344
8345 if (Conversion->getTrailingRequiresClause()) {
8346 ConstraintSatisfaction Satisfaction;
8347 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8348 /*ForOverloadResolution*/ true) ||
8349 !Satisfaction.IsSatisfied) {
8350 Candidate.Viable = false;
8352 return;
8353 }
8354 }
8355
8356 if (EnableIfAttr *FailedAttr =
8357 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8358 Candidate.Viable = false;
8359 Candidate.FailureKind = ovl_fail_enable_if;
8360 Candidate.DeductionFailure.Data = FailedAttr;
8361 return;
8362 }
8363}
8364
8365/// Add all of the non-member operator function declarations in the given
8366/// function set to the overload candidate set.
8368 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8369 OverloadCandidateSet &CandidateSet,
8370 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8371 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8372 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8373 ArrayRef<Expr *> FunctionArgs = Args;
8374
8375 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8376 FunctionDecl *FD =
8377 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8378
8379 // Don't consider rewritten functions if we're not rewriting.
8380 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8381 continue;
8382
8383 assert(!isa<CXXMethodDecl>(FD) &&
8384 "unqualified operator lookup found a member function");
8385
8386 if (FunTmpl) {
8387 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8388 FunctionArgs, CandidateSet);
8389 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8390 AddTemplateOverloadCandidate(
8391 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8392 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8393 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8394 } else {
8395 if (ExplicitTemplateArgs)
8396 continue;
8397 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8398 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8399 AddOverloadCandidate(
8400 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8401 false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8403 }
8404 }
8405}
8406
8407/// Add overload candidates for overloaded operators that are
8408/// member functions.
8409///
8410/// Add the overloaded operator candidates that are member functions
8411/// for the operator Op that was used in an operator expression such
8412/// as "x Op y". , Args/NumArgs provides the operator arguments, and
8413/// CandidateSet will store the added overload candidates. (C++
8414/// [over.match.oper]).
8416 SourceLocation OpLoc,
8417 ArrayRef<Expr *> Args,
8418 OverloadCandidateSet &CandidateSet,
8421
8422 // C++ [over.match.oper]p3:
8423 // For a unary operator @ with an operand of a type whose
8424 // cv-unqualified version is T1, and for a binary operator @ with
8425 // a left operand of a type whose cv-unqualified version is T1 and
8426 // a right operand of a type whose cv-unqualified version is T2,
8427 // three sets of candidate functions, designated member
8428 // candidates, non-member candidates and built-in candidates, are
8429 // constructed as follows:
8430 QualType T1 = Args[0]->getType();
8431
8432 // -- If T1 is a complete class type or a class currently being
8433 // defined, the set of member candidates is the result of the
8434 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8435 // the set of member candidates is empty.
8436 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8437 // Complete the type if it can be completed.
8438 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8439 return;
8440 // If the type is neither complete nor being defined, bail out now.
8441 if (!T1Rec->getDecl()->getDefinition())
8442 return;
8443
8444 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8445 LookupQualifiedName(Operators, T1Rec->getDecl());
8446 Operators.suppressAccessDiagnostics();
8447
8448 for (LookupResult::iterator Oper = Operators.begin(),
8449 OperEnd = Operators.end();
8450 Oper != OperEnd; ++Oper) {
8451 if (Oper->getAsFunction() &&
8453 !CandidateSet.getRewriteInfo().shouldAddReversed(
8454 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8455 continue;
8456 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8457 Args[0]->Classify(Context), Args.slice(1),
8458 CandidateSet, /*SuppressUserConversion=*/false, PO);
8459 }
8460 }
8461}
8462
8463/// AddBuiltinCandidate - Add a candidate for a built-in
8464/// operator. ResultTy and ParamTys are the result and parameter types
8465/// of the built-in candidate, respectively. Args and NumArgs are the
8466/// arguments being passed to the candidate. IsAssignmentOperator
8467/// should be true when this built-in candidate is an assignment
8468/// operator. NumContextualBoolArguments is the number of arguments
8469/// (at the beginning of the argument list) that will be contextually
8470/// converted to bool.
8472 OverloadCandidateSet& CandidateSet,
8473 bool IsAssignmentOperator,
8474 unsigned NumContextualBoolArguments) {
8475 // Overload resolution is always an unevaluated context.
8478
8479 // Add this candidate
8480 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8481 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8482 Candidate.Function = nullptr;
8483 Candidate.IsSurrogate = false;
8484 Candidate.IgnoreObjectArgument = false;
8485 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8486
8487 // Determine the implicit conversion sequences for each of the
8488 // arguments.
8489 Candidate.Viable = true;
8490 Candidate.ExplicitCallArguments = Args.size();
8491 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8492 // C++ [over.match.oper]p4:
8493 // For the built-in assignment operators, conversions of the
8494 // left operand are restricted as follows:
8495 // -- no temporaries are introduced to hold the left operand, and
8496 // -- no user-defined conversions are applied to the left
8497 // operand to achieve a type match with the left-most
8498 // parameter of a built-in candidate.
8499 //
8500 // We block these conversions by turning off user-defined
8501 // conversions, since that is the only way that initialization of
8502 // a reference to a non-class type can occur from something that
8503 // is not of the same type.
8504 if (ArgIdx < NumContextualBoolArguments) {
8505 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8506 "Contextual conversion to bool requires bool type");
8507 Candidate.Conversions[ArgIdx]
8508 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8509 } else {
8510 Candidate.Conversions[ArgIdx]
8511 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8512 ArgIdx == 0 && IsAssignmentOperator,
8513 /*InOverloadResolution=*/false,
8514 /*AllowObjCWritebackConversion=*/
8515 getLangOpts().ObjCAutoRefCount);
8516 }
8517 if (Candidate.Conversions[ArgIdx].isBad()) {
8518 Candidate.Viable = false;
8520 break;
8521 }
8522 }
8523}
8524
8525namespace {
8526
8527/// BuiltinCandidateTypeSet - A set of types that will be used for the
8528/// candidate operator functions for built-in operators (C++
8529/// [over.built]). The types are separated into pointer types and
8530/// enumeration types.
8531class BuiltinCandidateTypeSet {
8532 /// TypeSet - A set of types.
8533 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8534
8535 /// PointerTypes - The set of pointer types that will be used in the
8536 /// built-in candidates.
8537 TypeSet PointerTypes;
8538
8539 /// MemberPointerTypes - The set of member pointer types that will be
8540 /// used in the built-in candidates.
8541 TypeSet MemberPointerTypes;
8542
8543 /// EnumerationTypes - The set of enumeration types that will be
8544 /// used in the built-in candidates.
8545 TypeSet EnumerationTypes;
8546
8547 /// The set of vector types that will be used in the built-in
8548 /// candidates.
8549 TypeSet VectorTypes;
8550
8551 /// The set of matrix types that will be used in the built-in
8552 /// candidates.
8553 TypeSet MatrixTypes;
8554
8555 /// The set of _BitInt types that will be used in the built-in candidates.
8556 TypeSet BitIntTypes;
8557
8558 /// A flag indicating non-record types are viable candidates
8559 bool HasNonRecordTypes;
8560
8561 /// A flag indicating whether either arithmetic or enumeration types
8562 /// were present in the candidate set.
8563 bool HasArithmeticOrEnumeralTypes;
8564
8565 /// A flag indicating whether the nullptr type was present in the
8566 /// candidate set.
8567 bool HasNullPtrType;
8568
8569 /// Sema - The semantic analysis instance where we are building the
8570 /// candidate type set.
8571 Sema &SemaRef;
8572
8573 /// Context - The AST context in which we will build the type sets.
8574 ASTContext &Context;
8575
8576 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8577 const Qualifiers &VisibleQuals);
8578 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8579
8580public:
8581 /// iterator - Iterates through the types that are part of the set.
8582 typedef TypeSet::iterator iterator;
8583
8584 BuiltinCandidateTypeSet(Sema &SemaRef)
8585 : HasNonRecordTypes(false),
8586 HasArithmeticOrEnumeralTypes(false),
8587 HasNullPtrType(false),
8588 SemaRef(SemaRef),
8589 Context(SemaRef.Context) { }
8590
8591 void AddTypesConvertedFrom(QualType Ty,
8592 SourceLocation Loc,
8593 bool AllowUserConversions,
8594 bool AllowExplicitConversions,
8595 const Qualifiers &VisibleTypeConversionsQuals);
8596
8597 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8598 llvm::iterator_range<iterator> member_pointer_types() {
8599 return MemberPointerTypes;
8600 }
8601 llvm::iterator_range<iterator> enumeration_types() {
8602 return EnumerationTypes;
8603 }
8604 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8605 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8606 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8607
8608 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8609 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8610 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8611 bool hasNullPtrType() const { return HasNullPtrType; }
8612};
8613
8614} // end anonymous namespace
8615
8616/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8617/// the set of pointer types along with any more-qualified variants of
8618/// that type. For example, if @p Ty is "int const *", this routine
8619/// will add "int const *", "int const volatile *", "int const
8620/// restrict *", and "int const volatile restrict *" to the set of
8621/// pointer types. Returns true if the add of @p Ty itself succeeded,
8622/// false otherwise.
8623///
8624/// FIXME: what to do about extended qualifiers?
8625bool
8626BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8627 const Qualifiers &VisibleQuals) {
8628
8629 // Insert this type.
8630 if (!PointerTypes.insert(Ty))
8631 return false;
8632
8633 QualType PointeeTy;
8634 const PointerType *PointerTy = Ty->getAs<PointerType>();
8635 bool buildObjCPtr = false;
8636 if (!PointerTy) {
8638 PointeeTy = PTy->getPointeeType();
8639 buildObjCPtr = true;
8640 } else {
8641 PointeeTy = PointerTy->getPointeeType();
8642 }
8643
8644 // Don't add qualified variants of arrays. For one, they're not allowed
8645 // (the qualifier would sink to the element type), and for another, the
8646 // only overload situation where it matters is subscript or pointer +- int,
8647 // and those shouldn't have qualifier variants anyway.
8648 if (PointeeTy->isArrayType())
8649 return true;
8650
8651 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8652 bool hasVolatile = VisibleQuals.hasVolatile();
8653 bool hasRestrict = VisibleQuals.hasRestrict();
8654
8655 // Iterate through all strict supersets of BaseCVR.
8656 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8657 if ((CVR | BaseCVR) != CVR) continue;
8658 // Skip over volatile if no volatile found anywhere in the types.
8659 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8660
8661 // Skip over restrict if no restrict found anywhere in the types, or if
8662 // the type cannot be restrict-qualified.
8663 if ((CVR & Qualifiers::Restrict) &&
8664 (!hasRestrict ||
8665 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8666 continue;
8667
8668 // Build qualified pointee type.
8669 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8670
8671 // Build qualified pointer type.
8672 QualType QPointerTy;
8673 if (!buildObjCPtr)
8674 QPointerTy = Context.getPointerType(QPointeeTy);
8675 else
8676 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8677
8678 // Insert qualified pointer type.
8679 PointerTypes.insert(QPointerTy);
8680 }
8681
8682 return true;
8683}
8684
8685/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8686/// to the set of pointer types along with any more-qualified variants of
8687/// that type. For example, if @p Ty is "int const *", this routine
8688/// will add "int const *", "int const volatile *", "int const
8689/// restrict *", and "int const volatile restrict *" to the set of
8690/// pointer types. Returns true if the add of @p Ty itself succeeded,
8691/// false otherwise.
8692///
8693/// FIXME: what to do about extended qualifiers?
8694bool
8695BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8696 QualType Ty) {
8697 // Insert this type.
8698 if (!MemberPointerTypes.insert(Ty))
8699 return false;
8700
8701 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8702 assert(PointerTy && "type was not a member pointer type!");
8703
8704 QualType PointeeTy = PointerTy->getPointeeType();
8705 // Don't add qualified variants of arrays. For one, they're not allowed
8706 // (the qualifier would sink to the element type), and for another, the
8707 // only overload situation where it matters is subscript or pointer +- int,
8708 // and those shouldn't have qualifier variants anyway.
8709 if (PointeeTy->isArrayType())
8710 return true;
8711 const Type *ClassTy = PointerTy->getClass();
8712
8713 // Iterate through all strict supersets of the pointee type's CVR
8714 // qualifiers.
8715 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8716 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8717 if ((CVR | BaseCVR) != CVR) continue;
8718
8719 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8720 MemberPointerTypes.insert(
8721 Context.getMemberPointerType(QPointeeTy, ClassTy));
8722 }
8723
8724 return true;
8725}
8726
8727/// AddTypesConvertedFrom - Add each of the types to which the type @p
8728/// Ty can be implicit converted to the given set of @p Types. We're
8729/// primarily interested in pointer types and enumeration types. We also
8730/// take member pointer types, for the conditional operator.
8731/// AllowUserConversions is true if we should look at the conversion
8732/// functions of a class type, and AllowExplicitConversions if we
8733/// should also include the explicit conversion functions of a class
8734/// type.
8735void
8736BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8737 SourceLocation Loc,
8738 bool AllowUserConversions,
8739 bool AllowExplicitConversions,
8740 const Qualifiers &VisibleQuals) {
8741 // Only deal with canonical types.
8742 Ty = Context.getCanonicalType(Ty);
8743
8744 // Look through reference types; they aren't part of the type of an
8745 // expression for the purposes of conversions.
8746 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8747 Ty = RefTy->getPointeeType();
8748
8749 // If we're dealing with an array type, decay to the pointer.
8750 if (Ty->isArrayType())
8751 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8752
8753 // Otherwise, we don't care about qualifiers on the type.
8754 Ty = Ty.getLocalUnqualifiedType();
8755
8756 // Flag if we ever add a non-record type.
8757 const RecordType *TyRec = Ty->getAs<RecordType>();
8758 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8759
8760 // Flag if we encounter an arithmetic type.
8761 HasArithmeticOrEnumeralTypes =
8762 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8763
8764 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8765 PointerTypes.insert(Ty);
8766 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8767 // Insert our type, and its more-qualified variants, into the set
8768 // of types.
8769 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8770 return;
8771 } else if (Ty->isMemberPointerType()) {
8772 // Member pointers are far easier, since the pointee can't be converted.
8773 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8774 return;
8775 } else if (Ty->isEnumeralType()) {
8776 HasArithmeticOrEnumeralTypes = true;
8777 EnumerationTypes.insert(Ty);
8778 } else if (Ty->isBitIntType()) {
8779 HasArithmeticOrEnumeralTypes = true;
8780 BitIntTypes.insert(Ty);
8781 } else if (Ty->isVectorType()) {
8782 // We treat vector types as arithmetic types in many contexts as an
8783 // extension.
8784 HasArithmeticOrEnumeralTypes = true;
8785 VectorTypes.insert(Ty);
8786 } else if (Ty->isMatrixType()) {
8787 // Similar to vector types, we treat vector types as arithmetic types in
8788 // many contexts as an extension.
8789 HasArithmeticOrEnumeralTypes = true;
8790 MatrixTypes.insert(Ty);
8791 } else if (Ty->isNullPtrType()) {
8792 HasNullPtrType = true;
8793 } else if (AllowUserConversions && TyRec) {
8794 // No conversion functions in incomplete types.
8795 if (!SemaRef.isCompleteType(Loc, Ty))
8796 return;
8797
8798 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8799 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8800 if (isa<UsingShadowDecl>(D))
8801 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8802
8803 // Skip conversion function templates; they don't tell us anything
8804 // about which builtin types we can convert to.
8805 if (isa<FunctionTemplateDecl>(D))
8806 continue;
8807
8808 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8809 if (AllowExplicitConversions || !Conv->isExplicit()) {
8810 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8811 VisibleQuals);
8812 }
8813 }
8814 }
8815}
8816/// Helper function for adjusting address spaces for the pointer or reference
8817/// operands of builtin operators depending on the argument.
8819 Expr *Arg) {
8821}
8822
8823/// Helper function for AddBuiltinOperatorCandidates() that adds
8824/// the volatile- and non-volatile-qualified assignment operators for the
8825/// given type to the candidate set.
8827 QualType T,
8828 ArrayRef<Expr *> Args,
8829 OverloadCandidateSet &CandidateSet) {
8830 QualType ParamTypes[2];
8831
8832 // T& operator=(T&, T)
8833 ParamTypes[0] = S.Context.getLValueReferenceType(
8835 ParamTypes[1] = T;
8836 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8837 /*IsAssignmentOperator=*/true);
8838
8840 // volatile T& operator=(volatile T&, T)
8841 ParamTypes[0] = S.Context.getLValueReferenceType(
8843 Args[0]));
8844 ParamTypes[1] = T;
8845 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8846 /*IsAssignmentOperator=*/true);
8847 }
8848}
8849
8850/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8851/// if any, found in visible type conversion functions found in ArgExpr's type.
8852static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8853 Qualifiers VRQuals;
8854 const RecordType *TyRec;
8855 if (const MemberPointerType *RHSMPType =
8856 ArgExpr->getType()->getAs<MemberPointerType>())
8857 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8858 else
8859 TyRec = ArgExpr->getType()->getAs<RecordType>();
8860 if (!TyRec) {
8861 // Just to be safe, assume the worst case.
8862 VRQuals.addVolatile();
8863 VRQuals.addRestrict();
8864 return VRQuals;
8865 }
8866
8867 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8868 if (!ClassDecl->hasDefinition())
8869 return VRQuals;
8870
8871 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8872 if (isa<UsingShadowDecl>(D))
8873 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8874 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8875 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8876 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8877 CanTy = ResTypeRef->getPointeeType();
8878 // Need to go down the pointer/mempointer chain and add qualifiers
8879 // as see them.
8880 bool done = false;
8881 while (!done) {
8882 if (CanTy.isRestrictQualified())
8883 VRQuals.addRestrict();
8884 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8885 CanTy = ResTypePtr->getPointeeType();
8886 else if (const MemberPointerType *ResTypeMPtr =
8887 CanTy->getAs<MemberPointerType>())
8888 CanTy = ResTypeMPtr->getPointeeType();
8889 else
8890 done = true;
8891 if (CanTy.isVolatileQualified())
8892 VRQuals.addVolatile();
8893 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8894 return VRQuals;
8895 }
8896 }
8897 }
8898 return VRQuals;
8899}
8900
8901// Note: We're currently only handling qualifiers that are meaningful for the
8902// LHS of compound assignment overloading.
8904 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8905 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8906 // _Atomic
8907 if (Available.hasAtomic()) {
8908 Available.removeAtomic();
8909 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8910 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8911 return;
8912 }
8913
8914 // volatile
8915 if (Available.hasVolatile()) {
8916 Available.removeVolatile();
8917 assert(!Applied.hasVolatile());
8918 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8919 Callback);
8920 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8921 return;
8922 }
8923
8924 Callback(Applied);
8925}
8926
8928 QualifiersAndAtomic Quals,
8929 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8931 Callback);
8932}
8933
8935 QualifiersAndAtomic Quals,
8936 Sema &S) {
8937 if (Quals.hasAtomic())
8939 if (Quals.hasVolatile())
8942}
8943
8944namespace {
8945
8946/// Helper class to manage the addition of builtin operator overload
8947/// candidates. It provides shared state and utility methods used throughout
8948/// the process, as well as a helper method to add each group of builtin
8949/// operator overloads from the standard to a candidate set.
8950class BuiltinOperatorOverloadBuilder {
8951 // Common instance state available to all overload candidate addition methods.
8952 Sema &S;
8953 ArrayRef<Expr *> Args;
8954 QualifiersAndAtomic VisibleTypeConversionsQuals;
8955 bool HasArithmeticOrEnumeralCandidateType;
8957 OverloadCandidateSet &CandidateSet;
8958
8959 static constexpr int ArithmeticTypesCap = 26;
8961
8962 // Define some indices used to iterate over the arithmetic types in
8963 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8964 // types are that preserved by promotion (C++ [over.built]p2).
8965 unsigned FirstIntegralType,
8966 LastIntegralType;
8967 unsigned FirstPromotedIntegralType,
8968 LastPromotedIntegralType;
8969 unsigned FirstPromotedArithmeticType,
8970 LastPromotedArithmeticType;
8971 unsigned NumArithmeticTypes;
8972
8973 void InitArithmeticTypes() {
8974 // Start of promoted types.
8975 FirstPromotedArithmeticType = 0;
8976 ArithmeticTypes.push_back(S.Context.FloatTy);
8977 ArithmeticTypes.push_back(S.Context.DoubleTy);
8978 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8980 ArithmeticTypes.push_back(S.Context.Float128Ty);
8982 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8983
8984 // Start of integral types.
8985 FirstIntegralType = ArithmeticTypes.size();
8986 FirstPromotedIntegralType = ArithmeticTypes.size();
8987 ArithmeticTypes.push_back(S.Context.IntTy);
8988 ArithmeticTypes.push_back(S.Context.LongTy);
8989 ArithmeticTypes.push_back(S.Context.LongLongTy);
8993 ArithmeticTypes.push_back(S.Context.Int128Ty);
8994 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8995 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8996 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9000 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9001
9002 /// We add candidates for the unique, unqualified _BitInt types present in
9003 /// the candidate type set. The candidate set already handled ensuring the
9004 /// type is unqualified and canonical, but because we're adding from N
9005 /// different sets, we need to do some extra work to unique things. Insert
9006 /// the candidates into a unique set, then move from that set into the list
9007 /// of arithmetic types.
9008 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9009 llvm::for_each(CandidateTypes, [&BitIntCandidates](
9010 BuiltinCandidateTypeSet &Candidate) {
9011 for (QualType BitTy : Candidate.bitint_types())
9012 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9013 });
9014 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9015 LastPromotedIntegralType = ArithmeticTypes.size();
9016 LastPromotedArithmeticType = ArithmeticTypes.size();
9017 // End of promoted types.
9018
9019 ArithmeticTypes.push_back(S.Context.BoolTy);
9020 ArithmeticTypes.push_back(S.Context.CharTy);
9021 ArithmeticTypes.push_back(S.Context.WCharTy);
9022 if (S.Context.getLangOpts().Char8)
9023 ArithmeticTypes.push_back(S.Context.Char8Ty);
9024 ArithmeticTypes.push_back(S.Context.Char16Ty);
9025 ArithmeticTypes.push_back(S.Context.Char32Ty);
9026 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9027 ArithmeticTypes.push_back(S.Context.ShortTy);
9028 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9029 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9030 LastIntegralType = ArithmeticTypes.size();
9031 NumArithmeticTypes = ArithmeticTypes.size();
9032 // End of integral types.
9033 // FIXME: What about complex? What about half?
9034
9035 // We don't know for sure how many bit-precise candidates were involved, so
9036 // we subtract those from the total when testing whether we're under the
9037 // cap or not.
9038 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9039 ArithmeticTypesCap &&
9040 "Enough inline storage for all arithmetic types.");
9041 }
9042
9043 /// Helper method to factor out the common pattern of adding overloads
9044 /// for '++' and '--' builtin operators.
9045 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9046 bool HasVolatile,
9047 bool HasRestrict) {
9048 QualType ParamTypes[2] = {
9049 S.Context.getLValueReferenceType(CandidateTy),
9050 S.Context.IntTy
9051 };
9052
9053 // Non-volatile version.
9054 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9055
9056 // Use a heuristic to reduce number of builtin candidates in the set:
9057 // add volatile version only if there are conversions to a volatile type.
9058 if (HasVolatile) {
9059 ParamTypes[0] =
9061 S.Context.getVolatileType(CandidateTy));
9062 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9063 }
9064
9065 // Add restrict version only if there are conversions to a restrict type
9066 // and our candidate type is a non-restrict-qualified pointer.
9067 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9068 !CandidateTy.isRestrictQualified()) {
9069 ParamTypes[0]
9072 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9073
9074 if (HasVolatile) {
9075 ParamTypes[0]
9077 S.Context.getCVRQualifiedType(CandidateTy,
9080 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9081 }
9082 }
9083
9084 }
9085
9086 /// Helper to add an overload candidate for a binary builtin with types \p L
9087 /// and \p R.
9088 void AddCandidate(QualType L, QualType R) {
9089 QualType LandR[2] = {L, R};
9090 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9091 }
9092
9093public:
9094 BuiltinOperatorOverloadBuilder(
9095 Sema &S, ArrayRef<Expr *> Args,
9096 QualifiersAndAtomic VisibleTypeConversionsQuals,
9097 bool HasArithmeticOrEnumeralCandidateType,
9099 OverloadCandidateSet &CandidateSet)
9100 : S(S), Args(Args),
9101 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9102 HasArithmeticOrEnumeralCandidateType(
9103 HasArithmeticOrEnumeralCandidateType),
9104 CandidateTypes(CandidateTypes),
9105 CandidateSet(CandidateSet) {
9106
9107 InitArithmeticTypes();
9108 }
9109
9110 // Increment is deprecated for bool since C++17.
9111 //
9112 // C++ [over.built]p3:
9113 //
9114 // For every pair (T, VQ), where T is an arithmetic type other
9115 // than bool, and VQ is either volatile or empty, there exist
9116 // candidate operator functions of the form
9117 //
9118 // VQ T& operator++(VQ T&);
9119 // T operator++(VQ T&, int);
9120 //
9121 // C++ [over.built]p4:
9122 //
9123 // For every pair (T, VQ), where T is an arithmetic type other
9124 // than bool, and VQ is either volatile or empty, there exist
9125 // candidate operator functions of the form
9126 //
9127 // VQ T& operator--(VQ T&);
9128 // T operator--(VQ T&, int);
9129 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9130 if (!HasArithmeticOrEnumeralCandidateType)
9131 return;
9132
9133 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9134 const auto TypeOfT = ArithmeticTypes[Arith];
9135 if (TypeOfT == S.Context.BoolTy) {
9136 if (Op == OO_MinusMinus)
9137 continue;
9138 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9139 continue;
9140 }
9141 addPlusPlusMinusMinusStyleOverloads(
9142 TypeOfT,
9143 VisibleTypeConversionsQuals.hasVolatile(),
9144 VisibleTypeConversionsQuals.hasRestrict());
9145 }
9146 }
9147
9148 // C++ [over.built]p5:
9149 //
9150 // For every pair (T, VQ), where T is a cv-qualified or
9151 // cv-unqualified object type, and VQ is either volatile or
9152 // empty, there exist candidate operator functions of the form
9153 //
9154 // T*VQ& operator++(T*VQ&);
9155 // T*VQ& operator--(T*VQ&);
9156 // T* operator++(T*VQ&, int);
9157 // T* operator--(T*VQ&, int);
9158 void addPlusPlusMinusMinusPointerOverloads() {
9159 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9160 // Skip pointer types that aren't pointers to object types.
9161 if (!PtrTy->getPointeeType()->isObjectType())
9162 continue;
9163
9164 addPlusPlusMinusMinusStyleOverloads(
9165 PtrTy,
9166 (!PtrTy.isVolatileQualified() &&
9167 VisibleTypeConversionsQuals.hasVolatile()),
9168 (!PtrTy.isRestrictQualified() &&
9169 VisibleTypeConversionsQuals.hasRestrict()));
9170 }
9171 }
9172
9173 // C++ [over.built]p6:
9174 // For every cv-qualified or cv-unqualified object type T, there
9175 // exist candidate operator functions of the form
9176 //
9177 // T& operator*(T*);
9178 //
9179 // C++ [over.built]p7:
9180 // For every function type T that does not have cv-qualifiers or a
9181 // ref-qualifier, there exist candidate operator functions of the form
9182 // T& operator*(T*);
9183 void addUnaryStarPointerOverloads() {
9184 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9185 QualType PointeeTy = ParamTy->getPointeeType();
9186 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9187 continue;
9188
9189 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9190 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9191 continue;
9192
9193 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9194 }
9195 }
9196
9197 // C++ [over.built]p9:
9198 // For every promoted arithmetic type T, there exist candidate
9199 // operator functions of the form
9200 //
9201 // T operator+(T);
9202 // T operator-(T);
9203 void addUnaryPlusOrMinusArithmeticOverloads() {
9204 if (!HasArithmeticOrEnumeralCandidateType)
9205 return;
9206
9207 for (unsigned Arith = FirstPromotedArithmeticType;
9208 Arith < LastPromotedArithmeticType; ++Arith) {
9209 QualType ArithTy = ArithmeticTypes[Arith];
9210 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9211 }
9212
9213 // Extension: We also add these operators for vector types.
9214 for (QualType VecTy : CandidateTypes[0].vector_types())
9215 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9216 }
9217
9218 // C++ [over.built]p8:
9219 // For every type T, there exist candidate operator functions of
9220 // the form
9221 //
9222 // T* operator+(T*);
9223 void addUnaryPlusPointerOverloads() {
9224 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9225 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9226 }
9227
9228 // C++ [over.built]p10:
9229 // For every promoted integral type T, there exist candidate
9230 // operator functions of the form
9231 //
9232 // T operator~(T);
9233 void addUnaryTildePromotedIntegralOverloads() {
9234 if (!HasArithmeticOrEnumeralCandidateType)
9235 return;
9236
9237 for (unsigned Int = FirstPromotedIntegralType;
9238 Int < LastPromotedIntegralType; ++Int) {
9239 QualType IntTy = ArithmeticTypes[Int];
9240 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9241 }
9242
9243 // Extension: We also add this operator for vector types.
9244 for (QualType VecTy : CandidateTypes[0].vector_types())
9245 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9246 }
9247
9248 // C++ [over.match.oper]p16:
9249 // For every pointer to member type T or type std::nullptr_t, there
9250 // exist candidate operator functions of the form
9251 //
9252 // bool operator==(T,T);
9253 // bool operator!=(T,T);
9254 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9255 /// Set of (canonical) types that we've already handled.
9257
9258 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9259 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9260 // Don't add the same builtin candidate twice.
9261 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9262 continue;
9263
9264 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9265 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9266 }
9267
9268 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9270 if (AddedTypes.insert(NullPtrTy).second) {
9271 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9272 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9273 }
9274 }
9275 }
9276 }
9277
9278 // C++ [over.built]p15:
9279 //
9280 // For every T, where T is an enumeration type or a pointer type,
9281 // there exist candidate operator functions of the form
9282 //
9283 // bool operator<(T, T);
9284 // bool operator>(T, T);
9285 // bool operator<=(T, T);
9286 // bool operator>=(T, T);
9287 // bool operator==(T, T);
9288 // bool operator!=(T, T);
9289 // R operator<=>(T, T)
9290 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9291 // C++ [over.match.oper]p3:
9292 // [...]the built-in candidates include all of the candidate operator
9293 // functions defined in 13.6 that, compared to the given operator, [...]
9294 // do not have the same parameter-type-list as any non-template non-member
9295 // candidate.
9296 //
9297 // Note that in practice, this only affects enumeration types because there
9298 // aren't any built-in candidates of record type, and a user-defined operator
9299 // must have an operand of record or enumeration type. Also, the only other
9300 // overloaded operator with enumeration arguments, operator=,
9301 // cannot be overloaded for enumeration types, so this is the only place
9302 // where we must suppress candidates like this.
9304 UserDefinedBinaryOperators;
9305
9306 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9307 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9308 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9309 CEnd = CandidateSet.end();
9310 C != CEnd; ++C) {
9311 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9312 continue;
9313
9314 if (C->Function->isFunctionTemplateSpecialization())
9315 continue;
9316
9317 // We interpret "same parameter-type-list" as applying to the
9318 // "synthesized candidate, with the order of the two parameters
9319 // reversed", not to the original function.
9320 bool Reversed = C->isReversed();
9321 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9322 ->getType()
9323 .getUnqualifiedType();
9324 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9325 ->getType()
9326 .getUnqualifiedType();
9327
9328 // Skip if either parameter isn't of enumeral type.
9329 if (!FirstParamType->isEnumeralType() ||
9330 !SecondParamType->isEnumeralType())
9331 continue;
9332
9333 // Add this operator to the set of known user-defined operators.
9334 UserDefinedBinaryOperators.insert(
9335 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9336 S.Context.getCanonicalType(SecondParamType)));
9337 }
9338 }
9339 }
9340
9341 /// Set of (canonical) types that we've already handled.
9343
9344 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9345 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9346 // Don't add the same builtin candidate twice.
9347 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9348 continue;
9349 if (IsSpaceship && PtrTy->isFunctionPointerType())
9350 continue;
9351
9352 QualType ParamTypes[2] = {PtrTy, PtrTy};
9353 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9354 }
9355 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9356 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9357
9358 // Don't add the same builtin candidate twice, or if a user defined
9359 // candidate exists.
9360 if (!AddedTypes.insert(CanonType).second ||
9361 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9362 CanonType)))
9363 continue;
9364 QualType ParamTypes[2] = {EnumTy, EnumTy};
9365 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9366 }
9367 }
9368 }
9369
9370 // C++ [over.built]p13:
9371 //
9372 // For every cv-qualified or cv-unqualified object type T
9373 // there exist candidate operator functions of the form
9374 //
9375 // T* operator+(T*, ptrdiff_t);
9376 // T& operator[](T*, ptrdiff_t); [BELOW]
9377 // T* operator-(T*, ptrdiff_t);
9378 // T* operator+(ptrdiff_t, T*);
9379 // T& operator[](ptrdiff_t, T*); [BELOW]
9380 //
9381 // C++ [over.built]p14:
9382 //
9383 // For every T, where T is a pointer to object type, there
9384 // exist candidate operator functions of the form
9385 //
9386 // ptrdiff_t operator-(T, T);
9387 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9388 /// Set of (canonical) types that we've already handled.
9390
9391 for (int Arg = 0; Arg < 2; ++Arg) {
9392 QualType AsymmetricParamTypes[2] = {
9395 };
9396 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9397 QualType PointeeTy = PtrTy->getPointeeType();
9398 if (!PointeeTy->isObjectType())
9399 continue;
9400
9401 AsymmetricParamTypes[Arg] = PtrTy;
9402 if (Arg == 0 || Op == OO_Plus) {
9403 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9404 // T* operator+(ptrdiff_t, T*);
9405 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9406 }
9407 if (Op == OO_Minus) {
9408 // ptrdiff_t operator-(T, T);
9409 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9410 continue;
9411
9412 QualType ParamTypes[2] = {PtrTy, PtrTy};
9413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9414 }
9415 }
9416 }
9417 }
9418
9419 // C++ [over.built]p12:
9420 //
9421 // For every pair of promoted arithmetic types L and R, there
9422 // exist candidate operator functions of the form
9423 //
9424 // LR operator*(L, R);
9425 // LR operator/(L, R);
9426 // LR operator+(L, R);
9427 // LR operator-(L, R);
9428 // bool operator<(L, R);
9429 // bool operator>(L, R);
9430 // bool operator<=(L, R);
9431 // bool operator>=(L, R);
9432 // bool operator==(L, R);
9433 // bool operator!=(L, R);
9434 //
9435 // where LR is the result of the usual arithmetic conversions
9436 // between types L and R.
9437 //
9438 // C++ [over.built]p24:
9439 //
9440 // For every pair of promoted arithmetic types L and R, there exist
9441 // candidate operator functions of the form
9442 //
9443 // LR operator?(bool, L, R);
9444 //
9445 // where LR is the result of the usual arithmetic conversions
9446 // between types L and R.
9447 // Our candidates ignore the first parameter.
9448 void addGenericBinaryArithmeticOverloads() {
9449 if (!HasArithmeticOrEnumeralCandidateType)
9450 return;
9451
9452 for (unsigned Left = FirstPromotedArithmeticType;
9453 Left < LastPromotedArithmeticType; ++Left) {
9454 for (unsigned Right = FirstPromotedArithmeticType;
9455 Right < LastPromotedArithmeticType; ++Right) {
9456 QualType LandR[2] = { ArithmeticTypes[Left],
9457 ArithmeticTypes[Right] };
9458 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9459 }
9460 }
9461
9462 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9463 // conditional operator for vector types.
9464 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9465 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9466 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9467 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9468 }
9469 }
9470
9471 /// Add binary operator overloads for each candidate matrix type M1, M2:
9472 /// * (M1, M1) -> M1
9473 /// * (M1, M1.getElementType()) -> M1
9474 /// * (M2.getElementType(), M2) -> M2
9475 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9476 void addMatrixBinaryArithmeticOverloads() {
9477 if (!HasArithmeticOrEnumeralCandidateType)
9478 return;
9479
9480 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9481 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9482 AddCandidate(M1, M1);
9483 }
9484
9485 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9486 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9487 if (!CandidateTypes[0].containsMatrixType(M2))
9488 AddCandidate(M2, M2);
9489 }
9490 }
9491
9492 // C++2a [over.built]p14:
9493 //
9494 // For every integral type T there exists a candidate operator function
9495 // of the form
9496 //
9497 // std::strong_ordering operator<=>(T, T)
9498 //
9499 // C++2a [over.built]p15:
9500 //
9501 // For every pair of floating-point types L and R, there exists a candidate
9502 // operator function of the form
9503 //
9504 // std::partial_ordering operator<=>(L, R);
9505 //
9506 // FIXME: The current specification for integral types doesn't play nice with
9507 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9508 // comparisons. Under the current spec this can lead to ambiguity during
9509 // overload resolution. For example:
9510 //
9511 // enum A : int {a};
9512 // auto x = (a <=> (long)42);
9513 //
9514 // error: call is ambiguous for arguments 'A' and 'long'.
9515 // note: candidate operator<=>(int, int)
9516 // note: candidate operator<=>(long, long)
9517 //
9518 // To avoid this error, this function deviates from the specification and adds
9519 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9520 // arithmetic types (the same as the generic relational overloads).
9521 //
9522 // For now this function acts as a placeholder.
9523 void addThreeWayArithmeticOverloads() {
9524 addGenericBinaryArithmeticOverloads();
9525 }
9526
9527 // C++ [over.built]p17:
9528 //
9529 // For every pair of promoted integral types L and R, there
9530 // exist candidate operator functions of the form
9531 //
9532 // LR operator%(L, R);
9533 // LR operator&(L, R);
9534 // LR operator^(L, R);
9535 // LR operator|(L, R);
9536 // L operator<<(L, R);
9537 // L operator>>(L, R);
9538 //
9539 // where LR is the result of the usual arithmetic conversions
9540 // between types L and R.
9541 void addBinaryBitwiseArithmeticOverloads() {
9542 if (!HasArithmeticOrEnumeralCandidateType)
9543 return;
9544
9545 for (unsigned Left = FirstPromotedIntegralType;
9546 Left < LastPromotedIntegralType; ++Left) {
9547 for (unsigned Right = FirstPromotedIntegralType;
9548 Right < LastPromotedIntegralType; ++Right) {
9549 QualType LandR[2] = { ArithmeticTypes[Left],
9550 ArithmeticTypes[Right] };
9551 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9552 }
9553 }
9554 }
9555
9556 // C++ [over.built]p20:
9557 //
9558 // For every pair (T, VQ), where T is an enumeration or
9559 // pointer to member type and VQ is either volatile or
9560 // empty, there exist candidate operator functions of the form
9561 //
9562 // VQ T& operator=(VQ T&, T);
9563 void addAssignmentMemberPointerOrEnumeralOverloads() {
9564 /// Set of (canonical) types that we've already handled.
9566
9567 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9568 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9569 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9570 continue;
9571
9572 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9573 }
9574
9575 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9576 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9577 continue;
9578
9579 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9580 }
9581 }
9582 }
9583
9584 // C++ [over.built]p19:
9585 //
9586 // For every pair (T, VQ), where T is any type and VQ is either
9587 // volatile or empty, there exist candidate operator functions
9588 // of the form
9589 //
9590 // T*VQ& operator=(T*VQ&, T*);
9591 //
9592 // C++ [over.built]p21:
9593 //
9594 // For every pair (T, VQ), where T is a cv-qualified or
9595 // cv-unqualified object type and VQ is either volatile or
9596 // empty, there exist candidate operator functions of the form
9597 //
9598 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9599 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9600 void addAssignmentPointerOverloads(bool isEqualOp) {
9601 /// Set of (canonical) types that we've already handled.
9603
9604 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9605 // If this is operator=, keep track of the builtin candidates we added.
9606 if (isEqualOp)
9607 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9608 else if (!PtrTy->getPointeeType()->isObjectType())
9609 continue;
9610
9611 // non-volatile version
9612 QualType ParamTypes[2] = {
9614 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9615 };
9616 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9617 /*IsAssignmentOperator=*/ isEqualOp);
9618
9619 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9620 VisibleTypeConversionsQuals.hasVolatile();
9621 if (NeedVolatile) {
9622 // volatile version
9623 ParamTypes[0] =
9625 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9626 /*IsAssignmentOperator=*/isEqualOp);
9627 }
9628
9629 if (!PtrTy.isRestrictQualified() &&
9630 VisibleTypeConversionsQuals.hasRestrict()) {
9631 // restrict version
9632 ParamTypes[0] =
9634 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9635 /*IsAssignmentOperator=*/isEqualOp);
9636
9637 if (NeedVolatile) {
9638 // volatile restrict version
9639 ParamTypes[0] =
9642 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9643 /*IsAssignmentOperator=*/isEqualOp);
9644 }
9645 }
9646 }
9647
9648 if (isEqualOp) {
9649 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9650 // Make sure we don't add the same candidate twice.
9651 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9652 continue;
9653
9654 QualType ParamTypes[2] = {
9656 PtrTy,
9657 };
9658
9659 // non-volatile version
9660 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9661 /*IsAssignmentOperator=*/true);
9662
9663 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9664 VisibleTypeConversionsQuals.hasVolatile();
9665 if (NeedVolatile) {
9666 // volatile version
9667 ParamTypes[0] = S.Context.getLValueReferenceType(
9668 S.Context.getVolatileType(PtrTy));
9669 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9670 /*IsAssignmentOperator=*/true);
9671 }
9672
9673 if (!PtrTy.isRestrictQualified() &&
9674 VisibleTypeConversionsQuals.hasRestrict()) {
9675 // restrict version
9676 ParamTypes[0] = S.Context.getLValueReferenceType(
9677 S.Context.getRestrictType(PtrTy));
9678 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9679 /*IsAssignmentOperator=*/true);
9680
9681 if (NeedVolatile) {
9682 // volatile restrict version
9683 ParamTypes[0] =
9686 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9687 /*IsAssignmentOperator=*/true);
9688 }
9689 }
9690 }
9691 }
9692 }
9693
9694 // C++ [over.built]p18:
9695 //
9696 // For every triple (L, VQ, R), where L is an arithmetic type,
9697 // VQ is either volatile or empty, and R is a promoted
9698 // arithmetic type, there exist candidate operator functions of
9699 // the form
9700 //
9701 // VQ L& operator=(VQ L&, R);
9702 // VQ L& operator*=(VQ L&, R);
9703 // VQ L& operator/=(VQ L&, R);
9704 // VQ L& operator+=(VQ L&, R);
9705 // VQ L& operator-=(VQ L&, R);
9706 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9707 if (!HasArithmeticOrEnumeralCandidateType)
9708 return;
9709
9710 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9711 for (unsigned Right = FirstPromotedArithmeticType;
9712 Right < LastPromotedArithmeticType; ++Right) {
9713 QualType ParamTypes[2];
9714 ParamTypes[1] = ArithmeticTypes[Right];
9716 S, ArithmeticTypes[Left], Args[0]);
9717
9719 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9720 ParamTypes[0] =
9721 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9722 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9723 /*IsAssignmentOperator=*/isEqualOp);
9724 });
9725 }
9726 }
9727
9728 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9729 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9730 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9731 QualType ParamTypes[2];
9732 ParamTypes[1] = Vec2Ty;
9733 // Add this built-in operator as a candidate (VQ is empty).
9734 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9735 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9736 /*IsAssignmentOperator=*/isEqualOp);
9737
9738 // Add this built-in operator as a candidate (VQ is 'volatile').
9739 if (VisibleTypeConversionsQuals.hasVolatile()) {
9740 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9741 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9742 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9743 /*IsAssignmentOperator=*/isEqualOp);
9744 }
9745 }
9746 }
9747
9748 // C++ [over.built]p22:
9749 //
9750 // For every triple (L, VQ, R), where L is an integral type, VQ
9751 // is either volatile or empty, and R is a promoted integral
9752 // type, there exist candidate operator functions of the form
9753 //
9754 // VQ L& operator%=(VQ L&, R);
9755 // VQ L& operator<<=(VQ L&, R);
9756 // VQ L& operator>>=(VQ L&, R);
9757 // VQ L& operator&=(VQ L&, R);
9758 // VQ L& operator^=(VQ L&, R);
9759 // VQ L& operator|=(VQ L&, R);
9760 void addAssignmentIntegralOverloads() {
9761 if (!HasArithmeticOrEnumeralCandidateType)
9762 return;
9763
9764 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9765 for (unsigned Right = FirstPromotedIntegralType;
9766 Right < LastPromotedIntegralType; ++Right) {
9767 QualType ParamTypes[2];
9768 ParamTypes[1] = ArithmeticTypes[Right];
9770 S, ArithmeticTypes[Left], Args[0]);
9771
9773 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9774 ParamTypes[0] =
9775 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9776 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9777 });
9778 }
9779 }
9780 }
9781
9782 // C++ [over.operator]p23:
9783 //
9784 // There also exist candidate operator functions of the form
9785 //
9786 // bool operator!(bool);
9787 // bool operator&&(bool, bool);
9788 // bool operator||(bool, bool);
9789 void addExclaimOverload() {
9790 QualType ParamTy = S.Context.BoolTy;
9791 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9792 /*IsAssignmentOperator=*/false,
9793 /*NumContextualBoolArguments=*/1);
9794 }
9795 void addAmpAmpOrPipePipeOverload() {
9796 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9797 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9798 /*IsAssignmentOperator=*/false,
9799 /*NumContextualBoolArguments=*/2);
9800 }
9801
9802 // C++ [over.built]p13:
9803 //
9804 // For every cv-qualified or cv-unqualified object type T there
9805 // exist candidate operator functions of the form
9806 //
9807 // T* operator+(T*, ptrdiff_t); [ABOVE]
9808 // T& operator[](T*, ptrdiff_t);
9809 // T* operator-(T*, ptrdiff_t); [ABOVE]
9810 // T* operator+(ptrdiff_t, T*); [ABOVE]
9811 // T& operator[](ptrdiff_t, T*);
9812 void addSubscriptOverloads() {
9813 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9814 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9815 QualType PointeeType = PtrTy->getPointeeType();
9816 if (!PointeeType->isObjectType())
9817 continue;
9818
9819 // T& operator[](T*, ptrdiff_t)
9820 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9821 }
9822
9823 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9824 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9825 QualType PointeeType = PtrTy->getPointeeType();
9826 if (!PointeeType->isObjectType())
9827 continue;
9828
9829 // T& operator[](ptrdiff_t, T*)
9830 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9831 }
9832 }
9833
9834 // C++ [over.built]p11:
9835 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9836 // C1 is the same type as C2 or is a derived class of C2, T is an object
9837 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9838 // there exist candidate operator functions of the form
9839 //
9840 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9841 //
9842 // where CV12 is the union of CV1 and CV2.
9843 void addArrowStarOverloads() {
9844 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9845 QualType C1Ty = PtrTy;
9846 QualType C1;
9848 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9849 if (!isa<RecordType>(C1))
9850 continue;
9851 // heuristic to reduce number of builtin candidates in the set.
9852 // Add volatile/restrict version only if there are conversions to a
9853 // volatile/restrict type.
9854 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9855 continue;
9856 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9857 continue;
9858 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9859 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9860 QualType C2 = QualType(mptr->getClass(), 0);
9861 C2 = C2.getUnqualifiedType();
9862 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9863 break;
9864 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9865 // build CV12 T&
9866 QualType T = mptr->getPointeeType();
9867 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9868 T.isVolatileQualified())
9869 continue;
9870 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9871 T.isRestrictQualified())
9872 continue;
9873 T = Q1.apply(S.Context, T);
9874 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9875 }
9876 }
9877 }
9878
9879 // Note that we don't consider the first argument, since it has been
9880 // contextually converted to bool long ago. The candidates below are
9881 // therefore added as binary.
9882 //
9883 // C++ [over.built]p25:
9884 // For every type T, where T is a pointer, pointer-to-member, or scoped
9885 // enumeration type, there exist candidate operator functions of the form
9886 //
9887 // T operator?(bool, T, T);
9888 //
9889 void addConditionalOperatorOverloads() {
9890 /// Set of (canonical) types that we've already handled.
9892
9893 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9894 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9895 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9896 continue;
9897
9898 QualType ParamTypes[2] = {PtrTy, PtrTy};
9899 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9900 }
9901
9902 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9903 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9904 continue;
9905
9906 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9907 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9908 }
9909
9910 if (S.getLangOpts().CPlusPlus11) {
9911 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9912 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9913 continue;
9914
9915 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9916 continue;
9917
9918 QualType ParamTypes[2] = {EnumTy, EnumTy};
9919 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9920 }
9921 }
9922 }
9923 }
9924};
9925
9926} // end anonymous namespace
9927
9928/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9929/// operator overloads to the candidate set (C++ [over.built]), based
9930/// on the operator @p Op and the arguments given. For example, if the
9931/// operator is a binary '+', this routine might add "int
9932/// operator+(int, int)" to cover integer addition.
9934 SourceLocation OpLoc,
9935 ArrayRef<Expr *> Args,
9936 OverloadCandidateSet &CandidateSet) {
9937 // Find all of the types that the arguments can convert to, but only
9938 // if the operator we're looking at has built-in operator candidates
9939 // that make use of these types. Also record whether we encounter non-record
9940 // candidate types or either arithmetic or enumeral candidate types.
9941 QualifiersAndAtomic VisibleTypeConversionsQuals;
9942 VisibleTypeConversionsQuals.addConst();
9943 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9944 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9945 if (Args[ArgIdx]->getType()->isAtomicType())
9946 VisibleTypeConversionsQuals.addAtomic();
9947 }
9948
9949 bool HasNonRecordCandidateType = false;
9950 bool HasArithmeticOrEnumeralCandidateType = false;
9952 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9953 CandidateTypes.emplace_back(*this);
9954 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9955 OpLoc,
9956 true,
9957 (Op == OO_Exclaim ||
9958 Op == OO_AmpAmp ||
9959 Op == OO_PipePipe),
9960 VisibleTypeConversionsQuals);
9961 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9962 CandidateTypes[ArgIdx].hasNonRecordTypes();
9963 HasArithmeticOrEnumeralCandidateType =
9964 HasArithmeticOrEnumeralCandidateType ||
9965 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9966 }
9967
9968 // Exit early when no non-record types have been added to the candidate set
9969 // for any of the arguments to the operator.
9970 //
9971 // We can't exit early for !, ||, or &&, since there we have always have
9972 // 'bool' overloads.
9973 if (!HasNonRecordCandidateType &&
9974 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9975 return;
9976
9977 // Setup an object to manage the common state for building overloads.
9978 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9979 VisibleTypeConversionsQuals,
9980 HasArithmeticOrEnumeralCandidateType,
9981 CandidateTypes, CandidateSet);
9982
9983 // Dispatch over the operation to add in only those overloads which apply.
9984 switch (Op) {
9985 case OO_None:
9987 llvm_unreachable("Expected an overloaded operator");
9988
9989 case OO_New:
9990 case OO_Delete:
9991 case OO_Array_New:
9992 case OO_Array_Delete:
9993 case OO_Call:
9994 llvm_unreachable(
9995 "Special operators don't use AddBuiltinOperatorCandidates");
9996
9997 case OO_Comma:
9998 case OO_Arrow:
9999 case OO_Coawait:
10000 // C++ [over.match.oper]p3:
10001 // -- For the operator ',', the unary operator '&', the
10002 // operator '->', or the operator 'co_await', the
10003 // built-in candidates set is empty.
10004 break;
10005
10006 case OO_Plus: // '+' is either unary or binary
10007 if (Args.size() == 1)
10008 OpBuilder.addUnaryPlusPointerOverloads();
10009 [[fallthrough]];
10010
10011 case OO_Minus: // '-' is either unary or binary
10012 if (Args.size() == 1) {
10013 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10014 } else {
10015 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10016 OpBuilder.addGenericBinaryArithmeticOverloads();
10017 OpBuilder.addMatrixBinaryArithmeticOverloads();
10018 }
10019 break;
10020
10021 case OO_Star: // '*' is either unary or binary
10022 if (Args.size() == 1)
10023 OpBuilder.addUnaryStarPointerOverloads();
10024 else {
10025 OpBuilder.addGenericBinaryArithmeticOverloads();
10026 OpBuilder.addMatrixBinaryArithmeticOverloads();
10027 }
10028 break;
10029
10030 case OO_Slash:
10031 OpBuilder.addGenericBinaryArithmeticOverloads();
10032 break;
10033
10034 case OO_PlusPlus:
10035 case OO_MinusMinus:
10036 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10037 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10038 break;
10039
10040 case OO_EqualEqual:
10041 case OO_ExclaimEqual:
10042 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10043 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10044 OpBuilder.addGenericBinaryArithmeticOverloads();
10045 break;
10046
10047 case OO_Less:
10048 case OO_Greater:
10049 case OO_LessEqual:
10050 case OO_GreaterEqual:
10051 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10052 OpBuilder.addGenericBinaryArithmeticOverloads();
10053 break;
10054
10055 case OO_Spaceship:
10056 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10057 OpBuilder.addThreeWayArithmeticOverloads();
10058 break;
10059
10060 case OO_Percent:
10061 case OO_Caret:
10062 case OO_Pipe:
10063 case OO_LessLess:
10064 case OO_GreaterGreater:
10065 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10066 break;
10067
10068 case OO_Amp: // '&' is either unary or binary
10069 if (Args.size() == 1)
10070 // C++ [over.match.oper]p3:
10071 // -- For the operator ',', the unary operator '&', or the
10072 // operator '->', the built-in candidates set is empty.
10073 break;
10074
10075 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10076 break;
10077
10078 case OO_Tilde:
10079 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10080 break;
10081
10082 case OO_Equal:
10083 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10084 [[fallthrough]];
10085
10086 case OO_PlusEqual:
10087 case OO_MinusEqual:
10088 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10089 [[fallthrough]];
10090
10091 case OO_StarEqual:
10092 case OO_SlashEqual:
10093 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10094 break;
10095
10096 case OO_PercentEqual:
10097 case OO_LessLessEqual:
10098 case OO_GreaterGreaterEqual:
10099 case OO_AmpEqual:
10100 case OO_CaretEqual:
10101 case OO_PipeEqual:
10102 OpBuilder.addAssignmentIntegralOverloads();
10103 break;
10104
10105 case OO_Exclaim:
10106 OpBuilder.addExclaimOverload();
10107 break;
10108
10109 case OO_AmpAmp:
10110 case OO_PipePipe:
10111 OpBuilder.addAmpAmpOrPipePipeOverload();
10112 break;
10113
10114 case OO_Subscript:
10115 if (Args.size() == 2)
10116 OpBuilder.addSubscriptOverloads();
10117 break;
10118
10119 case OO_ArrowStar:
10120 OpBuilder.addArrowStarOverloads();
10121 break;
10122
10123 case OO_Conditional:
10124 OpBuilder.addConditionalOperatorOverloads();
10125 OpBuilder.addGenericBinaryArithmeticOverloads();
10126 break;
10127 }
10128}
10129
10130/// Add function candidates found via argument-dependent lookup
10131/// to the set of overloading candidates.
10132///
10133/// This routine performs argument-dependent name lookup based on the
10134/// given function name (which may also be an operator name) and adds
10135/// all of the overload candidates found by ADL to the overload
10136/// candidate set (C++ [basic.lookup.argdep]).
10137void
10139 SourceLocation Loc,
10140 ArrayRef<Expr *> Args,
10141 TemplateArgumentListInfo *ExplicitTemplateArgs,
10142 OverloadCandidateSet& CandidateSet,
10143 bool PartialOverloading) {
10144 ADLResult Fns;
10145
10146 // FIXME: This approach for uniquing ADL results (and removing
10147 // redundant candidates from the set) relies on pointer-equality,
10148 // which means we need to key off the canonical decl. However,
10149 // always going back to the canonical decl might not get us the
10150 // right set of default arguments. What default arguments are
10151 // we supposed to consider on ADL candidates, anyway?
10152
10153 // FIXME: Pass in the explicit template arguments?
10154 ArgumentDependentLookup(Name, Loc, Args, Fns);
10155
10156 // Erase all of the candidates we already knew about.
10157 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10158 CandEnd = CandidateSet.end();
10159 Cand != CandEnd; ++Cand)
10160 if (Cand->Function) {
10161 Fns.erase(Cand->Function);
10162 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
10163 Fns.erase(FunTmpl);
10164 }
10165
10166 // For each of the ADL candidates we found, add it to the overload
10167 // set.
10168 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10170
10171 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10172 if (ExplicitTemplateArgs)
10173 continue;
10174
10175 AddOverloadCandidate(
10176 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10177 PartialOverloading, /*AllowExplicit=*/true,
10178 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10179 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10180 AddOverloadCandidate(
10181 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10182 /*SuppressUserConversions=*/false, PartialOverloading,
10183 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10184 ADLCallKind::UsesADL, std::nullopt,
10186 }
10187 } else {
10188 auto *FTD = cast<FunctionTemplateDecl>(*I);
10189 AddTemplateOverloadCandidate(
10190 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10191 /*SuppressUserConversions=*/false, PartialOverloading,
10192 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10193 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10194 *this, Args, FTD->getTemplatedDecl())) {
10195 AddTemplateOverloadCandidate(
10196 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10197 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10198 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10200 }
10201 }
10202 }
10203}
10204
10205namespace {
10206enum class Comparison { Equal, Better, Worse };
10207}
10208
10209/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10210/// overload resolution.
10211///
10212/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10213/// Cand1's first N enable_if attributes have precisely the same conditions as
10214/// Cand2's first N enable_if attributes (where N = the number of enable_if
10215/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10216///
10217/// Note that you can have a pair of candidates such that Cand1's enable_if
10218/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10219/// worse than Cand1's.
10220static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10221 const FunctionDecl *Cand2) {
10222 // Common case: One (or both) decls don't have enable_if attrs.
10223 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10224 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10225 if (!Cand1Attr || !Cand2Attr) {
10226 if (Cand1Attr == Cand2Attr)
10227 return Comparison::Equal;
10228 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10229 }
10230
10231 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10232 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10233
10234 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10235 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10236 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10237 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10238
10239 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10240 // has fewer enable_if attributes than Cand2, and vice versa.
10241 if (!Cand1A)
10242 return Comparison::Worse;
10243 if (!Cand2A)
10244 return Comparison::Better;
10245
10246 Cand1ID.clear();
10247 Cand2ID.clear();
10248
10249 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10250 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10251 if (Cand1ID != Cand2ID)
10252 return Comparison::Worse;
10253 }
10254
10255 return Comparison::Equal;
10256}
10257
10258static Comparison
10260 const OverloadCandidate &Cand2) {
10261 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10262 !Cand2.Function->isMultiVersion())
10263 return Comparison::Equal;
10264
10265 // If both are invalid, they are equal. If one of them is invalid, the other
10266 // is better.
10267 if (Cand1.Function->isInvalidDecl()) {
10268 if (Cand2.Function->isInvalidDecl())
10269 return Comparison::Equal;
10270 return Comparison::Worse;
10271 }
10272 if (Cand2.Function->isInvalidDecl())
10273 return Comparison::Better;
10274
10275 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10276 // cpu_dispatch, else arbitrarily based on the identifiers.
10277 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10278 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10279 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10280 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10281
10282 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10283 return Comparison::Equal;
10284
10285 if (Cand1CPUDisp && !Cand2CPUDisp)
10286 return Comparison::Better;
10287 if (Cand2CPUDisp && !Cand1CPUDisp)
10288 return Comparison::Worse;
10289
10290 if (Cand1CPUSpec && Cand2CPUSpec) {
10291 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10292 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10293 ? Comparison::Better
10294 : Comparison::Worse;
10295
10296 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10297 FirstDiff = std::mismatch(
10298 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10299 Cand2CPUSpec->cpus_begin(),
10300 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10301 return LHS->getName() == RHS->getName();
10302 });
10303
10304 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10305 "Two different cpu-specific versions should not have the same "
10306 "identifier list, otherwise they'd be the same decl!");
10307 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10308 ? Comparison::Better
10309 : Comparison::Worse;
10310 }
10311 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10312}
10313
10314/// Compute the type of the implicit object parameter for the given function,
10315/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10316/// null QualType if there is a 'matches anything' implicit object parameter.
10317static std::optional<QualType>
10319 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10320 return std::nullopt;
10321
10322 auto *M = cast<CXXMethodDecl>(F);
10323 // Static member functions' object parameters match all types.
10324 if (M->isStatic())
10325 return QualType();
10326 return M->getFunctionObjectParameterReferenceType();
10327}
10328
10329// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10330// represent the same entity.
10331static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10332 const FunctionDecl *F2) {
10333 if (declaresSameEntity(F1, F2))
10334 return true;
10335 auto PT1 = F1->getPrimaryTemplate();
10336 auto PT2 = F2->getPrimaryTemplate();
10337 if (PT1 && PT2) {
10338 if (declaresSameEntity(PT1, PT2) ||
10339 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10340 PT2->getInstantiatedFromMemberTemplate()))
10341 return true;
10342 }
10343 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10344 // different functions with same params). Consider removing this (as no test
10345 // fail w/o it).
10346 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10347 if (First) {
10348 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10349 return *T;
10350 }
10351 assert(I < F->getNumParams());
10352 return F->getParamDecl(I++)->getType();
10353 };
10354
10355 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10356 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10357
10358 if (F1NumParams != F2NumParams)
10359 return false;
10360
10361 unsigned I1 = 0, I2 = 0;
10362 for (unsigned I = 0; I != F1NumParams; ++I) {
10363 QualType T1 = NextParam(F1, I1, I == 0);
10364 QualType T2 = NextParam(F2, I2, I == 0);
10365 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10366 if (!Context.hasSameUnqualifiedType(T1, T2))
10367 return false;
10368 }
10369 return true;
10370}
10371
10372/// We're allowed to use constraints partial ordering only if the candidates
10373/// have the same parameter types:
10374/// [over.match.best.general]p2.6
10375/// F1 and F2 are non-template functions with the same
10376/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10378 const OverloadCandidate &Cand1,
10379 const OverloadCandidate &Cand2) {
10380 if (!Cand1.Function || !Cand2.Function)
10381 return false;
10382
10383 FunctionDecl *Fn1 = Cand1.Function;
10384 FunctionDecl *Fn2 = Cand2.Function;
10385
10386 if (Fn1->isVariadic() != Fn1->isVariadic())
10387 return false;
10388
10390 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10391 return false;
10392
10393 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10394 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10395 if (Mem1 && Mem2) {
10396 // if they are member functions, both are direct members of the same class,
10397 // and
10398 if (Mem1->getParent() != Mem2->getParent())
10399 return false;
10400 // if both are non-static member functions, they have the same types for
10401 // their object parameters
10402 if (Mem1->isInstance() && Mem2->isInstance() &&
10404 Mem1->getFunctionObjectParameterReferenceType(),
10405 Mem1->getFunctionObjectParameterReferenceType()))
10406 return false;
10407 }
10408 return true;
10409}
10410
10411/// isBetterOverloadCandidate - Determines whether the first overload
10412/// candidate is a better candidate than the second (C++ 13.3.3p1).
10414 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10416 // Define viable functions to be better candidates than non-viable
10417 // functions.
10418 if (!Cand2.Viable)
10419 return Cand1.Viable;
10420 else if (!Cand1.Viable)
10421 return false;
10422
10423 // [CUDA] A function with 'never' preference is marked not viable, therefore
10424 // is never shown up here. The worst preference shown up here is 'wrong side',
10425 // e.g. an H function called by a HD function in device compilation. This is
10426 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10427 // function which is called only by an H function. A deferred diagnostic will
10428 // be triggered if it is emitted. However a wrong-sided function is still
10429 // a viable candidate here.
10430 //
10431 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10432 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10433 // can be emitted, Cand1 is not better than Cand2. This rule should have
10434 // precedence over other rules.
10435 //
10436 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10437 // other rules should be used to determine which is better. This is because
10438 // host/device based overloading resolution is mostly for determining
10439 // viability of a function. If two functions are both viable, other factors
10440 // should take precedence in preference, e.g. the standard-defined preferences
10441 // like argument conversion ranks or enable_if partial-ordering. The
10442 // preference for pass-object-size parameters is probably most similar to a
10443 // type-based-overloading decision and so should take priority.
10444 //
10445 // If other rules cannot determine which is better, CUDA preference will be
10446 // used again to determine which is better.
10447 //
10448 // TODO: Currently IdentifyPreference does not return correct values
10449 // for functions called in global variable initializers due to missing
10450 // correct context about device/host. Therefore we can only enforce this
10451 // rule when there is a caller. We should enforce this rule for functions
10452 // in global variable initializers once proper context is added.
10453 //
10454 // TODO: We can only enable the hostness based overloading resolution when
10455 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10456 // overloading resolution diagnostics.
10457 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10458 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10459 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10460 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10461 bool IsCand1ImplicitHD =
10463 bool IsCand2ImplicitHD =
10465 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10466 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10467 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10468 // The implicit HD function may be a function in a system header which
10469 // is forced by pragma. In device compilation, if we prefer HD candidates
10470 // over wrong-sided candidates, overloading resolution may change, which
10471 // may result in non-deferrable diagnostics. As a workaround, we let
10472 // implicit HD candidates take equal preference as wrong-sided candidates.
10473 // This will preserve the overloading resolution.
10474 // TODO: We still need special handling of implicit HD functions since
10475 // they may incur other diagnostics to be deferred. We should make all
10476 // host/device related diagnostics deferrable and remove special handling
10477 // of implicit HD functions.
10478 auto EmitThreshold =
10479 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10480 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10483 auto Cand1Emittable = P1 > EmitThreshold;
10484 auto Cand2Emittable = P2 > EmitThreshold;
10485 if (Cand1Emittable && !Cand2Emittable)
10486 return true;
10487 if (!Cand1Emittable && Cand2Emittable)
10488 return false;
10489 }
10490 }
10491
10492 // C++ [over.match.best]p1: (Changed in C++23)
10493 //
10494 // -- if F is a static member function, ICS1(F) is defined such
10495 // that ICS1(F) is neither better nor worse than ICS1(G) for
10496 // any function G, and, symmetrically, ICS1(G) is neither
10497 // better nor worse than ICS1(F).
10498 unsigned StartArg = 0;
10499 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10500 StartArg = 1;
10501
10502 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10503 // We don't allow incompatible pointer conversions in C++.
10504 if (!S.getLangOpts().CPlusPlus)
10505 return ICS.isStandard() &&
10506 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10507
10508 // The only ill-formed conversion we allow in C++ is the string literal to
10509 // char* conversion, which is only considered ill-formed after C++11.
10510 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10512 };
10513
10514 // Define functions that don't require ill-formed conversions for a given
10515 // argument to be better candidates than functions that do.
10516 unsigned NumArgs = Cand1.Conversions.size();
10517 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10518 bool HasBetterConversion = false;
10519 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10520 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10521 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10522 if (Cand1Bad != Cand2Bad) {
10523 if (Cand1Bad)
10524 return false;
10525 HasBetterConversion = true;
10526 }
10527 }
10528
10529 if (HasBetterConversion)
10530 return true;
10531
10532 // C++ [over.match.best]p1:
10533 // A viable function F1 is defined to be a better function than another
10534 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10535 // conversion sequence than ICSi(F2), and then...
10536 bool HasWorseConversion = false;
10537 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10539 Cand1.Conversions[ArgIdx],
10540 Cand2.Conversions[ArgIdx])) {
10542 // Cand1 has a better conversion sequence.
10543 HasBetterConversion = true;
10544 break;
10545
10547 if (Cand1.Function && Cand2.Function &&
10548 Cand1.isReversed() != Cand2.isReversed() &&
10549 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10550 // Work around large-scale breakage caused by considering reversed
10551 // forms of operator== in C++20:
10552 //
10553 // When comparing a function against a reversed function, if we have a
10554 // better conversion for one argument and a worse conversion for the
10555 // other, the implicit conversion sequences are treated as being equally
10556 // good.
10557 //
10558 // This prevents a comparison function from being considered ambiguous
10559 // with a reversed form that is written in the same way.
10560 //
10561 // We diagnose this as an extension from CreateOverloadedBinOp.
10562 HasWorseConversion = true;
10563 break;
10564 }
10565
10566 // Cand1 can't be better than Cand2.
10567 return false;
10568
10570 // Do nothing.
10571 break;
10572 }
10573 }
10574
10575 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10576 // ICSj(F2), or, if not that,
10577 if (HasBetterConversion && !HasWorseConversion)
10578 return true;
10579
10580 // -- the context is an initialization by user-defined conversion
10581 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10582 // from the return type of F1 to the destination type (i.e.,
10583 // the type of the entity being initialized) is a better
10584 // conversion sequence than the standard conversion sequence
10585 // from the return type of F2 to the destination type.
10587 Cand1.Function && Cand2.Function &&
10588 isa<CXXConversionDecl>(Cand1.Function) &&
10589 isa<CXXConversionDecl>(Cand2.Function)) {
10590 // First check whether we prefer one of the conversion functions over the
10591 // other. This only distinguishes the results in non-standard, extension
10592 // cases such as the conversion from a lambda closure type to a function
10593 // pointer or block.
10598 Cand1.FinalConversion,
10599 Cand2.FinalConversion);
10600
10603
10604 // FIXME: Compare kind of reference binding if conversion functions
10605 // convert to a reference type used in direct reference binding, per
10606 // C++14 [over.match.best]p1 section 2 bullet 3.
10607 }
10608
10609 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10610 // as combined with the resolution to CWG issue 243.
10611 //
10612 // When the context is initialization by constructor ([over.match.ctor] or
10613 // either phase of [over.match.list]), a constructor is preferred over
10614 // a conversion function.
10615 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10616 Cand1.Function && Cand2.Function &&
10617 isa<CXXConstructorDecl>(Cand1.Function) !=
10618 isa<CXXConstructorDecl>(Cand2.Function))
10619 return isa<CXXConstructorDecl>(Cand1.Function);
10620
10621 // -- F1 is a non-template function and F2 is a function template
10622 // specialization, or, if not that,
10623 bool Cand1IsSpecialization = Cand1.Function &&
10625 bool Cand2IsSpecialization = Cand2.Function &&
10627 if (Cand1IsSpecialization != Cand2IsSpecialization)
10628 return Cand2IsSpecialization;
10629
10630 // -- F1 and F2 are function template specializations, and the function
10631 // template for F1 is more specialized than the template for F2
10632 // according to the partial ordering rules described in 14.5.5.2, or,
10633 // if not that,
10634 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10635 const auto *Obj1Context =
10636 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10637 const auto *Obj2Context =
10638 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10639 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10641 Cand2.Function->getPrimaryTemplate(), Loc,
10642 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10643 : TPOC_Call,
10645 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10646 : QualType{},
10647 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10648 : QualType{},
10649 Cand1.isReversed() ^ Cand2.isReversed())) {
10650 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10651 }
10652 }
10653
10654 // -— F1 and F2 are non-template functions with the same
10655 // parameter-type-lists, and F1 is more constrained than F2 [...],
10656 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10657 sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10658 FunctionDecl *Function1 = Cand1.Function;
10659 FunctionDecl *Function2 = Cand2.Function;
10660 if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10661 Function1 = MF;
10662 if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10663 Function2 = MF;
10664
10665 const Expr *RC1 = Function1->getTrailingRequiresClause();
10666 const Expr *RC2 = Function2->getTrailingRequiresClause();
10667 if (RC1 && RC2) {
10668 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10669 if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10670 AtLeastAsConstrained1) ||
10671 S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10672 AtLeastAsConstrained2))
10673 return false;
10674 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10675 return AtLeastAsConstrained1;
10676 } else if (RC1 || RC2) {
10677 return RC1 != nullptr;
10678 }
10679 }
10680
10681 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10682 // class B of D, and for all arguments the corresponding parameters of
10683 // F1 and F2 have the same type.
10684 // FIXME: Implement the "all parameters have the same type" check.
10685 bool Cand1IsInherited =
10686 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10687 bool Cand2IsInherited =
10688 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10689 if (Cand1IsInherited != Cand2IsInherited)
10690 return Cand2IsInherited;
10691 else if (Cand1IsInherited) {
10692 assert(Cand2IsInherited);
10693 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10694 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10695 if (Cand1Class->isDerivedFrom(Cand2Class))
10696 return true;
10697 if (Cand2Class->isDerivedFrom(Cand1Class))
10698 return false;
10699 // Inherited from sibling base classes: still ambiguous.
10700 }
10701
10702 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10703 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10704 // with reversed order of parameters and F1 is not
10705 //
10706 // We rank reversed + different operator as worse than just reversed, but
10707 // that comparison can never happen, because we only consider reversing for
10708 // the maximally-rewritten operator (== or <=>).
10709 if (Cand1.RewriteKind != Cand2.RewriteKind)
10710 return Cand1.RewriteKind < Cand2.RewriteKind;
10711
10712 // Check C++17 tie-breakers for deduction guides.
10713 {
10714 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10715 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10716 if (Guide1 && Guide2) {
10717 // -- F1 is generated from a deduction-guide and F2 is not
10718 if (Guide1->isImplicit() != Guide2->isImplicit())
10719 return Guide2->isImplicit();
10720
10721 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10722 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10723 return true;
10724 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10725 return false;
10726
10727 // --F1 is generated from a non-template constructor and F2 is generated
10728 // from a constructor template
10729 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10730 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10731 if (Constructor1 && Constructor2) {
10732 bool isC1Templated = Constructor1->getTemplatedKind() !=
10734 bool isC2Templated = Constructor2->getTemplatedKind() !=
10736 if (isC1Templated != isC2Templated)
10737 return isC2Templated;
10738 }
10739 }
10740 }
10741
10742 // Check for enable_if value-based overload resolution.
10743 if (Cand1.Function && Cand2.Function) {
10744 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10745 if (Cmp != Comparison::Equal)
10746 return Cmp == Comparison::Better;
10747 }
10748
10749 bool HasPS1 = Cand1.Function != nullptr &&
10751 bool HasPS2 = Cand2.Function != nullptr &&
10753 if (HasPS1 != HasPS2 && HasPS1)
10754 return true;
10755
10756 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10757 if (MV == Comparison::Better)
10758 return true;
10759 if (MV == Comparison::Worse)
10760 return false;
10761
10762 // If other rules cannot determine which is better, CUDA preference is used
10763 // to determine which is better.
10764 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10765 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10766 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10767 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10768 }
10769
10770 // General member function overloading is handled above, so this only handles
10771 // constructors with address spaces.
10772 // This only handles address spaces since C++ has no other
10773 // qualifier that can be used with constructors.
10774 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10775 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10776 if (CD1 && CD2) {
10777 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10778 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10779 if (AS1 != AS2) {
10781 return true;
10783 return false;
10784 }
10785 }
10786
10787 return false;
10788}
10789
10790/// Determine whether two declarations are "equivalent" for the purposes of
10791/// name lookup and overload resolution. This applies when the same internal/no
10792/// linkage entity is defined by two modules (probably by textually including
10793/// the same header). In such a case, we don't consider the declarations to
10794/// declare the same entity, but we also don't want lookups with both
10795/// declarations visible to be ambiguous in some cases (this happens when using
10796/// a modularized libstdc++).
10798 const NamedDecl *B) {
10799 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10800 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10801 if (!VA || !VB)
10802 return false;
10803
10804 // The declarations must be declaring the same name as an internal linkage
10805 // entity in different modules.
10806 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10807 VB->getDeclContext()->getRedeclContext()) ||
10808 getOwningModule(VA) == getOwningModule(VB) ||
10809 VA->isExternallyVisible() || VB->isExternallyVisible())
10810 return false;
10811
10812 // Check that the declarations appear to be equivalent.
10813 //
10814 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10815 // For constants and functions, we should check the initializer or body is
10816 // the same. For non-constant variables, we shouldn't allow it at all.
10817 if (Context.hasSameType(VA->getType(), VB->getType()))
10818 return true;
10819
10820 // Enum constants within unnamed enumerations will have different types, but
10821 // may still be similar enough to be interchangeable for our purposes.
10822 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10823 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10824 // Only handle anonymous enums. If the enumerations were named and
10825 // equivalent, they would have been merged to the same type.
10826 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10827 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10828 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10829 !Context.hasSameType(EnumA->getIntegerType(),
10830 EnumB->getIntegerType()))
10831 return false;
10832 // Allow this only if the value is the same for both enumerators.
10833 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10834 }
10835 }
10836
10837 // Nothing else is sufficiently similar.
10838 return false;
10839}
10840
10843 assert(D && "Unknown declaration");
10844 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10845
10846 Module *M = getOwningModule(D);
10847 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10848 << !M << (M ? M->getFullModuleName() : "");
10849
10850 for (auto *E : Equiv) {
10851 Module *M = getOwningModule(E);
10852 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10853 << !M << (M ? M->getFullModuleName() : "");
10854 }
10855}
10856
10858 return FailureKind == ovl_fail_bad_deduction &&
10859 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10861 static_cast<CNSInfo *>(DeductionFailure.Data)
10862 ->Satisfaction.ContainsErrors;
10863}
10864
10865/// Computes the best viable function (C++ 13.3.3)
10866/// within an overload candidate set.
10867///
10868/// \param Loc The location of the function name (or operator symbol) for
10869/// which overload resolution occurs.
10870///
10871/// \param Best If overload resolution was successful or found a deleted
10872/// function, \p Best points to the candidate function found.
10873///
10874/// \returns The result of overload resolution.
10877 iterator &Best) {
10879 std::transform(begin(), end(), std::back_inserter(Candidates),
10880 [](OverloadCandidate &Cand) { return &Cand; });
10881
10882 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10883 // are accepted by both clang and NVCC. However, during a particular
10884 // compilation mode only one call variant is viable. We need to
10885 // exclude non-viable overload candidates from consideration based
10886 // only on their host/device attributes. Specifically, if one
10887 // candidate call is WrongSide and the other is SameSide, we ignore
10888 // the WrongSide candidate.
10889 // We only need to remove wrong-sided candidates here if
10890 // -fgpu-exclude-wrong-side-overloads is off. When
10891 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10892 // uniformly in isBetterOverloadCandidate.
10893 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10894 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10895 bool ContainsSameSideCandidate =
10896 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10897 // Check viable function only.
10898 return Cand->Viable && Cand->Function &&
10899 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10901 });
10902 if (ContainsSameSideCandidate) {
10903 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10904 // Check viable function only to avoid unnecessary data copying/moving.
10905 return Cand->Viable && Cand->Function &&
10906 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10908 };
10909 llvm::erase_if(Candidates, IsWrongSideCandidate);
10910 }
10911 }
10912
10913 // Find the best viable function.
10914 Best = end();
10915 for (auto *Cand : Candidates) {
10916 Cand->Best = false;
10917 if (Cand->Viable) {
10918 if (Best == end() ||
10919 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10920 Best = Cand;
10921 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10922 // This candidate has constraint that we were unable to evaluate because
10923 // it referenced an expression that contained an error. Rather than fall
10924 // back onto a potentially unintended candidate (made worse by
10925 // subsuming constraints), treat this as 'no viable candidate'.
10926 Best = end();
10927 return OR_No_Viable_Function;
10928 }
10929 }
10930
10931 // If we didn't find any viable functions, abort.
10932 if (Best == end())
10933 return OR_No_Viable_Function;
10934
10936
10938 PendingBest.push_back(&*Best);
10939 Best->Best = true;
10940
10941 // Make sure that this function is better than every other viable
10942 // function. If not, we have an ambiguity.
10943 while (!PendingBest.empty()) {
10944 auto *Curr = PendingBest.pop_back_val();
10945 for (auto *Cand : Candidates) {
10946 if (Cand->Viable && !Cand->Best &&
10947 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10948 PendingBest.push_back(Cand);
10949 Cand->Best = true;
10950
10952 Curr->Function))
10953 EquivalentCands.push_back(Cand->Function);
10954 else
10955 Best = end();
10956 }
10957 }
10958 }
10959
10960 // If we found more than one best candidate, this is ambiguous.
10961 if (Best == end())
10962 return OR_Ambiguous;
10963
10964 // Best is the best viable function.
10965 if (Best->Function && Best->Function->isDeleted())
10966 return OR_Deleted;
10967
10968 if (!EquivalentCands.empty())
10970 EquivalentCands);
10971
10972 return OR_Success;
10973}
10974
10975namespace {
10976
10977enum OverloadCandidateKind {
10978 oc_function,
10979 oc_method,
10980 oc_reversed_binary_operator,
10981 oc_constructor,
10982 oc_implicit_default_constructor,
10983 oc_implicit_copy_constructor,
10984 oc_implicit_move_constructor,
10985 oc_implicit_copy_assignment,
10986 oc_implicit_move_assignment,
10987 oc_implicit_equality_comparison,
10988 oc_inherited_constructor
10989};
10990
10991enum OverloadCandidateSelect {
10992 ocs_non_template,
10993 ocs_template,
10994 ocs_described_template,
10995};
10996
10997static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10998ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10999 const FunctionDecl *Fn,
11001 std::string &Description) {
11002
11003 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11004 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11005 isTemplate = true;
11006 Description = S.getTemplateArgumentBindingsText(
11007 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11008 }
11009
11010 OverloadCandidateSelect Select = [&]() {
11011 if (!Description.empty())
11012 return ocs_described_template;
11013 return isTemplate ? ocs_template : ocs_non_template;
11014 }();
11015
11016 OverloadCandidateKind Kind = [&]() {
11017 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11018 return oc_implicit_equality_comparison;
11019
11020 if (CRK & CRK_Reversed)
11021 return oc_reversed_binary_operator;
11022
11023 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11024 if (!Ctor->isImplicit()) {
11025 if (isa<ConstructorUsingShadowDecl>(Found))
11026 return oc_inherited_constructor;
11027 else
11028 return oc_constructor;
11029 }
11030
11031 if (Ctor->isDefaultConstructor())
11032 return oc_implicit_default_constructor;
11033
11034 if (Ctor->isMoveConstructor())
11035 return oc_implicit_move_constructor;
11036
11037 assert(Ctor->isCopyConstructor() &&
11038 "unexpected sort of implicit constructor");
11039 return oc_implicit_copy_constructor;
11040 }
11041
11042 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11043 // This actually gets spelled 'candidate function' for now, but
11044 // it doesn't hurt to split it out.
11045 if (!Meth->isImplicit())
11046 return oc_method;
11047
11048 if (Meth->isMoveAssignmentOperator())
11049 return oc_implicit_move_assignment;
11050
11051 if (Meth->isCopyAssignmentOperator())
11052 return oc_implicit_copy_assignment;
11053
11054 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11055 return oc_method;
11056 }
11057
11058 return oc_function;
11059 }();
11060
11061 return std::make_pair(Kind, Select);
11062}
11063
11064void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11065 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11066 // set.
11067 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11068 S.Diag(FoundDecl->getLocation(),
11069 diag::note_ovl_candidate_inherited_constructor)
11070 << Shadow->getNominatedBaseClass();
11071}
11072
11073} // end anonymous namespace
11074
11076 const FunctionDecl *FD) {
11077 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11078 bool AlwaysTrue;
11079 if (EnableIf->getCond()->isValueDependent() ||
11080 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11081 return false;
11082 if (!AlwaysTrue)
11083 return false;
11084 }
11085 return true;
11086}
11087
11088/// Returns true if we can take the address of the function.
11089///
11090/// \param Complain - If true, we'll emit a diagnostic
11091/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11092/// we in overload resolution?
11093/// \param Loc - The location of the statement we're complaining about. Ignored
11094/// if we're not complaining, or if we're in overload resolution.
11096 bool Complain,
11097 bool InOverloadResolution,
11098 SourceLocation Loc) {
11099 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11100 if (Complain) {
11101 if (InOverloadResolution)
11102 S.Diag(FD->getBeginLoc(),
11103 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11104 else
11105 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11106 }
11107 return false;
11108 }
11109
11110 if (FD->getTrailingRequiresClause()) {
11111 ConstraintSatisfaction Satisfaction;
11112 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11113 return false;
11114 if (!Satisfaction.IsSatisfied) {
11115 if (Complain) {
11116 if (InOverloadResolution) {
11117 SmallString<128> TemplateArgString;
11118 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11119 TemplateArgString += " ";
11120 TemplateArgString += S.getTemplateArgumentBindingsText(
11121 FunTmpl->getTemplateParameters(),
11123 }
11124
11125 S.Diag(FD->getBeginLoc(),
11126 diag::note_ovl_candidate_unsatisfied_constraints)
11127 << TemplateArgString;
11128 } else
11129 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11130 << FD;
11131 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11132 }
11133 return false;
11134 }
11135 }
11136
11137 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11138 return P->hasAttr<PassObjectSizeAttr>();
11139 });
11140 if (I == FD->param_end())
11141 return true;
11142
11143 if (Complain) {
11144 // Add one to ParamNo because it's user-facing
11145 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11146 if (InOverloadResolution)
11147 S.Diag(FD->getLocation(),
11148 diag::note_ovl_candidate_has_pass_object_size_params)
11149 << ParamNo;
11150 else
11151 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11152 << FD << ParamNo;
11153 }
11154 return false;
11155}
11156
11158 const FunctionDecl *FD) {
11159 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11160 /*InOverloadResolution=*/true,
11161 /*Loc=*/SourceLocation());
11162}
11163
11165 bool Complain,
11166 SourceLocation Loc) {
11167 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11168 /*InOverloadResolution=*/false,
11169 Loc);
11170}
11171
11172// Don't print candidates other than the one that matches the calling
11173// convention of the call operator, since that is guaranteed to exist.
11175 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11176
11177 if (!ConvD)
11178 return false;
11179 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11180 if (!RD->isLambda())
11181 return false;
11182
11183 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11184 CallingConv CallOpCC =
11185 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11186 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11187 CallingConv ConvToCC =
11188 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11189
11190 return ConvToCC != CallOpCC;
11191}
11192
11193// Notes the location of an overload candidate.
11195 OverloadCandidateRewriteKind RewriteKind,
11196 QualType DestType, bool TakingAddress) {
11197 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11198 return;
11199 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11200 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11201 return;
11202 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11203 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11204 return;
11206 return;
11207
11208 std::string FnDesc;
11209 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11210 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11211 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11212 << (unsigned)KSPair.first << (unsigned)KSPair.second
11213 << Fn << FnDesc;
11214
11215 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11216 Diag(Fn->getLocation(), PD);
11217 MaybeEmitInheritedConstructorNote(*this, Found);
11218}
11219
11220static void
11222 // Perhaps the ambiguity was caused by two atomic constraints that are
11223 // 'identical' but not equivalent:
11224 //
11225 // void foo() requires (sizeof(T) > 4) { } // #1
11226 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11227 //
11228 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11229 // #2 to subsume #1, but these constraint are not considered equivalent
11230 // according to the subsumption rules because they are not the same
11231 // source-level construct. This behavior is quite confusing and we should try
11232 // to help the user figure out what happened.
11233
11234 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11235 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11236 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11237 if (!I->Function)
11238 continue;
11240 if (auto *Template = I->Function->getPrimaryTemplate())
11241 Template->getAssociatedConstraints(AC);
11242 else
11243 I->Function->getAssociatedConstraints(AC);
11244 if (AC.empty())
11245 continue;
11246 if (FirstCand == nullptr) {
11247 FirstCand = I->Function;
11248 FirstAC = AC;
11249 } else if (SecondCand == nullptr) {
11250 SecondCand = I->Function;
11251 SecondAC = AC;
11252 } else {
11253 // We have more than one pair of constrained functions - this check is
11254 // expensive and we'd rather not try to diagnose it.
11255 return;
11256 }
11257 }
11258 if (!SecondCand)
11259 return;
11260 // The diagnostic can only happen if there are associated constraints on
11261 // both sides (there needs to be some identical atomic constraint).
11262 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11263 SecondCand, SecondAC))
11264 // Just show the user one diagnostic, they'll probably figure it out
11265 // from here.
11266 return;
11267}
11268
11269// Notes the location of all overload candidates designated through
11270// OverloadedExpr
11271void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11272 bool TakingAddress) {
11273 assert(OverloadedExpr->getType() == Context.OverloadTy);
11274
11275 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11276 OverloadExpr *OvlExpr = Ovl.Expression;
11277
11278 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11279 IEnd = OvlExpr->decls_end();
11280 I != IEnd; ++I) {
11281 if (FunctionTemplateDecl *FunTmpl =
11282 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11283 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11284 TakingAddress);
11285 } else if (FunctionDecl *Fun
11286 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11287 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11288 }
11289 }
11290}
11291
11292/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11293/// "lead" diagnostic; it will be given two arguments, the source and
11294/// target types of the conversion.
11296 Sema &S,
11297 SourceLocation CaretLoc,
11298 const PartialDiagnostic &PDiag) const {
11299 S.Diag(CaretLoc, PDiag)
11300 << Ambiguous.getFromType() << Ambiguous.getToType();
11301 unsigned CandsShown = 0;
11303 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11304 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11305 break;
11306 ++CandsShown;
11307 S.NoteOverloadCandidate(I->first, I->second);
11308 }
11309 S.Diags.overloadCandidatesShown(CandsShown);
11310 if (I != E)
11311 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11312}
11313
11315 unsigned I, bool TakingCandidateAddress) {
11316 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11317 assert(Conv.isBad());
11318 assert(Cand->Function && "for now, candidate must be a function");
11319 FunctionDecl *Fn = Cand->Function;
11320
11321 // There's a conversion slot for the object argument if this is a
11322 // non-constructor method. Note that 'I' corresponds the
11323 // conversion-slot index.
11324 bool isObjectArgument = false;
11325 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11326 if (I == 0)
11327 isObjectArgument = true;
11328 else
11329 I--;
11330 }
11331
11332 std::string FnDesc;
11333 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11334 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11335 FnDesc);
11336
11337 Expr *FromExpr = Conv.Bad.FromExpr;
11338 QualType FromTy = Conv.Bad.getFromType();
11339 QualType ToTy = Conv.Bad.getToType();
11340 SourceRange ToParamRange =
11341 !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
11342
11343 if (FromTy == S.Context.OverloadTy) {
11344 assert(FromExpr && "overload set argument came from implicit argument?");
11345 Expr *E = FromExpr->IgnoreParens();
11346 if (isa<UnaryOperator>(E))
11347 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11348 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11349
11350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11351 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11352 << ToParamRange << ToTy << Name << I + 1;
11353 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11354 return;
11355 }
11356
11357 // Do some hand-waving analysis to see if the non-viability is due
11358 // to a qualifier mismatch.
11359 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11360 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11361 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11362 CToTy = RT->getPointeeType();
11363 else {
11364 // TODO: detect and diagnose the full richness of const mismatches.
11365 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11366 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11367 CFromTy = FromPT->getPointeeType();
11368 CToTy = ToPT->getPointeeType();
11369 }
11370 }
11371
11372 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11373 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11374 Qualifiers FromQs = CFromTy.getQualifiers();
11375 Qualifiers ToQs = CToTy.getQualifiers();
11376
11377 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11378 if (isObjectArgument)
11379 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11380 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11381 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11382 else
11383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11384 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11385 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11386 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11387 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11388 return;
11389 }
11390
11391 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11393 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11394 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11395 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11396 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11397 return;
11398 }
11399
11400 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11402 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11403 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11404 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11405 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11406 return;
11407 }
11408
11409 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11410 assert(CVR && "expected qualifiers mismatch");
11411
11412 if (isObjectArgument) {
11413 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11414 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11415 << FromTy << (CVR - 1);
11416 } else {
11417 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11418 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11419 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11420 }
11421 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11422 return;
11423 }
11424
11427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11428 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11429 << (unsigned)isObjectArgument << I + 1
11431 << ToParamRange;
11432 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11433 return;
11434 }
11435
11436 // Special diagnostic for failure to convert an initializer list, since
11437 // telling the user that it has type void is not useful.
11438 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11439 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11440 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11441 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11444 ? 2
11445 : 0);
11446 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11447 return;
11448 }
11449
11450 // Diagnose references or pointers to incomplete types differently,
11451 // since it's far from impossible that the incompleteness triggered
11452 // the failure.
11453 QualType TempFromTy = FromTy.getNonReferenceType();
11454 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11455 TempFromTy = PTy->getPointeeType();
11456 if (TempFromTy->isIncompleteType()) {
11457 // Emit the generic diagnostic and, optionally, add the hints to it.
11458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11459 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11460 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11461 << (unsigned)(Cand->Fix.Kind);
11462
11463 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11464 return;
11465 }
11466
11467 // Diagnose base -> derived pointer conversions.
11468 unsigned BaseToDerivedConversion = 0;
11469 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11470 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11471 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11472 FromPtrTy->getPointeeType()) &&
11473 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11474 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11475 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11476 FromPtrTy->getPointeeType()))
11477 BaseToDerivedConversion = 1;
11478 }
11479 } else if (const ObjCObjectPointerType *FromPtrTy
11480 = FromTy->getAs<ObjCObjectPointerType>()) {
11481 if (const ObjCObjectPointerType *ToPtrTy
11482 = ToTy->getAs<ObjCObjectPointerType>())
11483 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11484 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11485 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11486 FromPtrTy->getPointeeType()) &&
11487 FromIface->isSuperClassOf(ToIface))
11488 BaseToDerivedConversion = 2;
11489 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11490 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11491 !FromTy->isIncompleteType() &&
11492 !ToRefTy->getPointeeType()->isIncompleteType() &&
11493 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11494 BaseToDerivedConversion = 3;
11495 }
11496 }
11497
11498 if (BaseToDerivedConversion) {
11499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11500 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11501 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11502 << I + 1;
11503 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11504 return;
11505 }
11506
11507 if (isa<ObjCObjectPointerType>(CFromTy) &&
11508 isa<PointerType>(CToTy)) {
11509 Qualifiers FromQs = CFromTy.getQualifiers();
11510 Qualifiers ToQs = CToTy.getQualifiers();
11511 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11513 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11514 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11515 << I + 1;
11516 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11517 return;
11518 }
11519 }
11520
11521 if (TakingCandidateAddress &&
11523 return;
11524
11525 // Emit the generic diagnostic and, optionally, add the hints to it.
11526 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11527 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11528 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11529 << (unsigned)(Cand->Fix.Kind);
11530
11531 // Check that location of Fn is not in system header.
11532 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11533 // If we can fix the conversion, suggest the FixIts.
11534 for (const FixItHint &HI : Cand->Fix.Hints)
11535 FDiag << HI;
11536 }
11537
11538 S.Diag(Fn->getLocation(), FDiag);
11539
11540 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11541}
11542
11543/// Additional arity mismatch diagnosis specific to a function overload
11544/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11545/// over a candidate in any candidate set.
11547 unsigned NumArgs) {
11548 FunctionDecl *Fn = Cand->Function;
11549 unsigned MinParams = Fn->getMinRequiredArguments();
11550
11551 // With invalid overloaded operators, it's possible that we think we
11552 // have an arity mismatch when in fact it looks like we have the
11553 // right number of arguments, because only overloaded operators have
11554 // the weird behavior of overloading member and non-member functions.
11555 // Just don't report anything.
11556 if (Fn->isInvalidDecl() &&
11558 return true;
11559
11560 if (NumArgs < MinParams) {
11561 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11563 Cand->DeductionFailure.getResult() ==
11565 } else {
11566 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11568 Cand->DeductionFailure.getResult() ==
11570 }
11571
11572 return false;
11573}
11574
11575/// General arity mismatch diagnosis over a candidate in a candidate set.
11576static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11577 unsigned NumFormalArgs) {
11578 assert(isa<FunctionDecl>(D) &&
11579 "The templated declaration should at least be a function"
11580 " when diagnosing bad template argument deduction due to too many"
11581 " or too few arguments");
11582
11583 FunctionDecl *Fn = cast<FunctionDecl>(D);
11584
11585 // TODO: treat calls to a missing default constructor as a special case
11586 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11587 unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11588
11589 // at least / at most / exactly
11590 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11591 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11592 unsigned mode, modeCount;
11593 if (NumFormalArgs < MinParams) {
11594 if (MinParams != ParamCount || FnTy->isVariadic() ||
11595 FnTy->isTemplateVariadic())
11596 mode = 0; // "at least"
11597 else
11598 mode = 2; // "exactly"
11599 modeCount = MinParams;
11600 } else {
11601 if (MinParams != ParamCount)
11602 mode = 1; // "at most"
11603 else
11604 mode = 2; // "exactly"
11605 modeCount = ParamCount;
11606 }
11607
11608 std::string Description;
11609 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11610 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11611
11612 if (modeCount == 1 &&
11613 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11614 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11615 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11616 << Description << mode
11617 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11618 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11619 else
11620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11621 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11622 << Description << mode << modeCount << NumFormalArgs
11623 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11624
11625 MaybeEmitInheritedConstructorNote(S, Found);
11626}
11627
11628/// Arity mismatch diagnosis specific to a function overload candidate.
11630 unsigned NumFormalArgs) {
11631 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11632 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11633}
11634
11636 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11637 return TD;
11638 llvm_unreachable("Unsupported: Getting the described template declaration"
11639 " for bad deduction diagnosis");
11640}
11641
11642/// Diagnose a failed template-argument deduction.
11643static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11644 DeductionFailureInfo &DeductionFailure,
11645 unsigned NumArgs,
11646 bool TakingCandidateAddress) {
11647 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11648 NamedDecl *ParamD;
11649 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11650 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11651 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11652 switch (DeductionFailure.getResult()) {
11654 llvm_unreachable(
11655 "TemplateDeductionResult::Success while diagnosing bad deduction");
11657 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11658 "while diagnosing bad deduction");
11661 return;
11662
11664 assert(ParamD && "no parameter found for incomplete deduction result");
11665 S.Diag(Templated->getLocation(),
11666 diag::note_ovl_candidate_incomplete_deduction)
11667 << ParamD->getDeclName();
11668 MaybeEmitInheritedConstructorNote(S, Found);
11669 return;
11670 }
11671
11673 assert(ParamD && "no parameter found for incomplete deduction result");
11674 S.Diag(Templated->getLocation(),
11675 diag::note_ovl_candidate_incomplete_deduction_pack)
11676 << ParamD->getDeclName()
11677 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11678 << *DeductionFailure.getFirstArg();
11679 MaybeEmitInheritedConstructorNote(S, Found);
11680 return;
11681 }
11682
11684 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11685 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11686
11687 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11688
11689 // Param will have been canonicalized, but it should just be a
11690 // qualified version of ParamD, so move the qualifiers to that.
11692 Qs.strip(Param);
11693 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11694 assert(S.Context.hasSameType(Param, NonCanonParam));
11695
11696 // Arg has also been canonicalized, but there's nothing we can do
11697 // about that. It also doesn't matter as much, because it won't
11698 // have any template parameters in it (because deduction isn't
11699 // done on dependent types).
11700 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11701
11702 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11703 << ParamD->getDeclName() << Arg << NonCanonParam;
11704 MaybeEmitInheritedConstructorNote(S, Found);
11705 return;
11706 }
11707
11709 assert(ParamD && "no parameter found for inconsistent deduction result");
11710 int which = 0;
11711 if (isa<TemplateTypeParmDecl>(ParamD))
11712 which = 0;
11713 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11714 // Deduction might have failed because we deduced arguments of two
11715 // different types for a non-type template parameter.
11716 // FIXME: Use a different TDK value for this.
11717 QualType T1 =
11718 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11719 QualType T2 =
11720 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11721 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11722 S.Diag(Templated->getLocation(),
11723 diag::note_ovl_candidate_inconsistent_deduction_types)
11724 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11725 << *DeductionFailure.getSecondArg() << T2;
11726 MaybeEmitInheritedConstructorNote(S, Found);
11727 return;
11728 }
11729
11730 which = 1;
11731 } else {
11732 which = 2;
11733 }
11734
11735 // Tweak the diagnostic if the problem is that we deduced packs of
11736 // different arities. We'll print the actual packs anyway in case that
11737 // includes additional useful information.
11738 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11739 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11740 DeductionFailure.getFirstArg()->pack_size() !=
11741 DeductionFailure.getSecondArg()->pack_size()) {
11742 which = 3;
11743 }
11744
11745 S.Diag(Templated->getLocation(),
11746 diag::note_ovl_candidate_inconsistent_deduction)
11747 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11748 << *DeductionFailure.getSecondArg();
11749 MaybeEmitInheritedConstructorNote(S, Found);
11750 return;
11751 }
11752
11754 assert(ParamD && "no parameter found for invalid explicit arguments");
11755 if (ParamD->getDeclName())
11756 S.Diag(Templated->getLocation(),
11757 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11758 << ParamD->getDeclName();
11759 else {
11760 int index = 0;
11761 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11762 index = TTP->getIndex();
11763 else if (NonTypeTemplateParmDecl *NTTP
11764 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11765 index = NTTP->getIndex();
11766 else
11767 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11768 S.Diag(Templated->getLocation(),
11769 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11770 << (index + 1);
11771 }
11772 MaybeEmitInheritedConstructorNote(S, Found);
11773 return;
11774
11776 // Format the template argument list into the argument string.
11777 SmallString<128> TemplateArgString;
11778 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11779 TemplateArgString = " ";
11780 TemplateArgString += S.getTemplateArgumentBindingsText(
11781 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11782 if (TemplateArgString.size() == 1)
11783 TemplateArgString.clear();
11784 S.Diag(Templated->getLocation(),
11785 diag::note_ovl_candidate_unsatisfied_constraints)
11786 << TemplateArgString;
11787
11789 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11790 return;
11791 }
11794 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11795 return;
11796
11798 S.Diag(Templated->getLocation(),
11799 diag::note_ovl_candidate_instantiation_depth);
11800 MaybeEmitInheritedConstructorNote(S, Found);
11801 return;
11802
11804 // Format the template argument list into the argument string.
11805 SmallString<128> TemplateArgString;
11806 if (TemplateArgumentList *Args =
11807 DeductionFailure.getTemplateArgumentList()) {
11808 TemplateArgString = " ";
11809 TemplateArgString += S.getTemplateArgumentBindingsText(
11810 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11811 if (TemplateArgString.size() == 1)
11812 TemplateArgString.clear();
11813 }
11814
11815 // If this candidate was disabled by enable_if, say so.
11816 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11817 if (PDiag && PDiag->second.getDiagID() ==
11818 diag::err_typename_nested_not_found_enable_if) {
11819 // FIXME: Use the source range of the condition, and the fully-qualified
11820 // name of the enable_if template. These are both present in PDiag.
11821 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11822 << "'enable_if'" << TemplateArgString;
11823 return;
11824 }
11825
11826 // We found a specific requirement that disabled the enable_if.
11827 if (PDiag && PDiag->second.getDiagID() ==
11828 diag::err_typename_nested_not_found_requirement) {
11829 S.Diag(Templated->getLocation(),
11830 diag::note_ovl_candidate_disabled_by_requirement)
11831 << PDiag->second.getStringArg(0) << TemplateArgString;
11832 return;
11833 }
11834
11835 // Format the SFINAE diagnostic into the argument string.
11836 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11837 // formatted message in another diagnostic.
11838 SmallString<128> SFINAEArgString;
11839 SourceRange R;
11840 if (PDiag) {
11841 SFINAEArgString = ": ";
11842 R = SourceRange(PDiag->first, PDiag->first);
11843 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11844 }
11845
11846 S.Diag(Templated->getLocation(),
11847 diag::note_ovl_candidate_substitution_failure)
11848 << TemplateArgString << SFINAEArgString << R;
11849 MaybeEmitInheritedConstructorNote(S, Found);
11850 return;
11851 }
11852
11855 // Format the template argument list into the argument string.
11856 SmallString<128> TemplateArgString;
11857 if (TemplateArgumentList *Args =
11858 DeductionFailure.getTemplateArgumentList()) {
11859 TemplateArgString = " ";
11860 TemplateArgString += S.getTemplateArgumentBindingsText(
11861 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11862 if (TemplateArgString.size() == 1)
11863 TemplateArgString.clear();
11864 }
11865
11866 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11867 << (*DeductionFailure.getCallArgIndex() + 1)
11868 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11869 << TemplateArgString
11870 << (DeductionFailure.getResult() ==
11872 break;
11873 }
11874
11876 // FIXME: Provide a source location to indicate what we couldn't match.
11877 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11878 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11879 if (FirstTA.getKind() == TemplateArgument::Template &&
11880 SecondTA.getKind() == TemplateArgument::Template) {
11881 TemplateName FirstTN = FirstTA.getAsTemplate();
11882 TemplateName SecondTN = SecondTA.getAsTemplate();
11883 if (FirstTN.getKind() == TemplateName::Template &&
11884 SecondTN.getKind() == TemplateName::Template) {
11885 if (FirstTN.getAsTemplateDecl()->getName() ==
11886 SecondTN.getAsTemplateDecl()->getName()) {
11887 // FIXME: This fixes a bad diagnostic where both templates are named
11888 // the same. This particular case is a bit difficult since:
11889 // 1) It is passed as a string to the diagnostic printer.
11890 // 2) The diagnostic printer only attempts to find a better
11891 // name for types, not decls.
11892 // Ideally, this should folded into the diagnostic printer.
11893 S.Diag(Templated->getLocation(),
11894 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11895 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11896 return;
11897 }
11898 }
11899 }
11900
11901 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11902 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11903 return;
11904
11905 // FIXME: For generic lambda parameters, check if the function is a lambda
11906 // call operator, and if so, emit a prettier and more informative
11907 // diagnostic that mentions 'auto' and lambda in addition to
11908 // (or instead of?) the canonical template type parameters.
11909 S.Diag(Templated->getLocation(),
11910 diag::note_ovl_candidate_non_deduced_mismatch)
11911 << FirstTA << SecondTA;
11912 return;
11913 }
11914 // TODO: diagnose these individually, then kill off
11915 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11917 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11918 MaybeEmitInheritedConstructorNote(S, Found);
11919 return;
11921 S.Diag(Templated->getLocation(),
11922 diag::note_cuda_ovl_candidate_target_mismatch);
11923 return;
11924 }
11925}
11926
11927/// Diagnose a failed template-argument deduction, for function calls.
11929 unsigned NumArgs,
11930 bool TakingCandidateAddress) {
11934 if (CheckArityMismatch(S, Cand, NumArgs))
11935 return;
11936 }
11937 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11938 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11939}
11940
11941/// CUDA: diagnose an invalid call across targets.
11943 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11944 FunctionDecl *Callee = Cand->Function;
11945
11946 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11947 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11948
11949 std::string FnDesc;
11950 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11951 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11952 Cand->getRewriteKind(), FnDesc);
11953
11954 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11955 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11956 << FnDesc /* Ignored */
11957 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11958
11959 // This could be an implicit constructor for which we could not infer the
11960 // target due to a collsion. Diagnose that case.
11961 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11962 if (Meth != nullptr && Meth->isImplicit()) {
11963 CXXRecordDecl *ParentClass = Meth->getParent();
11965
11966 switch (FnKindPair.first) {
11967 default:
11968 return;
11969 case oc_implicit_default_constructor:
11971 break;
11972 case oc_implicit_copy_constructor:
11974 break;
11975 case oc_implicit_move_constructor:
11977 break;
11978 case oc_implicit_copy_assignment:
11980 break;
11981 case oc_implicit_move_assignment:
11983 break;
11984 };
11985
11986 bool ConstRHS = false;
11987 if (Meth->getNumParams()) {
11988 if (const ReferenceType *RT =
11989 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11990 ConstRHS = RT->getPointeeType().isConstQualified();
11991 }
11992 }
11993
11994 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11995 /* ConstRHS */ ConstRHS,
11996 /* Diagnose */ true);
11997 }
11998}
11999
12001 FunctionDecl *Callee = Cand->Function;
12002 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12003
12004 S.Diag(Callee->getLocation(),
12005 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12006 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12007}
12008
12011 assert(ES.isExplicit() && "not an explicit candidate");
12012
12013 unsigned Kind;
12014 switch (Cand->Function->getDeclKind()) {
12015 case Decl::Kind::CXXConstructor:
12016 Kind = 0;
12017 break;
12018 case Decl::Kind::CXXConversion:
12019 Kind = 1;
12020 break;
12021 case Decl::Kind::CXXDeductionGuide:
12022 Kind = Cand->Function->isImplicit() ? 0 : 2;
12023 break;
12024 default:
12025 llvm_unreachable("invalid Decl");
12026 }
12027
12028 // Note the location of the first (in-class) declaration; a redeclaration
12029 // (particularly an out-of-class definition) will typically lack the
12030 // 'explicit' specifier.
12031 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12033 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12034 First = Pattern->getFirstDecl();
12035
12036 S.Diag(First->getLocation(),
12037 diag::note_ovl_candidate_explicit)
12038 << Kind << (ES.getExpr() ? 1 : 0)
12039 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12040}
12041
12042/// Generates a 'note' diagnostic for an overload candidate. We've
12043/// already generated a primary error at the call site.
12044///
12045/// It really does need to be a single diagnostic with its caret
12046/// pointed at the candidate declaration. Yes, this creates some
12047/// major challenges of technical writing. Yes, this makes pointing
12048/// out problems with specific arguments quite awkward. It's still
12049/// better than generating twenty screens of text for every failed
12050/// overload.
12051///
12052/// It would be great to be able to express per-candidate problems
12053/// more richly for those diagnostic clients that cared, but we'd
12054/// still have to be just as careful with the default diagnostics.
12055/// \param CtorDestAS Addr space of object being constructed (for ctor
12056/// candidates only).
12058 unsigned NumArgs,
12059 bool TakingCandidateAddress,
12060 LangAS CtorDestAS = LangAS::Default) {
12061 FunctionDecl *Fn = Cand->Function;
12063 return;
12064
12065 // There is no physical candidate declaration to point to for OpenCL builtins.
12066 // Except for failed conversions, the notes are identical for each candidate,
12067 // so do not generate such notes.
12068 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12070 return;
12071
12072 // Note deleted candidates, but only if they're viable.
12073 if (Cand->Viable) {
12074 if (Fn->isDeleted()) {
12075 std::string FnDesc;
12076 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12077 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12078 Cand->getRewriteKind(), FnDesc);
12079
12080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12081 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12082 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12083 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12084 return;
12085 }
12086
12087 // We don't really have anything else to say about viable candidates.
12088 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12089 return;
12090 }
12091
12092 switch (Cand->FailureKind) {
12095 return DiagnoseArityMismatch(S, Cand, NumArgs);
12096
12098 return DiagnoseBadDeduction(S, Cand, NumArgs,
12099 TakingCandidateAddress);
12100
12102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12103 << (Fn->getPrimaryTemplate() ? 1 : 0);
12104 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12105 return;
12106 }
12107
12109 Qualifiers QualsForPrinting;
12110 QualsForPrinting.setAddressSpace(CtorDestAS);
12111 S.Diag(Fn->getLocation(),
12112 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12113 << QualsForPrinting;
12114 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12115 return;
12116 }
12117
12121 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12122
12124 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12125 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12126 if (Cand->Conversions[I].isBad())
12127 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12128
12129 // FIXME: this currently happens when we're called from SemaInit
12130 // when user-conversion overload fails. Figure out how to handle
12131 // those conditions and diagnose them well.
12132 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12133 }
12134
12136 return DiagnoseBadTarget(S, Cand);
12137
12138 case ovl_fail_enable_if:
12139 return DiagnoseFailedEnableIfAttr(S, Cand);
12140
12141 case ovl_fail_explicit:
12142 return DiagnoseFailedExplicitSpec(S, Cand);
12143
12145 // It's generally not interesting to note copy/move constructors here.
12146 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12147 return;
12148 S.Diag(Fn->getLocation(),
12149 diag::note_ovl_candidate_inherited_constructor_slice)
12150 << (Fn->getPrimaryTemplate() ? 1 : 0)
12152 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12153 return;
12154
12156 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
12157 (void)Available;
12158 assert(!Available);
12159 break;
12160 }
12162 // Do nothing, these should simply be ignored.
12163 break;
12164
12166 std::string FnDesc;
12167 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12168 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12169 Cand->getRewriteKind(), FnDesc);
12170
12171 S.Diag(Fn->getLocation(),
12172 diag::note_ovl_candidate_constraints_not_satisfied)
12173 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12174 << FnDesc /* Ignored */;
12175 ConstraintSatisfaction Satisfaction;
12176 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12177 break;
12178 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12179 }
12180 }
12181}
12182
12185 return;
12186
12187 // Desugar the type of the surrogate down to a function type,
12188 // retaining as many typedefs as possible while still showing
12189 // the function type (and, therefore, its parameter types).
12190 QualType FnType = Cand->Surrogate->getConversionType();
12191 bool isLValueReference = false;
12192 bool isRValueReference = false;
12193 bool isPointer = false;
12194 if (const LValueReferenceType *FnTypeRef =
12195 FnType->getAs<LValueReferenceType>()) {
12196 FnType = FnTypeRef->getPointeeType();
12197 isLValueReference = true;
12198 } else if (const RValueReferenceType *FnTypeRef =
12199 FnType->getAs<RValueReferenceType>()) {
12200 FnType = FnTypeRef->getPointeeType();
12201 isRValueReference = true;
12202 }
12203 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12204 FnType = FnTypePtr->getPointeeType();
12205 isPointer = true;
12206 }
12207 // Desugar down to a function type.
12208 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12209 // Reconstruct the pointer/reference as appropriate.
12210 if (isPointer) FnType = S.Context.getPointerType(FnType);
12211 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12212 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12213
12214 if (!Cand->Viable &&
12216 S.Diag(Cand->Surrogate->getLocation(),
12217 diag::note_ovl_surrogate_constraints_not_satisfied)
12218 << Cand->Surrogate;
12219 ConstraintSatisfaction Satisfaction;
12220 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12221 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12222 } else {
12223 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12224 << FnType;
12225 }
12226}
12227
12228static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12229 SourceLocation OpLoc,
12230 OverloadCandidate *Cand) {
12231 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12232 std::string TypeStr("operator");
12233 TypeStr += Opc;
12234 TypeStr += "(";
12235 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12236 if (Cand->Conversions.size() == 1) {
12237 TypeStr += ")";
12238 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12239 } else {
12240 TypeStr += ", ";
12241 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12242 TypeStr += ")";
12243 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12244 }
12245}
12246
12248 OverloadCandidate *Cand) {
12249 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12250 if (ICS.isBad()) break; // all meaningless after first invalid
12251 if (!ICS.isAmbiguous()) continue;
12252
12254 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12255 }
12256}
12257
12259 if (Cand->Function)
12260 return Cand->Function->getLocation();
12261 if (Cand->IsSurrogate)
12262 return Cand->Surrogate->getLocation();
12263 return SourceLocation();
12264}
12265
12266static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12267 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12271 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12272
12276 return 1;
12277
12280 return 2;
12281
12289 return 3;
12290
12292 return 4;
12293
12295 return 5;
12296
12299 return 6;
12300 }
12301 llvm_unreachable("Unhandled deduction result");
12302}
12303
12304namespace {
12305
12306struct CompareOverloadCandidatesForDisplay {
12307 Sema &S;
12308 SourceLocation Loc;
12309 size_t NumArgs;
12311
12312 CompareOverloadCandidatesForDisplay(
12313 Sema &S, SourceLocation Loc, size_t NArgs,
12315 : S(S), NumArgs(NArgs), CSK(CSK) {}
12316
12317 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12318 // If there are too many or too few arguments, that's the high-order bit we
12319 // want to sort by, even if the immediate failure kind was something else.
12320 if (C->FailureKind == ovl_fail_too_many_arguments ||
12321 C->FailureKind == ovl_fail_too_few_arguments)
12322 return static_cast<OverloadFailureKind>(C->FailureKind);
12323
12324 if (C->Function) {
12325 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12327 if (NumArgs < C->Function->getMinRequiredArguments())
12329 }
12330
12331 return static_cast<OverloadFailureKind>(C->FailureKind);
12332 }
12333
12334 bool operator()(const OverloadCandidate *L,
12335 const OverloadCandidate *R) {
12336 // Fast-path this check.
12337 if (L == R) return false;
12338
12339 // Order first by viability.
12340 if (L->Viable) {
12341 if (!R->Viable) return true;
12342
12343 if (int Ord = CompareConversions(*L, *R))
12344 return Ord < 0;
12345 // Use other tie breakers.
12346 } else if (R->Viable)
12347 return false;
12348
12349 assert(L->Viable == R->Viable);
12350
12351 // Criteria by which we can sort non-viable candidates:
12352 if (!L->Viable) {
12353 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12354 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12355
12356 // 1. Arity mismatches come after other candidates.
12357 if (LFailureKind == ovl_fail_too_many_arguments ||
12358 LFailureKind == ovl_fail_too_few_arguments) {
12359 if (RFailureKind == ovl_fail_too_many_arguments ||
12360 RFailureKind == ovl_fail_too_few_arguments) {
12361 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12362 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12363 if (LDist == RDist) {
12364 if (LFailureKind == RFailureKind)
12365 // Sort non-surrogates before surrogates.
12366 return !L->IsSurrogate && R->IsSurrogate;
12367 // Sort candidates requiring fewer parameters than there were
12368 // arguments given after candidates requiring more parameters
12369 // than there were arguments given.
12370 return LFailureKind == ovl_fail_too_many_arguments;
12371 }
12372 return LDist < RDist;
12373 }
12374 return false;
12375 }
12376 if (RFailureKind == ovl_fail_too_many_arguments ||
12377 RFailureKind == ovl_fail_too_few_arguments)
12378 return true;
12379
12380 // 2. Bad conversions come first and are ordered by the number
12381 // of bad conversions and quality of good conversions.
12382 if (LFailureKind == ovl_fail_bad_conversion) {
12383 if (RFailureKind != ovl_fail_bad_conversion)
12384 return true;
12385
12386 // The conversion that can be fixed with a smaller number of changes,
12387 // comes first.
12388 unsigned numLFixes = L->Fix.NumConversionsFixed;
12389 unsigned numRFixes = R->Fix.NumConversionsFixed;
12390 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12391 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12392 if (numLFixes != numRFixes) {
12393 return numLFixes < numRFixes;
12394 }
12395
12396 // If there's any ordering between the defined conversions...
12397 if (int Ord = CompareConversions(*L, *R))
12398 return Ord < 0;
12399 } else if (RFailureKind == ovl_fail_bad_conversion)
12400 return false;
12401
12402 if (LFailureKind == ovl_fail_bad_deduction) {
12403 if (RFailureKind != ovl_fail_bad_deduction)
12404 return true;
12405
12407 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12408 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12409 if (LRank != RRank)
12410 return LRank < RRank;
12411 }
12412 } else if (RFailureKind == ovl_fail_bad_deduction)
12413 return false;
12414
12415 // TODO: others?
12416 }
12417
12418 // Sort everything else by location.
12421
12422 // Put candidates without locations (e.g. builtins) at the end.
12423 if (LLoc.isValid() && RLoc.isValid())
12424 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12425 if (LLoc.isValid() && !RLoc.isValid())
12426 return true;
12427 if (RLoc.isValid() && !LLoc.isValid())
12428 return false;
12429 assert(!LLoc.isValid() && !RLoc.isValid());
12430 // For builtins and other functions without locations, fallback to the order
12431 // in which they were added into the candidate set.
12432 return L < R;
12433 }
12434
12435private:
12436 struct ConversionSignals {
12437 unsigned KindRank = 0;
12439
12440 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12441 ConversionSignals Sig;
12442 Sig.KindRank = Seq.getKindRank();
12443 if (Seq.isStandard())
12444 Sig.Rank = Seq.Standard.getRank();
12445 else if (Seq.isUserDefined())
12446 Sig.Rank = Seq.UserDefined.After.getRank();
12447 // We intend StaticObjectArgumentConversion to compare the same as
12448 // StandardConversion with ICR_ExactMatch rank.
12449 return Sig;
12450 }
12451
12452 static ConversionSignals ForObjectArgument() {
12453 // We intend StaticObjectArgumentConversion to compare the same as
12454 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12455 return {};
12456 }
12457 };
12458
12459 // Returns -1 if conversions in L are considered better.
12460 // 0 if they are considered indistinguishable.
12461 // 1 if conversions in R are better.
12462 int CompareConversions(const OverloadCandidate &L,
12463 const OverloadCandidate &R) {
12464 // We cannot use `isBetterOverloadCandidate` because it is defined
12465 // according to the C++ standard and provides a partial order, but we need
12466 // a total order as this function is used in sort.
12467 assert(L.Conversions.size() == R.Conversions.size());
12468 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12469 auto LS = L.IgnoreObjectArgument && I == 0
12470 ? ConversionSignals::ForObjectArgument()
12471 : ConversionSignals::ForSequence(L.Conversions[I]);
12472 auto RS = R.IgnoreObjectArgument
12473 ? ConversionSignals::ForObjectArgument()
12474 : ConversionSignals::ForSequence(R.Conversions[I]);
12475 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12476 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12477 ? -1
12478 : 1;
12479 }
12480 // FIXME: find a way to compare templates for being more or less
12481 // specialized that provides a strict weak ordering.
12482 return 0;
12483 }
12484};
12485}
12486
12487/// CompleteNonViableCandidate - Normally, overload resolution only
12488/// computes up to the first bad conversion. Produces the FixIt set if
12489/// possible.
12490static void
12492 ArrayRef<Expr *> Args,
12494 assert(!Cand->Viable);
12495
12496 // Don't do anything on failures other than bad conversion.
12498 return;
12499
12500 // We only want the FixIts if all the arguments can be corrected.
12501 bool Unfixable = false;
12502 // Use a implicit copy initialization to check conversion fixes.
12504
12505 // Attempt to fix the bad conversion.
12506 unsigned ConvCount = Cand->Conversions.size();
12507 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12508 ++ConvIdx) {
12509 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12510 if (Cand->Conversions[ConvIdx].isInitialized() &&
12511 Cand->Conversions[ConvIdx].isBad()) {
12512 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12513 break;
12514 }
12515 }
12516
12517 // FIXME: this should probably be preserved from the overload
12518 // operation somehow.
12519 bool SuppressUserConversions = false;
12520
12521 unsigned ConvIdx = 0;
12522 unsigned ArgIdx = 0;
12523 ArrayRef<QualType> ParamTypes;
12524 bool Reversed = Cand->isReversed();
12525
12526 if (Cand->IsSurrogate) {
12527 QualType ConvType
12529 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12530 ConvType = ConvPtrType->getPointeeType();
12531 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12532 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12533 ConvIdx = 1;
12534 } else if (Cand->Function) {
12535 ParamTypes =
12536 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12537 if (isa<CXXMethodDecl>(Cand->Function) &&
12538 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12539 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12540 ConvIdx = 1;
12542 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12544 OO_Subscript)
12545 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12546 ArgIdx = 1;
12547 }
12548 } else {
12549 // Builtin operator.
12550 assert(ConvCount <= 3);
12551 ParamTypes = Cand->BuiltinParamTypes;
12552 }
12553
12554 // Fill in the rest of the conversions.
12555 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12556 ConvIdx != ConvCount;
12557 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12558 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12559 if (Cand->Conversions[ConvIdx].isInitialized()) {
12560 // We've already checked this conversion.
12561 } else if (ParamIdx < ParamTypes.size()) {
12562 if (ParamTypes[ParamIdx]->isDependentType())
12563 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12564 Args[ArgIdx]->getType());
12565 else {
12566 Cand->Conversions[ConvIdx] =
12567 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12568 SuppressUserConversions,
12569 /*InOverloadResolution=*/true,
12570 /*AllowObjCWritebackConversion=*/
12571 S.getLangOpts().ObjCAutoRefCount);
12572 // Store the FixIt in the candidate if it exists.
12573 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12574 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12575 }
12576 } else
12577 Cand->Conversions[ConvIdx].setEllipsis();
12578 }
12579}
12580
12583 SourceLocation OpLoc,
12584 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12585 // Sort the candidates by viability and position. Sorting directly would
12586 // be prohibitive, so we make a set of pointers and sort those.
12588 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12589 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12590 if (!Filter(*Cand))
12591 continue;
12592 switch (OCD) {
12593 case OCD_AllCandidates:
12594 if (!Cand->Viable) {
12595 if (!Cand->Function && !Cand->IsSurrogate) {
12596 // This a non-viable builtin candidate. We do not, in general,
12597 // want to list every possible builtin candidate.
12598 continue;
12599 }
12600 CompleteNonViableCandidate(S, Cand, Args, Kind);
12601 }
12602 break;
12603
12605 if (!Cand->Viable)
12606 continue;
12607 break;
12608
12610 if (!Cand->Best)
12611 continue;
12612 break;
12613 }
12614
12615 Cands.push_back(Cand);
12616 }
12617
12618 llvm::stable_sort(
12619 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12620
12621 return Cands;
12622}
12623
12625 SourceLocation OpLoc) {
12626 bool DeferHint = false;
12627 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12628 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12629 // host device candidates.
12630 auto WrongSidedCands =
12631 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12632 return (Cand.Viable == false &&
12633 Cand.FailureKind == ovl_fail_bad_target) ||
12634 (Cand.Function &&
12635 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12636 Cand.Function->template hasAttr<CUDADeviceAttr>());
12637 });
12638 DeferHint = !WrongSidedCands.empty();
12639 }
12640 return DeferHint;
12641}
12642
12643/// When overload resolution fails, prints diagnostic messages containing the
12644/// candidates in the candidate set.
12647 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12648 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12649
12650 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12651
12652 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12653
12654 // In WebAssembly we don't want to emit further diagnostics if a table is
12655 // passed as an argument to a function.
12656 bool NoteCands = true;
12657 for (const Expr *Arg : Args) {
12658 if (Arg->getType()->isWebAssemblyTableType())
12659 NoteCands = false;
12660 }
12661
12662 if (NoteCands)
12663 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12664
12665 if (OCD == OCD_AmbiguousCandidates)
12667}
12668
12671 StringRef Opc, SourceLocation OpLoc) {
12672 bool ReportedAmbiguousConversions = false;
12673
12674 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12675 unsigned CandsShown = 0;
12676 auto I = Cands.begin(), E = Cands.end();
12677 for (; I != E; ++I) {
12678 OverloadCandidate *Cand = *I;
12679
12680 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12681 ShowOverloads == Ovl_Best) {
12682 break;
12683 }
12684 ++CandsShown;
12685
12686 if (Cand->Function)
12687 NoteFunctionCandidate(S, Cand, Args.size(),
12688 /*TakingCandidateAddress=*/false, DestAS);
12689 else if (Cand->IsSurrogate)
12690 NoteSurrogateCandidate(S, Cand);
12691 else {
12692 assert(Cand->Viable &&
12693 "Non-viable built-in candidates are not added to Cands.");
12694 // Generally we only see ambiguities including viable builtin
12695 // operators if overload resolution got screwed up by an
12696 // ambiguous user-defined conversion.
12697 //
12698 // FIXME: It's quite possible for different conversions to see
12699 // different ambiguities, though.
12700 if (!ReportedAmbiguousConversions) {
12701 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12702 ReportedAmbiguousConversions = true;
12703 }
12704
12705 // If this is a viable builtin, print it.
12706 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12707 }
12708 }
12709
12710 // Inform S.Diags that we've shown an overload set with N elements. This may
12711 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12712 S.Diags.overloadCandidatesShown(CandsShown);
12713
12714 if (I != E)
12715 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12716 shouldDeferDiags(S, Args, OpLoc))
12717 << int(E - I);
12718}
12719
12720static SourceLocation
12722 return Cand->Specialization ? Cand->Specialization->getLocation()
12723 : SourceLocation();
12724}
12725
12726namespace {
12727struct CompareTemplateSpecCandidatesForDisplay {
12728 Sema &S;
12729 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12730
12731 bool operator()(const TemplateSpecCandidate *L,
12732 const TemplateSpecCandidate *R) {
12733 // Fast-path this check.
12734 if (L == R)
12735 return false;
12736
12737 // Assuming that both candidates are not matches...
12738
12739 // Sort by the ranking of deduction failures.
12743
12744 // Sort everything else by location.
12747
12748 // Put candidates without locations (e.g. builtins) at the end.
12749 if (LLoc.isInvalid())
12750 return false;
12751 if (RLoc.isInvalid())
12752 return true;
12753
12754 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12755 }
12756};
12757}
12758
12759/// Diagnose a template argument deduction failure.
12760/// We are treating these failures as overload failures due to bad
12761/// deductions.
12763 bool ForTakingAddress) {
12764 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12765 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12766}
12767
12768void TemplateSpecCandidateSet::destroyCandidates() {
12769 for (iterator i = begin(), e = end(); i != e; ++i) {
12770 i->DeductionFailure.Destroy();
12771 }
12772}
12773
12775 destroyCandidates();
12776 Candidates.clear();
12777}
12778
12779/// NoteCandidates - When no template specialization match is found, prints
12780/// diagnostic messages containing the non-matching specializations that form
12781/// the candidate set.
12782/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12783/// OCD == OCD_AllCandidates and Cand->Viable == false.
12785 // Sort the candidates by position (assuming no candidate is a match).
12786 // Sorting directly would be prohibitive, so we make a set of pointers
12787 // and sort those.
12789 Cands.reserve(size());
12790 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12791 if (Cand->Specialization)
12792 Cands.push_back(Cand);
12793 // Otherwise, this is a non-matching builtin candidate. We do not,
12794 // in general, want to list every possible builtin candidate.
12795 }
12796
12797 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12798
12799 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12800 // for generalization purposes (?).
12801 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12802
12804 unsigned CandsShown = 0;
12805 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12806 TemplateSpecCandidate *Cand = *I;
12807
12808 // Set an arbitrary limit on the number of candidates we'll spam
12809 // the user with. FIXME: This limit should depend on details of the
12810 // candidate list.
12811 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12812 break;
12813 ++CandsShown;
12814
12815 assert(Cand->Specialization &&
12816 "Non-matching built-in candidates are not added to Cands.");
12817 Cand->NoteDeductionFailure(S, ForTakingAddress);
12818 }
12819
12820 if (I != E)
12821 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12822}
12823
12824// [PossiblyAFunctionType] --> [Return]
12825// NonFunctionType --> NonFunctionType
12826// R (A) --> R(A)
12827// R (*)(A) --> R (A)
12828// R (&)(A) --> R (A)
12829// R (S::*)(A) --> R (A)
12831 QualType Ret = PossiblyAFunctionType;
12832 if (const PointerType *ToTypePtr =
12833 PossiblyAFunctionType->getAs<PointerType>())
12834 Ret = ToTypePtr->getPointeeType();
12835 else if (const ReferenceType *ToTypeRef =
12836 PossiblyAFunctionType->getAs<ReferenceType>())
12837 Ret = ToTypeRef->getPointeeType();
12838 else if (const MemberPointerType *MemTypePtr =
12839 PossiblyAFunctionType->getAs<MemberPointerType>())
12840 Ret = MemTypePtr->getPointeeType();
12841 Ret =
12842 Context.getCanonicalType(Ret).getUnqualifiedType();
12843 return Ret;
12844}
12845
12847 bool Complain = true) {
12848 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12849 S.DeduceReturnType(FD, Loc, Complain))
12850 return true;
12851
12852 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12853 if (S.getLangOpts().CPlusPlus17 &&
12854 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12855 !S.ResolveExceptionSpec(Loc, FPT))
12856 return true;
12857
12858 return false;
12859}
12860
12861namespace {
12862// A helper class to help with address of function resolution
12863// - allows us to avoid passing around all those ugly parameters
12864class AddressOfFunctionResolver {
12865 Sema& S;
12866 Expr* SourceExpr;
12867 const QualType& TargetType;
12868 QualType TargetFunctionType; // Extracted function type from target type
12869
12870 bool Complain;
12871 //DeclAccessPair& ResultFunctionAccessPair;
12872 ASTContext& Context;
12873
12874 bool TargetTypeIsNonStaticMemberFunction;
12875 bool FoundNonTemplateFunction;
12876 bool StaticMemberFunctionFromBoundPointer;
12877 bool HasComplained;
12878
12879 OverloadExpr::FindResult OvlExprInfo;
12880 OverloadExpr *OvlExpr;
12881 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12883 TemplateSpecCandidateSet FailedCandidates;
12884
12885public:
12886 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12887 const QualType &TargetType, bool Complain)
12888 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12889 Complain(Complain), Context(S.getASTContext()),
12890 TargetTypeIsNonStaticMemberFunction(
12891 !!TargetType->getAs<MemberPointerType>()),
12892 FoundNonTemplateFunction(false),
12893 StaticMemberFunctionFromBoundPointer(false),
12894 HasComplained(false),
12895 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12896 OvlExpr(OvlExprInfo.Expression),
12897 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12898 ExtractUnqualifiedFunctionTypeFromTargetType();
12899
12900 if (TargetFunctionType->isFunctionType()) {
12901 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12902 if (!UME->isImplicitAccess() &&
12904 StaticMemberFunctionFromBoundPointer = true;
12905 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12906 DeclAccessPair dap;
12908 OvlExpr, false, &dap)) {
12909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12910 if (!Method->isStatic()) {
12911 // If the target type is a non-function type and the function found
12912 // is a non-static member function, pretend as if that was the
12913 // target, it's the only possible type to end up with.
12914 TargetTypeIsNonStaticMemberFunction = true;
12915
12916 // And skip adding the function if its not in the proper form.
12917 // We'll diagnose this due to an empty set of functions.
12918 if (!OvlExprInfo.HasFormOfMemberPointer)
12919 return;
12920 }
12921
12922 Matches.push_back(std::make_pair(dap, Fn));
12923 }
12924 return;
12925 }
12926
12927 if (OvlExpr->hasExplicitTemplateArgs())
12928 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12929
12930 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12931 // C++ [over.over]p4:
12932 // If more than one function is selected, [...]
12933 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12934 if (FoundNonTemplateFunction)
12935 EliminateAllTemplateMatches();
12936 else
12937 EliminateAllExceptMostSpecializedTemplate();
12938 }
12939 }
12940
12941 if (S.getLangOpts().CUDA && Matches.size() > 1)
12942 EliminateSuboptimalCudaMatches();
12943 }
12944
12945 bool hasComplained() const { return HasComplained; }
12946
12947private:
12948 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12949 QualType Discard;
12950 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12951 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12952 }
12953
12954 /// \return true if A is considered a better overload candidate for the
12955 /// desired type than B.
12956 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12957 // If A doesn't have exactly the correct type, we don't want to classify it
12958 // as "better" than anything else. This way, the user is required to
12959 // disambiguate for us if there are multiple candidates and no exact match.
12960 return candidateHasExactlyCorrectType(A) &&
12961 (!candidateHasExactlyCorrectType(B) ||
12962 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12963 }
12964
12965 /// \return true if we were able to eliminate all but one overload candidate,
12966 /// false otherwise.
12967 bool eliminiateSuboptimalOverloadCandidates() {
12968 // Same algorithm as overload resolution -- one pass to pick the "best",
12969 // another pass to be sure that nothing is better than the best.
12970 auto Best = Matches.begin();
12971 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12972 if (isBetterCandidate(I->second, Best->second))
12973 Best = I;
12974
12975 const FunctionDecl *BestFn = Best->second;
12976 auto IsBestOrInferiorToBest = [this, BestFn](
12977 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12978 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12979 };
12980
12981 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12982 // option, so we can potentially give the user a better error
12983 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12984 return false;
12985 Matches[0] = *Best;
12986 Matches.resize(1);
12987 return true;
12988 }
12989
12990 bool isTargetTypeAFunction() const {
12991 return TargetFunctionType->isFunctionType();
12992 }
12993
12994 // [ToType] [Return]
12995
12996 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12997 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12998 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12999 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13000 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13001 }
13002
13003 // return true if any matching specializations were found
13004 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13005 const DeclAccessPair& CurAccessFunPair) {
13006 if (CXXMethodDecl *Method
13007 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13008 // Skip non-static function templates when converting to pointer, and
13009 // static when converting to member pointer.
13010 bool CanConvertToFunctionPointer =
13011 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13012 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13013 return false;
13014 }
13015 else if (TargetTypeIsNonStaticMemberFunction)
13016 return false;
13017
13018 // C++ [over.over]p2:
13019 // If the name is a function template, template argument deduction is
13020 // done (14.8.2.2), and if the argument deduction succeeds, the
13021 // resulting template argument list is used to generate a single
13022 // function template specialization, which is added to the set of
13023 // overloaded functions considered.
13024 FunctionDecl *Specialization = nullptr;
13025 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13027 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13028 Specialization, Info, /*IsAddressOfFunction*/ true);
13029 Result != TemplateDeductionResult::Success) {
13030 // Make a note of the failed deduction for diagnostics.
13031 FailedCandidates.addCandidate()
13032 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13033 MakeDeductionFailureInfo(Context, Result, Info));
13034 return false;
13035 }
13036
13037 // Template argument deduction ensures that we have an exact match or
13038 // compatible pointer-to-function arguments that would be adjusted by ICS.
13039 // This function template specicalization works.
13041 Context.getCanonicalType(Specialization->getType()),
13042 Context.getCanonicalType(TargetFunctionType)));
13043
13045 return false;
13046
13047 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13048 return true;
13049 }
13050
13051 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13052 const DeclAccessPair& CurAccessFunPair) {
13053 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13054 // Skip non-static functions when converting to pointer, and static
13055 // when converting to member pointer.
13056 bool CanConvertToFunctionPointer =
13057 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13058 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13059 return false;
13060 }
13061 else if (TargetTypeIsNonStaticMemberFunction)
13062 return false;
13063
13064 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13065 if (S.getLangOpts().CUDA) {
13066 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13067 if (!(Caller && Caller->isImplicit()) &&
13068 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13069 return false;
13070 }
13071 if (FunDecl->isMultiVersion()) {
13072 const auto *TA = FunDecl->getAttr<TargetAttr>();
13073 if (TA && !TA->isDefaultVersion())
13074 return false;
13075 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13076 if (TVA && !TVA->isDefaultVersion())
13077 return false;
13078 }
13079
13080 // If any candidate has a placeholder return type, trigger its deduction
13081 // now.
13082 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13083 Complain)) {
13084 HasComplained |= Complain;
13085 return false;
13086 }
13087
13088 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13089 return false;
13090
13091 // If we're in C, we need to support types that aren't exactly identical.
13092 if (!S.getLangOpts().CPlusPlus ||
13093 candidateHasExactlyCorrectType(FunDecl)) {
13094 Matches.push_back(std::make_pair(
13095 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13096 FoundNonTemplateFunction = true;
13097 return true;
13098 }
13099 }
13100
13101 return false;
13102 }
13103
13104 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13105 bool Ret = false;
13106
13107 // If the overload expression doesn't have the form of a pointer to
13108 // member, don't try to convert it to a pointer-to-member type.
13109 if (IsInvalidFormOfPointerToMemberFunction())
13110 return false;
13111
13112 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13113 E = OvlExpr->decls_end();
13114 I != E; ++I) {
13115 // Look through any using declarations to find the underlying function.
13116 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13117
13118 // C++ [over.over]p3:
13119 // Non-member functions and static member functions match
13120 // targets of type "pointer-to-function" or "reference-to-function."
13121 // Nonstatic member functions match targets of
13122 // type "pointer-to-member-function."
13123 // Note that according to DR 247, the containing class does not matter.
13124 if (FunctionTemplateDecl *FunctionTemplate
13125 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13126 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13127 Ret = true;
13128 }
13129 // If we have explicit template arguments supplied, skip non-templates.
13130 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13131 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13132 Ret = true;
13133 }
13134 assert(Ret || Matches.empty());
13135 return Ret;
13136 }
13137
13138 void EliminateAllExceptMostSpecializedTemplate() {
13139 // [...] and any given function template specialization F1 is
13140 // eliminated if the set contains a second function template
13141 // specialization whose function template is more specialized
13142 // than the function template of F1 according to the partial
13143 // ordering rules of 14.5.5.2.
13144
13145 // The algorithm specified above is quadratic. We instead use a
13146 // two-pass algorithm (similar to the one used to identify the
13147 // best viable function in an overload set) that identifies the
13148 // best function template (if it exists).
13149
13150 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13151 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13152 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13153
13154 // TODO: It looks like FailedCandidates does not serve much purpose
13155 // here, since the no_viable diagnostic has index 0.
13157 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13158 SourceExpr->getBeginLoc(), S.PDiag(),
13159 S.PDiag(diag::err_addr_ovl_ambiguous)
13160 << Matches[0].second->getDeclName(),
13161 S.PDiag(diag::note_ovl_candidate)
13162 << (unsigned)oc_function << (unsigned)ocs_described_template,
13163 Complain, TargetFunctionType);
13164
13165 if (Result != MatchesCopy.end()) {
13166 // Make it the first and only element
13167 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13168 Matches[0].second = cast<FunctionDecl>(*Result);
13169 Matches.resize(1);
13170 } else
13171 HasComplained |= Complain;
13172 }
13173
13174 void EliminateAllTemplateMatches() {
13175 // [...] any function template specializations in the set are
13176 // eliminated if the set also contains a non-template function, [...]
13177 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13178 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13179 ++I;
13180 else {
13181 Matches[I] = Matches[--N];
13182 Matches.resize(N);
13183 }
13184 }
13185 }
13186
13187 void EliminateSuboptimalCudaMatches() {
13188 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13189 Matches);
13190 }
13191
13192public:
13193 void ComplainNoMatchesFound() const {
13194 assert(Matches.empty());
13195 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13196 << OvlExpr->getName() << TargetFunctionType
13197 << OvlExpr->getSourceRange();
13198 if (FailedCandidates.empty())
13199 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13200 /*TakingAddress=*/true);
13201 else {
13202 // We have some deduction failure messages. Use them to diagnose
13203 // the function templates, and diagnose the non-template candidates
13204 // normally.
13205 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13206 IEnd = OvlExpr->decls_end();
13207 I != IEnd; ++I)
13208 if (FunctionDecl *Fun =
13209 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13211 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13212 /*TakingAddress=*/true);
13213 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13214 }
13215 }
13216
13217 bool IsInvalidFormOfPointerToMemberFunction() const {
13218 return TargetTypeIsNonStaticMemberFunction &&
13219 !OvlExprInfo.HasFormOfMemberPointer;
13220 }
13221
13222 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13223 // TODO: Should we condition this on whether any functions might
13224 // have matched, or is it more appropriate to do that in callers?
13225 // TODO: a fixit wouldn't hurt.
13226 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13227 << TargetType << OvlExpr->getSourceRange();
13228 }
13229
13230 bool IsStaticMemberFunctionFromBoundPointer() const {
13231 return StaticMemberFunctionFromBoundPointer;
13232 }
13233
13234 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13235 S.Diag(OvlExpr->getBeginLoc(),
13236 diag::err_invalid_form_pointer_member_function)
13237 << OvlExpr->getSourceRange();
13238 }
13239
13240 void ComplainOfInvalidConversion() const {
13241 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13242 << OvlExpr->getName() << TargetType;
13243 }
13244
13245 void ComplainMultipleMatchesFound() const {
13246 assert(Matches.size() > 1);
13247 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13248 << OvlExpr->getName() << OvlExpr->getSourceRange();
13249 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13250 /*TakingAddress=*/true);
13251 }
13252
13253 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13254
13255 int getNumMatches() const { return Matches.size(); }
13256
13257 FunctionDecl* getMatchingFunctionDecl() const {
13258 if (Matches.size() != 1) return nullptr;
13259 return Matches[0].second;
13260 }
13261
13262 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13263 if (Matches.size() != 1) return nullptr;
13264 return &Matches[0].first;
13265 }
13266};
13267}
13268
13269/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13270/// an overloaded function (C++ [over.over]), where @p From is an
13271/// expression with overloaded function type and @p ToType is the type
13272/// we're trying to resolve to. For example:
13273///
13274/// @code
13275/// int f(double);
13276/// int f(int);
13277///
13278/// int (*pfd)(double) = f; // selects f(double)
13279/// @endcode
13280///
13281/// This routine returns the resulting FunctionDecl if it could be
13282/// resolved, and NULL otherwise. When @p Complain is true, this
13283/// routine will emit diagnostics if there is an error.
13286 QualType TargetType,
13287 bool Complain,
13288 DeclAccessPair &FoundResult,
13289 bool *pHadMultipleCandidates) {
13290 assert(AddressOfExpr->getType() == Context.OverloadTy);
13291
13292 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13293 Complain);
13294 int NumMatches = Resolver.getNumMatches();
13295 FunctionDecl *Fn = nullptr;
13296 bool ShouldComplain = Complain && !Resolver.hasComplained();
13297 if (NumMatches == 0 && ShouldComplain) {
13298 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13299 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13300 else
13301 Resolver.ComplainNoMatchesFound();
13302 }
13303 else if (NumMatches > 1 && ShouldComplain)
13304 Resolver.ComplainMultipleMatchesFound();
13305 else if (NumMatches == 1) {
13306 Fn = Resolver.getMatchingFunctionDecl();
13307 assert(Fn);
13308 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13309 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13310 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13311 if (Complain) {
13312 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13313 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13314 else
13315 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13316 }
13317 }
13318
13319 if (pHadMultipleCandidates)
13320 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13321 return Fn;
13322}
13323
13324/// Given an expression that refers to an overloaded function, try to
13325/// resolve that function to a single function that can have its address taken.
13326/// This will modify `Pair` iff it returns non-null.
13327///
13328/// This routine can only succeed if from all of the candidates in the overload
13329/// set for SrcExpr that can have their addresses taken, there is one candidate
13330/// that is more constrained than the rest.
13334 OverloadExpr *Ovl = R.Expression;
13335 bool IsResultAmbiguous = false;
13336 FunctionDecl *Result = nullptr;
13337 DeclAccessPair DAP;
13338 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13339
13340 // Return positive for better, negative for worse, 0 for equal preference.
13341 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13342 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13343 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13344 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13345 };
13346
13347 auto CheckMoreConstrained = [&](FunctionDecl *FD1,
13348 FunctionDecl *FD2) -> std::optional<bool> {
13350 FD1 = MF;
13352 FD2 = MF;
13354 FD1->getAssociatedConstraints(AC1);
13355 FD2->getAssociatedConstraints(AC2);
13356 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
13357 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
13358 return std::nullopt;
13359 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
13360 return std::nullopt;
13361 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
13362 return std::nullopt;
13363 return AtLeastAsConstrained1;
13364 };
13365
13366 // Don't use the AddressOfResolver because we're specifically looking for
13367 // cases where we have one overload candidate that lacks
13368 // enable_if/pass_object_size/...
13369 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13370 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13371 if (!FD)
13372 return nullptr;
13373
13375 continue;
13376
13377 // If we found a better result, update Result.
13378 auto FoundBetter = [&]() {
13379 IsResultAmbiguous = false;
13380 DAP = I.getPair();
13381 Result = FD;
13382 };
13383
13384 // We have more than one result - see if it is more constrained than the
13385 // previous one.
13386 if (Result) {
13387 // Check CUDA preference first. If the candidates have differennt CUDA
13388 // preference, choose the one with higher CUDA preference. Otherwise,
13389 // choose the one with more constraints.
13390 if (getLangOpts().CUDA) {
13391 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13392 // FD has different preference than Result.
13393 if (PreferenceByCUDA != 0) {
13394 // FD is more preferable than Result.
13395 if (PreferenceByCUDA > 0)
13396 FoundBetter();
13397 continue;
13398 }
13399 }
13400 // FD has the same CUDA prefernece than Result. Continue check
13401 // constraints.
13402 std::optional<bool> MoreConstrainedThanPrevious =
13403 CheckMoreConstrained(FD, Result);
13404 if (!MoreConstrainedThanPrevious) {
13405 IsResultAmbiguous = true;
13406 AmbiguousDecls.push_back(FD);
13407 continue;
13408 }
13409 if (!*MoreConstrainedThanPrevious)
13410 continue;
13411 // FD is more constrained - replace Result with it.
13412 }
13413 FoundBetter();
13414 }
13415
13416 if (IsResultAmbiguous)
13417 return nullptr;
13418
13419 if (Result) {
13421 // We skipped over some ambiguous declarations which might be ambiguous with
13422 // the selected result.
13423 for (FunctionDecl *Skipped : AmbiguousDecls) {
13424 // If skipped candidate has different CUDA preference than the result,
13425 // there is no ambiguity. Otherwise check whether they have different
13426 // constraints.
13427 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13428 continue;
13429 if (!CheckMoreConstrained(Skipped, Result))
13430 return nullptr;
13431 }
13432 Pair = DAP;
13433 }
13434 return Result;
13435}
13436
13437/// Given an overloaded function, tries to turn it into a non-overloaded
13438/// function reference using resolveAddressOfSingleOverloadCandidate. This
13439/// will perform access checks, diagnose the use of the resultant decl, and, if
13440/// requested, potentially perform a function-to-pointer decay.
13441///
13442/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13443/// Otherwise, returns true. This may emit diagnostics and return true.
13445 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13446 Expr *E = SrcExpr.get();
13447 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13448
13449 DeclAccessPair DAP;
13450 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13451 if (!Found || Found->isCPUDispatchMultiVersion() ||
13453 return false;
13454
13455 // Emitting multiple diagnostics for a function that is both inaccessible and
13456 // unavailable is consistent with our behavior elsewhere. So, always check
13457 // for both.
13458 DiagnoseUseOfDecl(Found, E->getExprLoc());
13459 CheckAddressOfMemberAccess(E, DAP);
13460 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13461 if (Res.isInvalid())
13462 return false;
13463 Expr *Fixed = Res.get();
13464 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13465 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13466 else
13467 SrcExpr = Fixed;
13468 return true;
13469}
13470
13471/// Given an expression that refers to an overloaded function, try to
13472/// resolve that overloaded function expression down to a single function.
13473///
13474/// This routine can only resolve template-ids that refer to a single function
13475/// template, where that template-id refers to a single template whose template
13476/// arguments are either provided by the template-id or have defaults,
13477/// as described in C++0x [temp.arg.explicit]p3.
13478///
13479/// If no template-ids are found, no diagnostics are emitted and NULL is
13480/// returned.
13482 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13483 TemplateSpecCandidateSet *FailedTSC) {
13484 // C++ [over.over]p1:
13485 // [...] [Note: any redundant set of parentheses surrounding the
13486 // overloaded function name is ignored (5.1). ]
13487 // C++ [over.over]p1:
13488 // [...] The overloaded function name can be preceded by the &
13489 // operator.
13490
13491 // If we didn't actually find any template-ids, we're done.
13492 if (!ovl->hasExplicitTemplateArgs())
13493 return nullptr;
13494
13495 TemplateArgumentListInfo ExplicitTemplateArgs;
13496 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13497
13498 // Look through all of the overloaded functions, searching for one
13499 // whose type matches exactly.
13500 FunctionDecl *Matched = nullptr;
13501 for (UnresolvedSetIterator I = ovl->decls_begin(),
13502 E = ovl->decls_end(); I != E; ++I) {
13503 // C++0x [temp.arg.explicit]p3:
13504 // [...] In contexts where deduction is done and fails, or in contexts
13505 // where deduction is not done, if a template argument list is
13506 // specified and it, along with any default template arguments,
13507 // identifies a single function template specialization, then the
13508 // template-id is an lvalue for the function template specialization.
13509 FunctionTemplateDecl *FunctionTemplate
13510 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13511
13512 // C++ [over.over]p2:
13513 // If the name is a function template, template argument deduction is
13514 // done (14.8.2.2), and if the argument deduction succeeds, the
13515 // resulting template argument list is used to generate a single
13516 // function template specialization, which is added to the set of
13517 // overloaded functions considered.
13518 FunctionDecl *Specialization = nullptr;
13519 TemplateDeductionInfo Info(ovl->getNameLoc());
13521 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13522 /*IsAddressOfFunction*/ true);
13524 // Make a note of the failed deduction for diagnostics.
13525 if (FailedTSC)
13526 FailedTSC->addCandidate().set(
13527 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13528 MakeDeductionFailureInfo(Context, Result, Info));
13529 continue;
13530 }
13531
13532 assert(Specialization && "no specialization and no error?");
13533
13534 // Multiple matches; we can't resolve to a single declaration.
13535 if (Matched) {
13536 if (Complain) {
13537 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13538 << ovl->getName();
13539 NoteAllOverloadCandidates(ovl);
13540 }
13541 return nullptr;
13542 }
13543
13544 Matched = Specialization;
13545 if (FoundResult) *FoundResult = I.getPair();
13546 }
13547
13548 if (Matched &&
13549 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13550 return nullptr;
13551
13552 return Matched;
13553}
13554
13555// Resolve and fix an overloaded expression that can be resolved
13556// because it identifies a single function template specialization.
13557//
13558// Last three arguments should only be supplied if Complain = true
13559//
13560// Return true if it was logically possible to so resolve the
13561// expression, regardless of whether or not it succeeded. Always
13562// returns true if 'complain' is set.
13564 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13565 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13566 unsigned DiagIDForComplaining) {
13567 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13568
13570
13571 DeclAccessPair found;
13572 ExprResult SingleFunctionExpression;
13573 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13574 ovl.Expression, /*complain*/ false, &found)) {
13575 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13576 SrcExpr = ExprError();
13577 return true;
13578 }
13579
13580 // It is only correct to resolve to an instance method if we're
13581 // resolving a form that's permitted to be a pointer to member.
13582 // Otherwise we'll end up making a bound member expression, which
13583 // is illegal in all the contexts we resolve like this.
13584 if (!ovl.HasFormOfMemberPointer &&
13585 isa<CXXMethodDecl>(fn) &&
13586 cast<CXXMethodDecl>(fn)->isInstance()) {
13587 if (!complain) return false;
13588
13589 Diag(ovl.Expression->getExprLoc(),
13590 diag::err_bound_member_function)
13591 << 0 << ovl.Expression->getSourceRange();
13592
13593 // TODO: I believe we only end up here if there's a mix of
13594 // static and non-static candidates (otherwise the expression
13595 // would have 'bound member' type, not 'overload' type).
13596 // Ideally we would note which candidate was chosen and why
13597 // the static candidates were rejected.
13598 SrcExpr = ExprError();
13599 return true;
13600 }
13601
13602 // Fix the expression to refer to 'fn'.
13603 SingleFunctionExpression =
13604 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13605
13606 // If desired, do function-to-pointer decay.
13607 if (doFunctionPointerConversion) {
13608 SingleFunctionExpression =
13609 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13610 if (SingleFunctionExpression.isInvalid()) {
13611 SrcExpr = ExprError();
13612 return true;
13613 }
13614 }
13615 }
13616
13617 if (!SingleFunctionExpression.isUsable()) {
13618 if (complain) {
13619 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13620 << ovl.Expression->getName()
13621 << DestTypeForComplaining
13622 << OpRangeForComplaining
13624 NoteAllOverloadCandidates(SrcExpr.get());
13625
13626 SrcExpr = ExprError();
13627 return true;
13628 }
13629
13630 return false;
13631 }
13632
13633 SrcExpr = SingleFunctionExpression;
13634 return true;
13635}
13636
13637/// Add a single candidate to the overload set.
13639 DeclAccessPair FoundDecl,
13640 TemplateArgumentListInfo *ExplicitTemplateArgs,
13641 ArrayRef<Expr *> Args,
13642 OverloadCandidateSet &CandidateSet,
13643 bool PartialOverloading,
13644 bool KnownValid) {
13645 NamedDecl *Callee = FoundDecl.getDecl();
13646 if (isa<UsingShadowDecl>(Callee))
13647 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13648
13649 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13650 if (ExplicitTemplateArgs) {
13651 assert(!KnownValid && "Explicit template arguments?");
13652 return;
13653 }
13654 // Prevent ill-formed function decls to be added as overload candidates.
13655 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13656 return;
13657
13658 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13659 /*SuppressUserConversions=*/false,
13660 PartialOverloading);
13661 return;
13662 }
13663
13664 if (FunctionTemplateDecl *FuncTemplate
13665 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13666 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13667 ExplicitTemplateArgs, Args, CandidateSet,
13668 /*SuppressUserConversions=*/false,
13669 PartialOverloading);
13670 return;
13671 }
13672
13673 assert(!KnownValid && "unhandled case in overloaded call candidate");
13674}
13675
13676/// Add the overload candidates named by callee and/or found by argument
13677/// dependent lookup to the given overload set.
13679 ArrayRef<Expr *> Args,
13680 OverloadCandidateSet &CandidateSet,
13681 bool PartialOverloading) {
13682
13683#ifndef NDEBUG
13684 // Verify that ArgumentDependentLookup is consistent with the rules
13685 // in C++0x [basic.lookup.argdep]p3:
13686 //
13687 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13688 // and let Y be the lookup set produced by argument dependent
13689 // lookup (defined as follows). If X contains
13690 //
13691 // -- a declaration of a class member, or
13692 //
13693 // -- a block-scope function declaration that is not a
13694 // using-declaration, or
13695 //
13696 // -- a declaration that is neither a function or a function
13697 // template
13698 //
13699 // then Y is empty.
13700
13701 if (ULE->requiresADL()) {
13703 E = ULE->decls_end(); I != E; ++I) {
13704 assert(!(*I)->getDeclContext()->isRecord());
13705 assert(isa<UsingShadowDecl>(*I) ||
13706 !(*I)->getDeclContext()->isFunctionOrMethod());
13707 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13708 }
13709 }
13710#endif
13711
13712 // It would be nice to avoid this copy.
13713 TemplateArgumentListInfo TABuffer;
13714 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13715 if (ULE->hasExplicitTemplateArgs()) {
13716 ULE->copyTemplateArgumentsInto(TABuffer);
13717 ExplicitTemplateArgs = &TABuffer;
13718 }
13719
13721 E = ULE->decls_end(); I != E; ++I)
13722 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13723 CandidateSet, PartialOverloading,
13724 /*KnownValid*/ true);
13725
13726 if (ULE->requiresADL())
13727 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13728 Args, ExplicitTemplateArgs,
13729 CandidateSet, PartialOverloading);
13730}
13731
13732/// Add the call candidates from the given set of lookup results to the given
13733/// overload set. Non-function lookup results are ignored.
13735 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13736 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13737 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13738 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13739 CandidateSet, false, /*KnownValid*/ false);
13740}
13741
13742/// Determine whether a declaration with the specified name could be moved into
13743/// a different namespace.
13745 switch (Name.getCXXOverloadedOperator()) {
13746 case OO_New: case OO_Array_New:
13747 case OO_Delete: case OO_Array_Delete:
13748 return false;
13749
13750 default:
13751 return true;
13752 }
13753}
13754
13755/// Attempt to recover from an ill-formed use of a non-dependent name in a
13756/// template, where the non-dependent name was declared after the template
13757/// was defined. This is common in code written for a compilers which do not
13758/// correctly implement two-stage name lookup.
13759///
13760/// Returns true if a viable candidate was found and a diagnostic was issued.
13762 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13764 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13765 CXXRecordDecl **FoundInClass = nullptr) {
13766 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13767 return false;
13768
13769 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13770 if (DC->isTransparentContext())
13771 continue;
13772
13773 SemaRef.LookupQualifiedName(R, DC);
13774
13775 if (!R.empty()) {
13777
13778 OverloadCandidateSet Candidates(FnLoc, CSK);
13779 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13780 Candidates);
13781
13784 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13785
13786 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13787 // We either found non-function declarations or a best viable function
13788 // at class scope. A class-scope lookup result disables ADL. Don't
13789 // look past this, but let the caller know that we found something that
13790 // either is, or might be, usable in this class.
13791 if (FoundInClass) {
13792 *FoundInClass = RD;
13793 if (OR == OR_Success) {
13794 R.clear();
13795 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13796 R.resolveKind();
13797 }
13798 }
13799 return false;
13800 }
13801
13802 if (OR != OR_Success) {
13803 // There wasn't a unique best function or function template.
13804 return false;
13805 }
13806
13807 // Find the namespaces where ADL would have looked, and suggest
13808 // declaring the function there instead.
13809 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13810 Sema::AssociatedClassSet AssociatedClasses;
13811 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13812 AssociatedNamespaces,
13813 AssociatedClasses);
13814 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13816 DeclContext *Std = SemaRef.getStdNamespace();
13817 for (Sema::AssociatedNamespaceSet::iterator
13818 it = AssociatedNamespaces.begin(),
13819 end = AssociatedNamespaces.end(); it != end; ++it) {
13820 // Never suggest declaring a function within namespace 'std'.
13821 if (Std && Std->Encloses(*it))
13822 continue;
13823
13824 // Never suggest declaring a function within a namespace with a
13825 // reserved name, like __gnu_cxx.
13826 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13827 if (NS &&
13828 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13829 continue;
13830
13831 SuggestedNamespaces.insert(*it);
13832 }
13833 }
13834
13835 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13836 << R.getLookupName();
13837 if (SuggestedNamespaces.empty()) {
13838 SemaRef.Diag(Best->Function->getLocation(),
13839 diag::note_not_found_by_two_phase_lookup)
13840 << R.getLookupName() << 0;
13841 } else if (SuggestedNamespaces.size() == 1) {
13842 SemaRef.Diag(Best->Function->getLocation(),
13843 diag::note_not_found_by_two_phase_lookup)
13844 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13845 } else {
13846 // FIXME: It would be useful to list the associated namespaces here,
13847 // but the diagnostics infrastructure doesn't provide a way to produce
13848 // a localized representation of a list of items.
13849 SemaRef.Diag(Best->Function->getLocation(),
13850 diag::note_not_found_by_two_phase_lookup)
13851 << R.getLookupName() << 2;
13852 }
13853
13854 // Try to recover by calling this function.
13855 return true;
13856 }
13857
13858 R.clear();
13859 }
13860
13861 return false;
13862}
13863
13864/// Attempt to recover from ill-formed use of a non-dependent operator in a
13865/// template, where the non-dependent operator was declared after the template
13866/// was defined.
13867///
13868/// Returns true if a viable candidate was found and a diagnostic was issued.
13869static bool
13871 SourceLocation OpLoc,
13872 ArrayRef<Expr *> Args) {
13873 DeclarationName OpName =
13875 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13876 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13878 /*ExplicitTemplateArgs=*/nullptr, Args);
13879}
13880
13881namespace {
13882class BuildRecoveryCallExprRAII {
13883 Sema &SemaRef;
13885
13886public:
13887 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13888 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13889 SemaRef.IsBuildingRecoveryCallExpr = true;
13890 }
13891
13892 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13893};
13894}
13895
13896/// Attempts to recover from a call where no functions were found.
13897///
13898/// This function will do one of three things:
13899/// * Diagnose, recover, and return a recovery expression.
13900/// * Diagnose, fail to recover, and return ExprError().
13901/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13902/// expected to diagnose as appropriate.
13903static ExprResult
13906 SourceLocation LParenLoc,
13908 SourceLocation RParenLoc,
13909 bool EmptyLookup, bool AllowTypoCorrection) {
13910 // Do not try to recover if it is already building a recovery call.
13911 // This stops infinite loops for template instantiations like
13912 //
13913 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13914 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13915 if (SemaRef.IsBuildingRecoveryCallExpr)
13916 return ExprResult();
13917 BuildRecoveryCallExprRAII RCE(SemaRef);
13918
13919 CXXScopeSpec SS;
13920 SS.Adopt(ULE->getQualifierLoc());
13921 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13922
13923 TemplateArgumentListInfo TABuffer;
13924 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13925 if (ULE->hasExplicitTemplateArgs()) {
13926 ULE->copyTemplateArgumentsInto(TABuffer);
13927 ExplicitTemplateArgs = &TABuffer;
13928 }
13929
13930 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13932 CXXRecordDecl *FoundInClass = nullptr;
13933 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13935 ExplicitTemplateArgs, Args, &FoundInClass)) {
13936 // OK, diagnosed a two-phase lookup issue.
13937 } else if (EmptyLookup) {
13938 // Try to recover from an empty lookup with typo correction.
13939 R.clear();
13940 NoTypoCorrectionCCC NoTypoValidator{};
13941 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13942 ExplicitTemplateArgs != nullptr,
13943 dyn_cast<MemberExpr>(Fn));
13944 CorrectionCandidateCallback &Validator =
13945 AllowTypoCorrection
13946 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13947 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13948 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13949 Args))
13950 return ExprError();
13951 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13952 // We found a usable declaration of the name in a dependent base of some
13953 // enclosing class.
13954 // FIXME: We should also explain why the candidates found by name lookup
13955 // were not viable.
13956 if (SemaRef.DiagnoseDependentMemberLookup(R))
13957 return ExprError();
13958 } else {
13959 // We had viable candidates and couldn't recover; let the caller diagnose
13960 // this.
13961 return ExprResult();
13962 }
13963
13964 // If we get here, we should have issued a diagnostic and formed a recovery
13965 // lookup result.
13966 assert(!R.empty() && "lookup results empty despite recovery");
13967
13968 // If recovery created an ambiguity, just bail out.
13969 if (R.isAmbiguous()) {
13971 return ExprError();
13972 }
13973
13974 // Build an implicit member call if appropriate. Just drop the
13975 // casts and such from the call, we don't really care.
13976 ExprResult NewFn = ExprError();
13977 if ((*R.begin())->isCXXClassMember())
13978 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13979 ExplicitTemplateArgs, S);
13980 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13981 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13982 ExplicitTemplateArgs);
13983 else
13984 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13985
13986 if (NewFn.isInvalid())
13987 return ExprError();
13988
13989 // This shouldn't cause an infinite loop because we're giving it
13990 // an expression with viable lookup results, which should never
13991 // end up here.
13992 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13993 MultiExprArg(Args.data(), Args.size()),
13994 RParenLoc);
13995}
13996
13997/// Constructs and populates an OverloadedCandidateSet from
13998/// the given function.
13999/// \returns true when an the ExprResult output parameter has been set.
14002 MultiExprArg Args,
14003 SourceLocation RParenLoc,
14004 OverloadCandidateSet *CandidateSet,
14005 ExprResult *Result) {
14006#ifndef NDEBUG
14007 if (ULE->requiresADL()) {
14008 // To do ADL, we must have found an unqualified name.
14009 assert(!ULE->getQualifier() && "qualified name with ADL");
14010
14011 // We don't perform ADL for implicit declarations of builtins.
14012 // Verify that this was correctly set up.
14013 FunctionDecl *F;
14014 if (ULE->decls_begin() != ULE->decls_end() &&
14015 ULE->decls_begin() + 1 == ULE->decls_end() &&
14016 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14017 F->getBuiltinID() && F->isImplicit())
14018 llvm_unreachable("performing ADL for builtin");
14019
14020 // We don't perform ADL in C.
14021 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14022 }
14023#endif
14024
14025 UnbridgedCastsSet UnbridgedCasts;
14026 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14027 *Result = ExprError();
14028 return true;
14029 }
14030
14031 // Add the functions denoted by the callee to the set of candidate
14032 // functions, including those from argument-dependent lookup.
14033 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14034
14035 if (getLangOpts().MSVCCompat &&
14036 CurContext->isDependentContext() && !isSFINAEContext() &&
14037 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14038
14040 if (CandidateSet->empty() ||
14041 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14043 // In Microsoft mode, if we are inside a template class member function
14044 // then create a type dependent CallExpr. The goal is to postpone name
14045 // lookup to instantiation time to be able to search into type dependent
14046 // base classes.
14047 CallExpr *CE =
14048 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14049 RParenLoc, CurFPFeatureOverrides());
14051 *Result = CE;
14052 return true;
14053 }
14054 }
14055
14056 if (CandidateSet->empty())
14057 return false;
14058
14059 UnbridgedCasts.restore();
14060 return false;
14061}
14062
14063// Guess at what the return type for an unresolvable overload should be.
14066 std::optional<QualType> Result;
14067 // Adjust Type after seeing a candidate.
14068 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14069 if (!Candidate.Function)
14070 return;
14071 if (Candidate.Function->isInvalidDecl())
14072 return;
14073 QualType T = Candidate.Function->getReturnType();
14074 if (T.isNull())
14075 return;
14076 if (!Result)
14077 Result = T;
14078 else if (Result != T)
14079 Result = QualType();
14080 };
14081
14082 // Look for an unambiguous type from a progressively larger subset.
14083 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14084 //
14085 // First, consider only the best candidate.
14086 if (Best && *Best != CS.end())
14087 ConsiderCandidate(**Best);
14088 // Next, consider only viable candidates.
14089 if (!Result)
14090 for (const auto &C : CS)
14091 if (C.Viable)
14092 ConsiderCandidate(C);
14093 // Finally, consider all candidates.
14094 if (!Result)
14095 for (const auto &C : CS)
14096 ConsiderCandidate(C);
14097
14098 if (!Result)
14099 return QualType();
14100 auto Value = *Result;
14101 if (Value.isNull() || Value->isUndeducedType())
14102 return QualType();
14103 return Value;
14104}
14105
14106/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14107/// the completed call expression. If overload resolution fails, emits
14108/// diagnostics and returns ExprError()
14111 SourceLocation LParenLoc,
14112 MultiExprArg Args,
14113 SourceLocation RParenLoc,
14114 Expr *ExecConfig,
14115 OverloadCandidateSet *CandidateSet,
14117 OverloadingResult OverloadResult,
14118 bool AllowTypoCorrection) {
14119 switch (OverloadResult) {
14120 case OR_Success: {
14121 FunctionDecl *FDecl = (*Best)->Function;
14122 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14123 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14124 return ExprError();
14125 ExprResult Res =
14126 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14127 if (Res.isInvalid())
14128 return ExprError();
14129 return SemaRef.BuildResolvedCallExpr(
14130 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14131 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14132 }
14133
14134 case OR_No_Viable_Function: {
14135 // Try to recover by looking for viable functions which the user might
14136 // have meant to call.
14137 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14138 Args, RParenLoc,
14139 CandidateSet->empty(),
14140 AllowTypoCorrection);
14141 if (Recovery.isInvalid() || Recovery.isUsable())
14142 return Recovery;
14143
14144 // If the user passes in a function that we can't take the address of, we
14145 // generally end up emitting really bad error messages. Here, we attempt to
14146 // emit better ones.
14147 for (const Expr *Arg : Args) {
14148 if (!Arg->getType()->isFunctionType())
14149 continue;
14150 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14151 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14152 if (FD &&
14153 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14154 Arg->getExprLoc()))
14155 return ExprError();
14156 }
14157 }
14158
14159 CandidateSet->NoteCandidates(
14161 Fn->getBeginLoc(),
14162 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14163 << ULE->getName() << Fn->getSourceRange()),
14164 SemaRef, OCD_AllCandidates, Args);
14165 break;
14166 }
14167
14168 case OR_Ambiguous:
14169 CandidateSet->NoteCandidates(
14171 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14172 << ULE->getName() << Fn->getSourceRange()),
14173 SemaRef, OCD_AmbiguousCandidates, Args);
14174 break;
14175
14176 case OR_Deleted: {
14177 FunctionDecl *FDecl = (*Best)->Function;
14179 Fn->getSourceRange(), ULE->getName(),
14180 *CandidateSet, FDecl, Args);
14181
14182 // We emitted an error for the unavailable/deleted function call but keep
14183 // the call in the AST.
14184 ExprResult Res =
14185 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14186 if (Res.isInvalid())
14187 return ExprError();
14188 return SemaRef.BuildResolvedCallExpr(
14189 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14190 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14191 }
14192 }
14193
14194 // Overload resolution failed, try to recover.
14195 SmallVector<Expr *, 8> SubExprs = {Fn};
14196 SubExprs.append(Args.begin(), Args.end());
14197 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14198 chooseRecoveryType(*CandidateSet, Best));
14199}
14200
14203 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14204 if (I->Viable &&
14205 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14206 I->Viable = false;
14207 I->FailureKind = ovl_fail_addr_not_available;
14208 }
14209 }
14210}
14211
14212/// BuildOverloadedCallExpr - Given the call expression that calls Fn
14213/// (which eventually refers to the declaration Func) and the call
14214/// arguments Args/NumArgs, attempt to resolve the function call down
14215/// to a specific function. If overload resolution succeeds, returns
14216/// the call expression produced by overload resolution.
14217/// Otherwise, emits diagnostics and returns ExprError.
14220 SourceLocation LParenLoc,
14221 MultiExprArg Args,
14222 SourceLocation RParenLoc,
14223 Expr *ExecConfig,
14224 bool AllowTypoCorrection,
14225 bool CalleesAddressIsTaken) {
14226 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14228 ExprResult result;
14229
14230 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14231 &result))
14232 return result;
14233
14234 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14235 // functions that aren't addressible are considered unviable.
14236 if (CalleesAddressIsTaken)
14237 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14238
14240 OverloadingResult OverloadResult =
14241 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14242
14243 // Model the case with a call to a templated function whose definition
14244 // encloses the call and whose return type contains a placeholder type as if
14245 // the UnresolvedLookupExpr was type-dependent.
14246 if (OverloadResult == OR_Success) {
14247 const FunctionDecl *FDecl = Best->Function;
14248 if (FDecl && FDecl->isTemplateInstantiation() &&
14249 FDecl->getReturnType()->isUndeducedType()) {
14250 if (const auto *TP =
14251 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14252 TP && TP->willHaveBody()) {
14253 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14254 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14255 }
14256 }
14257 }
14258
14259 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14260 ExecConfig, &CandidateSet, &Best,
14261 OverloadResult, AllowTypoCorrection);
14262}
14263
14267 const UnresolvedSetImpl &Fns,
14268 bool PerformADL) {
14269 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14270 PerformADL, Fns.begin(), Fns.end(),
14271 /*KnownDependent=*/false);
14272}
14273
14275 CXXConversionDecl *Method,
14276 bool HadMultipleCandidates) {
14277 // Convert the expression to match the conversion function's implicit object
14278 // parameter.
14279 ExprResult Exp;
14280 if (Method->isExplicitObjectMemberFunction())
14281 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14282 else
14283 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14284 FoundDecl, Method);
14285 if (Exp.isInvalid())
14286 return true;
14287
14288 if (Method->getParent()->isLambda() &&
14290 // This is a lambda conversion to block pointer; check if the argument
14291 // was a LambdaExpr.
14292 Expr *SubE = E;
14293 auto *CE = dyn_cast<CastExpr>(SubE);
14294 if (CE && CE->getCastKind() == CK_NoOp)
14295 SubE = CE->getSubExpr();
14296 SubE = SubE->IgnoreParens();
14297 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14298 SubE = BE->getSubExpr();
14299 if (isa<LambdaExpr>(SubE)) {
14300 // For the conversion to block pointer on a lambda expression, we
14301 // construct a special BlockLiteral instead; this doesn't really make
14302 // a difference in ARC, but outside of ARC the resulting block literal
14303 // follows the normal lifetime rules for block literals instead of being
14304 // autoreleased.
14305 PushExpressionEvaluationContext(
14306 ExpressionEvaluationContext::PotentiallyEvaluated);
14307 ExprResult BlockExp = BuildBlockForLambdaConversion(
14308 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14309 PopExpressionEvaluationContext();
14310
14311 // FIXME: This note should be produced by a CodeSynthesisContext.
14312 if (BlockExp.isInvalid())
14313 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14314 return BlockExp;
14315 }
14316 }
14317 CallExpr *CE;
14318 QualType ResultType = Method->getReturnType();
14320 ResultType = ResultType.getNonLValueExprType(Context);
14321 if (Method->isExplicitObjectMemberFunction()) {
14322 ExprResult FnExpr =
14323 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14324 HadMultipleCandidates, E->getBeginLoc());
14325 if (FnExpr.isInvalid())
14326 return ExprError();
14327 Expr *ObjectParam = Exp.get();
14328 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14329 ResultType, VK, Exp.get()->getEndLoc(),
14330 CurFPFeatureOverrides());
14331 } else {
14332 MemberExpr *ME =
14333 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14335 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14336 HadMultipleCandidates, DeclarationNameInfo(),
14338
14339 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14340 Exp.get()->getEndLoc(),
14341 CurFPFeatureOverrides());
14342 }
14343
14344 if (CheckFunctionCall(Method, CE,
14345 Method->getType()->castAs<FunctionProtoType>()))
14346 return ExprError();
14347
14348 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14349}
14350
14351/// Create a unary operation that may resolve to an overloaded
14352/// operator.
14353///
14354/// \param OpLoc The location of the operator itself (e.g., '*').
14355///
14356/// \param Opc The UnaryOperatorKind that describes this operator.
14357///
14358/// \param Fns The set of non-member functions that will be
14359/// considered by overload resolution. The caller needs to build this
14360/// set based on the context using, e.g.,
14361/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14362/// set should not contain any member functions; those will be added
14363/// by CreateOverloadedUnaryOp().
14364///
14365/// \param Input The input argument.
14368 const UnresolvedSetImpl &Fns,
14369 Expr *Input, bool PerformADL) {
14371 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14373 // TODO: provide better source location info.
14374 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14375
14376 if (checkPlaceholderForOverload(*this, Input))
14377 return ExprError();
14378
14379 Expr *Args[2] = { Input, nullptr };
14380 unsigned NumArgs = 1;
14381
14382 // For post-increment and post-decrement, add the implicit '0' as
14383 // the second argument, so that we know this is a post-increment or
14384 // post-decrement.
14385 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14386 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14387 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14388 SourceLocation());
14389 NumArgs = 2;
14390 }
14391
14392 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14393
14394 if (Input->isTypeDependent()) {
14396 // [C++26][expr.unary.op][expr.pre.incr]
14397 // The * operator yields an lvalue of type
14398 // The pre/post increment operators yied an lvalue.
14399 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14400 VK = VK_LValue;
14401
14402 if (Fns.empty())
14403 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14404 OK_Ordinary, OpLoc, false,
14405 CurFPFeatureOverrides());
14406
14407 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14408 ExprResult Fn = CreateUnresolvedLookupExpr(
14409 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14410 if (Fn.isInvalid())
14411 return ExprError();
14412 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14413 Context.DependentTy, VK, OpLoc,
14414 CurFPFeatureOverrides());
14415 }
14416
14417 // Build an empty overload set.
14419
14420 // Add the candidates from the given function set.
14421 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14422
14423 // Add operator candidates that are member functions.
14424 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14425
14426 // Add candidates from ADL.
14427 if (PerformADL) {
14428 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14429 /*ExplicitTemplateArgs*/nullptr,
14430 CandidateSet);
14431 }
14432
14433 // Add builtin operator candidates.
14434 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14435
14436 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14437
14438 // Perform overload resolution.
14440 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14441 case OR_Success: {
14442 // We found a built-in operator or an overloaded operator.
14443 FunctionDecl *FnDecl = Best->Function;
14444
14445 if (FnDecl) {
14446 Expr *Base = nullptr;
14447 // We matched an overloaded operator. Build a call to that
14448 // operator.
14449
14450 // Convert the arguments.
14451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14452 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14453
14454 ExprResult InputInit;
14455 if (Method->isExplicitObjectMemberFunction())
14456 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14457 else
14458 InputInit = PerformImplicitObjectArgumentInitialization(
14459 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14460 if (InputInit.isInvalid())
14461 return ExprError();
14462 Base = Input = InputInit.get();
14463 } else {
14464 // Convert the arguments.
14465 ExprResult InputInit
14466 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14467 Context,
14468 FnDecl->getParamDecl(0)),
14470 Input);
14471 if (InputInit.isInvalid())
14472 return ExprError();
14473 Input = InputInit.get();
14474 }
14475
14476 // Build the actual expression node.
14477 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14478 Base, HadMultipleCandidates,
14479 OpLoc);
14480 if (FnExpr.isInvalid())
14481 return ExprError();
14482
14483 // Determine the result type.
14484 QualType ResultTy = FnDecl->getReturnType();
14486 ResultTy = ResultTy.getNonLValueExprType(Context);
14487
14488 Args[0] = Input;
14490 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14491 CurFPFeatureOverrides(), Best->IsADLCandidate);
14492
14493 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14494 return ExprError();
14495
14496 if (CheckFunctionCall(FnDecl, TheCall,
14497 FnDecl->getType()->castAs<FunctionProtoType>()))
14498 return ExprError();
14499 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14500 } else {
14501 // We matched a built-in operator. Convert the arguments, then
14502 // break out so that we will build the appropriate built-in
14503 // operator node.
14504 ExprResult InputRes = PerformImplicitConversion(
14505 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14507 if (InputRes.isInvalid())
14508 return ExprError();
14509 Input = InputRes.get();
14510 break;
14511 }
14512 }
14513
14515 // This is an erroneous use of an operator which can be overloaded by
14516 // a non-member function. Check for non-member operators which were
14517 // defined too late to be candidates.
14518 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14519 // FIXME: Recover by calling the found function.
14520 return ExprError();
14521
14522 // No viable function; fall through to handling this as a
14523 // built-in operator, which will produce an error message for us.
14524 break;
14525
14526 case OR_Ambiguous:
14527 CandidateSet.NoteCandidates(
14528 PartialDiagnosticAt(OpLoc,
14529 PDiag(diag::err_ovl_ambiguous_oper_unary)
14531 << Input->getType() << Input->getSourceRange()),
14532 *this, OCD_AmbiguousCandidates, ArgsArray,
14533 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14534 return ExprError();
14535
14536 case OR_Deleted: {
14537 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14538 // object whose method was called. Later in NoteCandidates size of ArgsArray
14539 // is passed further and it eventually ends up compared to number of
14540 // function candidate parameters which never includes the object parameter,
14541 // so slice ArgsArray to make sure apples are compared to apples.
14542 StringLiteral *Msg = Best->Function->getDeletedMessage();
14543 CandidateSet.NoteCandidates(
14544 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14546 << (Msg != nullptr)
14547 << (Msg ? Msg->getString() : StringRef())
14548 << Input->getSourceRange()),
14549 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14550 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14551 return ExprError();
14552 }
14553 }
14554
14555 // Either we found no viable overloaded operator or we matched a
14556 // built-in operator. In either case, fall through to trying to
14557 // build a built-in operation.
14558 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14559}
14560
14561/// Perform lookup for an overloaded binary operator.
14564 const UnresolvedSetImpl &Fns,
14565 ArrayRef<Expr *> Args, bool PerformADL) {
14566 SourceLocation OpLoc = CandidateSet.getLocation();
14567
14568 OverloadedOperatorKind ExtraOp =
14571 : OO_None;
14572
14573 // Add the candidates from the given function set. This also adds the
14574 // rewritten candidates using these functions if necessary.
14575 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14576
14577 // Add operator candidates that are member functions.
14578 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14579 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14580 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14582
14583 // In C++20, also add any rewritten member candidates.
14584 if (ExtraOp) {
14585 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14586 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14587 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14588 CandidateSet,
14590 }
14591
14592 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14593 // performed for an assignment operator (nor for operator[] nor operator->,
14594 // which don't get here).
14595 if (Op != OO_Equal && PerformADL) {
14597 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14598 /*ExplicitTemplateArgs*/ nullptr,
14599 CandidateSet);
14600 if (ExtraOp) {
14601 DeclarationName ExtraOpName =
14602 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14603 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14604 /*ExplicitTemplateArgs*/ nullptr,
14605 CandidateSet);
14606 }
14607 }
14608
14609 // Add builtin operator candidates.
14610 //
14611 // FIXME: We don't add any rewritten candidates here. This is strictly
14612 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14613 // resulting in our selecting a rewritten builtin candidate. For example:
14614 //
14615 // enum class E { e };
14616 // bool operator!=(E, E) requires false;
14617 // bool k = E::e != E::e;
14618 //
14619 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14620 // it seems unreasonable to consider rewritten builtin candidates. A core
14621 // issue has been filed proposing to removed this requirement.
14622 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14623}
14624
14625/// Create a binary operation that may resolve to an overloaded
14626/// operator.
14627///
14628/// \param OpLoc The location of the operator itself (e.g., '+').
14629///
14630/// \param Opc The BinaryOperatorKind that describes this operator.
14631///
14632/// \param Fns The set of non-member functions that will be
14633/// considered by overload resolution. The caller needs to build this
14634/// set based on the context using, e.g.,
14635/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14636/// set should not contain any member functions; those will be added
14637/// by CreateOverloadedBinOp().
14638///
14639/// \param LHS Left-hand argument.
14640/// \param RHS Right-hand argument.
14641/// \param PerformADL Whether to consider operator candidates found by ADL.
14642/// \param AllowRewrittenCandidates Whether to consider candidates found by
14643/// C++20 operator rewrites.
14644/// \param DefaultedFn If we are synthesizing a defaulted operator function,
14645/// the function in question. Such a function is never a candidate in
14646/// our overload resolution. This also enables synthesizing a three-way
14647/// comparison from < and == as described in C++20 [class.spaceship]p1.
14650 const UnresolvedSetImpl &Fns, Expr *LHS,
14651 Expr *RHS, bool PerformADL,
14652 bool AllowRewrittenCandidates,
14653 FunctionDecl *DefaultedFn) {
14654 Expr *Args[2] = { LHS, RHS };
14655 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14656
14657 if (!getLangOpts().CPlusPlus20)
14658 AllowRewrittenCandidates = false;
14659
14661
14662 // If either side is type-dependent, create an appropriate dependent
14663 // expression.
14664 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14665 if (Fns.empty()) {
14666 // If there are no functions to store, just build a dependent
14667 // BinaryOperator or CompoundAssignment.
14670 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14671 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14672 Context.DependentTy);
14674 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14675 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14676 }
14677
14678 // FIXME: save results of ADL from here?
14679 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14680 // TODO: provide better source location info in DNLoc component.
14682 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14683 ExprResult Fn = CreateUnresolvedLookupExpr(
14684 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14685 if (Fn.isInvalid())
14686 return ExprError();
14687 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14688 Context.DependentTy, VK_PRValue, OpLoc,
14689 CurFPFeatureOverrides());
14690 }
14691
14692 // If this is the .* operator, which is not overloadable, just
14693 // create a built-in binary operator.
14694 if (Opc == BO_PtrMemD) {
14695 auto CheckPlaceholder = [&](Expr *&Arg) {
14696 ExprResult Res = CheckPlaceholderExpr(Arg);
14697 if (Res.isUsable())
14698 Arg = Res.get();
14699 return !Res.isUsable();
14700 };
14701
14702 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14703 // expression that contains placeholders (in either the LHS or RHS).
14704 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14705 return ExprError();
14706 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14707 }
14708
14709 // Always do placeholder-like conversions on the RHS.
14710 if (checkPlaceholderForOverload(*this, Args[1]))
14711 return ExprError();
14712
14713 // Do placeholder-like conversion on the LHS; note that we should
14714 // not get here with a PseudoObject LHS.
14715 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14716 if (checkPlaceholderForOverload(*this, Args[0]))
14717 return ExprError();
14718
14719 // If this is the assignment operator, we only perform overload resolution
14720 // if the left-hand side is a class or enumeration type. This is actually
14721 // a hack. The standard requires that we do overload resolution between the
14722 // various built-in candidates, but as DR507 points out, this can lead to
14723 // problems. So we do it this way, which pretty much follows what GCC does.
14724 // Note that we go the traditional code path for compound assignment forms.
14725 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14726 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14727
14728 // Build the overload set.
14731 Op, OpLoc, AllowRewrittenCandidates));
14732 if (DefaultedFn)
14733 CandidateSet.exclude(DefaultedFn);
14734 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14735
14736 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14737
14738 // Perform overload resolution.
14740 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14741 case OR_Success: {
14742 // We found a built-in operator or an overloaded operator.
14743 FunctionDecl *FnDecl = Best->Function;
14744
14745 bool IsReversed = Best->isReversed();
14746 if (IsReversed)
14747 std::swap(Args[0], Args[1]);
14748
14749 if (FnDecl) {
14750
14751 if (FnDecl->isInvalidDecl())
14752 return ExprError();
14753
14754 Expr *Base = nullptr;
14755 // We matched an overloaded operator. Build a call to that
14756 // operator.
14757
14758 OverloadedOperatorKind ChosenOp =
14760
14761 // C++2a [over.match.oper]p9:
14762 // If a rewritten operator== candidate is selected by overload
14763 // resolution for an operator@, its return type shall be cv bool
14764 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14765 !FnDecl->getReturnType()->isBooleanType()) {
14766 bool IsExtension =
14768 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14769 : diag::err_ovl_rewrite_equalequal_not_bool)
14770 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14771 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14772 Diag(FnDecl->getLocation(), diag::note_declared_at);
14773 if (!IsExtension)
14774 return ExprError();
14775 }
14776
14777 if (AllowRewrittenCandidates && !IsReversed &&
14778 CandidateSet.getRewriteInfo().isReversible()) {
14779 // We could have reversed this operator, but didn't. Check if some
14780 // reversed form was a viable candidate, and if so, if it had a
14781 // better conversion for either parameter. If so, this call is
14782 // formally ambiguous, and allowing it is an extension.
14784 for (OverloadCandidate &Cand : CandidateSet) {
14785 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14786 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14787 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14789 *this, OpLoc, Cand.Conversions[ArgIdx],
14790 Best->Conversions[ArgIdx]) ==
14792 AmbiguousWith.push_back(Cand.Function);
14793 break;
14794 }
14795 }
14796 }
14797 }
14798
14799 if (!AmbiguousWith.empty()) {
14800 bool AmbiguousWithSelf =
14801 AmbiguousWith.size() == 1 &&
14802 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14803 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14805 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14806 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14807 if (AmbiguousWithSelf) {
14808 Diag(FnDecl->getLocation(),
14809 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14810 // Mark member== const or provide matching != to disallow reversed
14811 // args. Eg.
14812 // struct S { bool operator==(const S&); };
14813 // S()==S();
14814 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14815 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14816 !MD->isConst() &&
14817 !MD->hasCXXExplicitFunctionObjectParameter() &&
14818 Context.hasSameUnqualifiedType(
14819 MD->getFunctionObjectParameterType(),
14820 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14821 Context.hasSameUnqualifiedType(
14822 MD->getFunctionObjectParameterType(),
14823 Args[0]->getType()) &&
14824 Context.hasSameUnqualifiedType(
14825 MD->getFunctionObjectParameterType(),
14826 Args[1]->getType()))
14827 Diag(FnDecl->getLocation(),
14828 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14829 } else {
14830 Diag(FnDecl->getLocation(),
14831 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14832 for (auto *F : AmbiguousWith)
14833 Diag(F->getLocation(),
14834 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14835 }
14836 }
14837 }
14838
14839 // Check for nonnull = nullable.
14840 // This won't be caught in the arg's initialization: the parameter to
14841 // the assignment operator is not marked nonnull.
14842 if (Op == OO_Equal)
14843 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14844 Args[1]->getType(), OpLoc);
14845
14846 // Convert the arguments.
14847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14848 // Best->Access is only meaningful for class members.
14849 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14850
14851 ExprResult Arg0, Arg1;
14852 unsigned ParamIdx = 0;
14853 if (Method->isExplicitObjectMemberFunction()) {
14854 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14855 ParamIdx = 1;
14856 } else {
14857 Arg0 = PerformImplicitObjectArgumentInitialization(
14858 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14859 }
14860 Arg1 = PerformCopyInitialization(
14862 Context, FnDecl->getParamDecl(ParamIdx)),
14863 SourceLocation(), Args[1]);
14864 if (Arg0.isInvalid() || Arg1.isInvalid())
14865 return ExprError();
14866
14867 Base = Args[0] = Arg0.getAs<Expr>();
14868 Args[1] = RHS = Arg1.getAs<Expr>();
14869 } else {
14870 // Convert the arguments.
14871 ExprResult Arg0 = PerformCopyInitialization(
14873 FnDecl->getParamDecl(0)),
14874 SourceLocation(), Args[0]);
14875 if (Arg0.isInvalid())
14876 return ExprError();
14877
14878 ExprResult Arg1 =
14879 PerformCopyInitialization(
14881 FnDecl->getParamDecl(1)),
14882 SourceLocation(), Args[1]);
14883 if (Arg1.isInvalid())
14884 return ExprError();
14885 Args[0] = LHS = Arg0.getAs<Expr>();
14886 Args[1] = RHS = Arg1.getAs<Expr>();
14887 }
14888
14889 // Build the actual expression node.
14890 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14891 Best->FoundDecl, Base,
14892 HadMultipleCandidates, OpLoc);
14893 if (FnExpr.isInvalid())
14894 return ExprError();
14895
14896 // Determine the result type.
14897 QualType ResultTy = FnDecl->getReturnType();
14899 ResultTy = ResultTy.getNonLValueExprType(Context);
14900
14901 CallExpr *TheCall;
14902 ArrayRef<const Expr *> ArgsArray(Args, 2);
14903 const Expr *ImplicitThis = nullptr;
14904
14905 // We always create a CXXOperatorCallExpr, even for explicit object
14906 // members; CodeGen should take care not to emit the this pointer.
14908 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14909 CurFPFeatureOverrides(), Best->IsADLCandidate);
14910
14911 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14912 Method && Method->isImplicitObjectMemberFunction()) {
14913 // Cut off the implicit 'this'.
14914 ImplicitThis = ArgsArray[0];
14915 ArgsArray = ArgsArray.slice(1);
14916 }
14917
14918 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14919 FnDecl))
14920 return ExprError();
14921
14922 // Check for a self move.
14923 if (Op == OO_Equal)
14924 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14925
14926 if (ImplicitThis) {
14927 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14928 QualType ThisTypeFromDecl = Context.getPointerType(
14929 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14930
14931 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14932 ThisTypeFromDecl);
14933 }
14934
14935 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14936 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14937 VariadicDoesNotApply);
14938
14939 ExprResult R = MaybeBindToTemporary(TheCall);
14940 if (R.isInvalid())
14941 return ExprError();
14942
14943 R = CheckForImmediateInvocation(R, FnDecl);
14944 if (R.isInvalid())
14945 return ExprError();
14946
14947 // For a rewritten candidate, we've already reversed the arguments
14948 // if needed. Perform the rest of the rewrite now.
14949 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14950 (Op == OO_Spaceship && IsReversed)) {
14951 if (Op == OO_ExclaimEqual) {
14952 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14953 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14954 } else {
14955 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14956 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14957 Expr *ZeroLiteral =
14958 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14959
14962 Ctx.Entity = FnDecl;
14963 pushCodeSynthesisContext(Ctx);
14964
14965 R = CreateOverloadedBinOp(
14966 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14967 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14968 /*AllowRewrittenCandidates=*/false);
14969
14970 popCodeSynthesisContext();
14971 }
14972 if (R.isInvalid())
14973 return ExprError();
14974 } else {
14975 assert(ChosenOp == Op && "unexpected operator name");
14976 }
14977
14978 // Make a note in the AST if we did any rewriting.
14979 if (Best->RewriteKind != CRK_None)
14980 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14981
14982 return R;
14983 } else {
14984 // We matched a built-in operator. Convert the arguments, then
14985 // break out so that we will build the appropriate built-in
14986 // operator node.
14987 ExprResult ArgsRes0 = PerformImplicitConversion(
14988 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14990 if (ArgsRes0.isInvalid())
14991 return ExprError();
14992 Args[0] = ArgsRes0.get();
14993
14994 ExprResult ArgsRes1 = PerformImplicitConversion(
14995 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14997 if (ArgsRes1.isInvalid())
14998 return ExprError();
14999 Args[1] = ArgsRes1.get();
15000 break;
15001 }
15002 }
15003
15004 case OR_No_Viable_Function: {
15005 // C++ [over.match.oper]p9:
15006 // If the operator is the operator , [...] and there are no
15007 // viable functions, then the operator is assumed to be the
15008 // built-in operator and interpreted according to clause 5.
15009 if (Opc == BO_Comma)
15010 break;
15011
15012 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15013 // compare result using '==' and '<'.
15014 if (DefaultedFn && Opc == BO_Cmp) {
15015 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15016 Args[1], DefaultedFn);
15017 if (E.isInvalid() || E.isUsable())
15018 return E;
15019 }
15020
15021 // For class as left operand for assignment or compound assignment
15022 // operator do not fall through to handling in built-in, but report that
15023 // no overloaded assignment operator found
15025 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15026 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15027 Args, OpLoc);
15028 DeferDiagsRAII DDR(*this,
15029 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15030 if (Args[0]->getType()->isRecordType() &&
15031 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15032 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15034 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15035 if (Args[0]->getType()->isIncompleteType()) {
15036 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15037 << Args[0]->getType()
15038 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15039 }
15040 } else {
15041 // This is an erroneous use of an operator which can be overloaded by
15042 // a non-member function. Check for non-member operators which were
15043 // defined too late to be candidates.
15044 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15045 // FIXME: Recover by calling the found function.
15046 return ExprError();
15047
15048 // No viable function; try to create a built-in operation, which will
15049 // produce an error. Then, show the non-viable candidates.
15050 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15051 }
15052 assert(Result.isInvalid() &&
15053 "C++ binary operator overloading is missing candidates!");
15054 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15055 return Result;
15056 }
15057
15058 case OR_Ambiguous:
15059 CandidateSet.NoteCandidates(
15060 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15062 << Args[0]->getType()
15063 << Args[1]->getType()
15064 << Args[0]->getSourceRange()
15065 << Args[1]->getSourceRange()),
15067 OpLoc);
15068 return ExprError();
15069
15070 case OR_Deleted: {
15071 if (isImplicitlyDeleted(Best->Function)) {
15072 FunctionDecl *DeletedFD = Best->Function;
15073 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15074 if (DFK.isSpecialMember()) {
15075 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15076 << Args[0]->getType()
15077 << llvm::to_underlying(DFK.asSpecialMember());
15078 } else {
15079 assert(DFK.isComparison());
15080 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15081 << Args[0]->getType() << DeletedFD;
15082 }
15083
15084 // The user probably meant to call this special member. Just
15085 // explain why it's deleted.
15086 NoteDeletedFunction(DeletedFD);
15087 return ExprError();
15088 }
15089
15090 StringLiteral *Msg = Best->Function->getDeletedMessage();
15091 CandidateSet.NoteCandidates(
15093 OpLoc,
15094 PDiag(diag::err_ovl_deleted_oper)
15095 << getOperatorSpelling(Best->Function->getDeclName()
15096 .getCXXOverloadedOperator())
15097 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15098 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15100 OpLoc);
15101 return ExprError();
15102 }
15103 }
15104
15105 // We matched a built-in operator; build it.
15106 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15107}
15108
15110 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15111 FunctionDecl *DefaultedFn) {
15112 const ComparisonCategoryInfo *Info =
15113 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15114 // If we're not producing a known comparison category type, we can't
15115 // synthesize a three-way comparison. Let the caller diagnose this.
15116 if (!Info)
15117 return ExprResult((Expr*)nullptr);
15118
15119 // If we ever want to perform this synthesis more generally, we will need to
15120 // apply the temporary materialization conversion to the operands.
15121 assert(LHS->isGLValue() && RHS->isGLValue() &&
15122 "cannot use prvalue expressions more than once");
15123 Expr *OrigLHS = LHS;
15124 Expr *OrigRHS = RHS;
15125
15126 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15127 // each of them multiple times below.
15128 LHS = new (Context)
15129 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15130 LHS->getObjectKind(), LHS);
15131 RHS = new (Context)
15132 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15133 RHS->getObjectKind(), RHS);
15134
15135 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15136 DefaultedFn);
15137 if (Eq.isInvalid())
15138 return ExprError();
15139
15140 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15141 true, DefaultedFn);
15142 if (Less.isInvalid())
15143 return ExprError();
15144
15146 if (Info->isPartial()) {
15147 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15148 DefaultedFn);
15149 if (Greater.isInvalid())
15150 return ExprError();
15151 }
15152
15153 // Form the list of comparisons we're going to perform.
15154 struct Comparison {
15155 ExprResult Cmp;
15157 } Comparisons[4] =
15163 };
15164
15165 int I = Info->isPartial() ? 3 : 2;
15166
15167 // Combine the comparisons with suitable conditional expressions.
15169 for (; I >= 0; --I) {
15170 // Build a reference to the comparison category constant.
15171 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15172 // FIXME: Missing a constant for a comparison category. Diagnose this?
15173 if (!VI)
15174 return ExprResult((Expr*)nullptr);
15175 ExprResult ThisResult =
15176 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15177 if (ThisResult.isInvalid())
15178 return ExprError();
15179
15180 // Build a conditional unless this is the final case.
15181 if (Result.get()) {
15182 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15183 ThisResult.get(), Result.get());
15184 if (Result.isInvalid())
15185 return ExprError();
15186 } else {
15187 Result = ThisResult;
15188 }
15189 }
15190
15191 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15192 // bind the OpaqueValueExprs before they're (repeatedly) used.
15193 Expr *SyntacticForm = BinaryOperator::Create(
15194 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15195 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15196 CurFPFeatureOverrides());
15197 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15198 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15199}
15200
15202 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15203 MultiExprArg Args, SourceLocation LParenLoc) {
15204
15205 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15206 unsigned NumParams = Proto->getNumParams();
15207 unsigned NumArgsSlots =
15208 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15209 // Build the full argument list for the method call (the implicit object
15210 // parameter is placed at the beginning of the list).
15211 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15212 bool IsError = false;
15213 // Initialize the implicit object parameter.
15214 // Check the argument types.
15215 for (unsigned i = 0; i != NumParams; i++) {
15216 Expr *Arg;
15217 if (i < Args.size()) {
15218 Arg = Args[i];
15219 ExprResult InputInit =
15221 S.Context, Method->getParamDecl(i)),
15222 SourceLocation(), Arg);
15223 IsError |= InputInit.isInvalid();
15224 Arg = InputInit.getAs<Expr>();
15225 } else {
15226 ExprResult DefArg =
15227 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15228 if (DefArg.isInvalid()) {
15229 IsError = true;
15230 break;
15231 }
15232 Arg = DefArg.getAs<Expr>();
15233 }
15234
15235 MethodArgs.push_back(Arg);
15236 }
15237 return IsError;
15238}
15239
15241 SourceLocation RLoc,
15242 Expr *Base,
15243 MultiExprArg ArgExpr) {
15245 Args.push_back(Base);
15246 for (auto *e : ArgExpr) {
15247 Args.push_back(e);
15248 }
15249 DeclarationName OpName =
15250 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15251
15252 SourceRange Range = ArgExpr.empty()
15253 ? SourceRange{}
15254 : SourceRange(ArgExpr.front()->getBeginLoc(),
15255 ArgExpr.back()->getEndLoc());
15256
15257 // If either side is type-dependent, create an appropriate dependent
15258 // expression.
15260
15261 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15262 // CHECKME: no 'operator' keyword?
15263 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15264 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15265 ExprResult Fn = CreateUnresolvedLookupExpr(
15266 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15267 if (Fn.isInvalid())
15268 return ExprError();
15269 // Can't add any actual overloads yet
15270
15271 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15272 Context.DependentTy, VK_PRValue, RLoc,
15273 CurFPFeatureOverrides());
15274 }
15275
15276 // Handle placeholders
15277 UnbridgedCastsSet UnbridgedCasts;
15278 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15279 return ExprError();
15280 }
15281 // Build an empty overload set.
15283
15284 // Subscript can only be overloaded as a member function.
15285
15286 // Add operator candidates that are member functions.
15287 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15288
15289 // Add builtin operator candidates.
15290 if (Args.size() == 2)
15291 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15292
15293 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15294
15295 // Perform overload resolution.
15297 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15298 case OR_Success: {
15299 // We found a built-in operator or an overloaded operator.
15300 FunctionDecl *FnDecl = Best->Function;
15301
15302 if (FnDecl) {
15303 // We matched an overloaded operator. Build a call to that
15304 // operator.
15305
15306 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15307
15308 // Convert the arguments.
15309 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15310 SmallVector<Expr *, 2> MethodArgs;
15311
15312 // Initialize the object parameter.
15313 if (Method->isExplicitObjectMemberFunction()) {
15314 ExprResult Res =
15315 InitializeExplicitObjectArgument(*this, Args[0], Method);
15316 if (Res.isInvalid())
15317 return ExprError();
15318 Args[0] = Res.get();
15319 ArgExpr = Args;
15320 } else {
15321 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15322 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15323 if (Arg0.isInvalid())
15324 return ExprError();
15325
15326 MethodArgs.push_back(Arg0.get());
15327 }
15328
15330 *this, MethodArgs, Method, ArgExpr, LLoc);
15331 if (IsError)
15332 return ExprError();
15333
15334 // Build the actual expression node.
15335 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15336 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15338 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15339 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15340 if (FnExpr.isInvalid())
15341 return ExprError();
15342
15343 // Determine the result type
15344 QualType ResultTy = FnDecl->getReturnType();
15346 ResultTy = ResultTy.getNonLValueExprType(Context);
15347
15349 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15350 CurFPFeatureOverrides());
15351
15352 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15353 return ExprError();
15354
15355 if (CheckFunctionCall(Method, TheCall,
15356 Method->getType()->castAs<FunctionProtoType>()))
15357 return ExprError();
15358
15359 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15360 FnDecl);
15361 } else {
15362 // We matched a built-in operator. Convert the arguments, then
15363 // break out so that we will build the appropriate built-in
15364 // operator node.
15365 ExprResult ArgsRes0 = PerformImplicitConversion(
15366 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15368 if (ArgsRes0.isInvalid())
15369 return ExprError();
15370 Args[0] = ArgsRes0.get();
15371
15372 ExprResult ArgsRes1 = PerformImplicitConversion(
15373 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15375 if (ArgsRes1.isInvalid())
15376 return ExprError();
15377 Args[1] = ArgsRes1.get();
15378
15379 break;
15380 }
15381 }
15382
15383 case OR_No_Viable_Function: {
15385 CandidateSet.empty()
15386 ? (PDiag(diag::err_ovl_no_oper)
15387 << Args[0]->getType() << /*subscript*/ 0
15388 << Args[0]->getSourceRange() << Range)
15389 : (PDiag(diag::err_ovl_no_viable_subscript)
15390 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15391 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15392 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15393 return ExprError();
15394 }
15395
15396 case OR_Ambiguous:
15397 if (Args.size() == 2) {
15398 CandidateSet.NoteCandidates(
15400 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15401 << "[]" << Args[0]->getType() << Args[1]->getType()
15402 << Args[0]->getSourceRange() << Range),
15403 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15404 } else {
15405 CandidateSet.NoteCandidates(
15407 PDiag(diag::err_ovl_ambiguous_subscript_call)
15408 << Args[0]->getType()
15409 << Args[0]->getSourceRange() << Range),
15410 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15411 }
15412 return ExprError();
15413
15414 case OR_Deleted: {
15415 StringLiteral *Msg = Best->Function->getDeletedMessage();
15416 CandidateSet.NoteCandidates(
15418 PDiag(diag::err_ovl_deleted_oper)
15419 << "[]" << (Msg != nullptr)
15420 << (Msg ? Msg->getString() : StringRef())
15421 << Args[0]->getSourceRange() << Range),
15422 *this, OCD_AllCandidates, Args, "[]", LLoc);
15423 return ExprError();
15424 }
15425 }
15426
15427 // We matched a built-in operator; build it.
15428 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15429}
15430
15431/// BuildCallToMemberFunction - Build a call to a member
15432/// function. MemExpr is the expression that refers to the member
15433/// function (and includes the object parameter), Args/NumArgs are the
15434/// arguments to the function call (not including the object
15435/// parameter). The caller needs to validate that the member
15436/// expression refers to a non-static member function or an overloaded
15437/// member function.
15439 SourceLocation LParenLoc,
15440 MultiExprArg Args,
15441 SourceLocation RParenLoc,
15442 Expr *ExecConfig, bool IsExecConfig,
15443 bool AllowRecovery) {
15444 assert(MemExprE->getType() == Context.BoundMemberTy ||
15445 MemExprE->getType() == Context.OverloadTy);
15446
15447 // Dig out the member expression. This holds both the object
15448 // argument and the member function we're referring to.
15449 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15450
15451 // Determine whether this is a call to a pointer-to-member function.
15452 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15453 assert(op->getType() == Context.BoundMemberTy);
15454 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15455
15456 QualType fnType =
15457 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15458
15459 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15460 QualType resultType = proto->getCallResultType(Context);
15462
15463 // Check that the object type isn't more qualified than the
15464 // member function we're calling.
15465 Qualifiers funcQuals = proto->getMethodQuals();
15466
15467 QualType objectType = op->getLHS()->getType();
15468 if (op->getOpcode() == BO_PtrMemI)
15469 objectType = objectType->castAs<PointerType>()->getPointeeType();
15470 Qualifiers objectQuals = objectType.getQualifiers();
15471
15472 Qualifiers difference = objectQuals - funcQuals;
15473 difference.removeObjCGCAttr();
15474 difference.removeAddressSpace();
15475 if (difference) {
15476 std::string qualsString = difference.getAsString();
15477 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15478 << fnType.getUnqualifiedType()
15479 << qualsString
15480 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15481 }
15482
15484 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15485 CurFPFeatureOverrides(), proto->getNumParams());
15486
15487 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15488 call, nullptr))
15489 return ExprError();
15490
15491 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15492 return ExprError();
15493
15494 if (CheckOtherCall(call, proto))
15495 return ExprError();
15496
15497 return MaybeBindToTemporary(call);
15498 }
15499
15500 // We only try to build a recovery expr at this level if we can preserve
15501 // the return type, otherwise we return ExprError() and let the caller
15502 // recover.
15503 auto BuildRecoveryExpr = [&](QualType Type) {
15504 if (!AllowRecovery)
15505 return ExprError();
15506 std::vector<Expr *> SubExprs = {MemExprE};
15507 llvm::append_range(SubExprs, Args);
15508 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15509 Type);
15510 };
15511 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15512 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15513 RParenLoc, CurFPFeatureOverrides());
15514
15515 UnbridgedCastsSet UnbridgedCasts;
15516 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15517 return ExprError();
15518
15519 MemberExpr *MemExpr;
15520 CXXMethodDecl *Method = nullptr;
15521 bool HadMultipleCandidates = false;
15522 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15523 NestedNameSpecifier *Qualifier = nullptr;
15524 if (isa<MemberExpr>(NakedMemExpr)) {
15525 MemExpr = cast<MemberExpr>(NakedMemExpr);
15526 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15527 FoundDecl = MemExpr->getFoundDecl();
15528 Qualifier = MemExpr->getQualifier();
15529 UnbridgedCasts.restore();
15530 } else {
15531 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15532 Qualifier = UnresExpr->getQualifier();
15533
15534 QualType ObjectType = UnresExpr->getBaseType();
15535 Expr::Classification ObjectClassification
15537 : UnresExpr->getBase()->Classify(Context);
15538
15539 // Add overload candidates
15540 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15542
15543 // FIXME: avoid copy.
15544 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15545 if (UnresExpr->hasExplicitTemplateArgs()) {
15546 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15547 TemplateArgs = &TemplateArgsBuffer;
15548 }
15549
15551 E = UnresExpr->decls_end(); I != E; ++I) {
15552
15553 QualType ExplicitObjectType = ObjectType;
15554
15555 NamedDecl *Func = *I;
15556 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15557 if (isa<UsingShadowDecl>(Func))
15558 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15559
15560 bool HasExplicitParameter = false;
15561 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15562 M && M->hasCXXExplicitFunctionObjectParameter())
15563 HasExplicitParameter = true;
15564 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15565 M &&
15566 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15567 HasExplicitParameter = true;
15568
15569 if (HasExplicitParameter)
15570 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15571
15572 // Microsoft supports direct constructor calls.
15573 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15574 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15575 CandidateSet,
15576 /*SuppressUserConversions*/ false);
15577 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15578 // If explicit template arguments were provided, we can't call a
15579 // non-template member function.
15580 if (TemplateArgs)
15581 continue;
15582
15583 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15584 ObjectClassification, Args, CandidateSet,
15585 /*SuppressUserConversions=*/false);
15586 } else {
15587 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15588 I.getPair(), ActingDC, TemplateArgs,
15589 ExplicitObjectType, ObjectClassification,
15590 Args, CandidateSet,
15591 /*SuppressUserConversions=*/false);
15592 }
15593 }
15594
15595 HadMultipleCandidates = (CandidateSet.size() > 1);
15596
15597 DeclarationName DeclName = UnresExpr->getMemberName();
15598
15599 UnbridgedCasts.restore();
15600
15602 bool Succeeded = false;
15603 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15604 Best)) {
15605 case OR_Success:
15606 Method = cast<CXXMethodDecl>(Best->Function);
15607 FoundDecl = Best->FoundDecl;
15608 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15609 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15610 break;
15611 // If FoundDecl is different from Method (such as if one is a template
15612 // and the other a specialization), make sure DiagnoseUseOfDecl is
15613 // called on both.
15614 // FIXME: This would be more comprehensively addressed by modifying
15615 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15616 // being used.
15617 if (Method != FoundDecl.getDecl() &&
15618 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15619 break;
15620 Succeeded = true;
15621 break;
15622
15624 CandidateSet.NoteCandidates(
15626 UnresExpr->getMemberLoc(),
15627 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15628 << DeclName << MemExprE->getSourceRange()),
15629 *this, OCD_AllCandidates, Args);
15630 break;
15631 case OR_Ambiguous:
15632 CandidateSet.NoteCandidates(
15633 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15634 PDiag(diag::err_ovl_ambiguous_member_call)
15635 << DeclName << MemExprE->getSourceRange()),
15636 *this, OCD_AmbiguousCandidates, Args);
15637 break;
15638 case OR_Deleted:
15639 DiagnoseUseOfDeletedFunction(
15640 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15641 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15642 break;
15643 }
15644 // Overload resolution fails, try to recover.
15645 if (!Succeeded)
15646 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15647
15648 ExprResult Res =
15649 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15650 if (Res.isInvalid())
15651 return ExprError();
15652 MemExprE = Res.get();
15653
15654 // If overload resolution picked a static member
15655 // build a non-member call based on that function.
15656 if (Method->isStatic()) {
15657 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15658 ExecConfig, IsExecConfig);
15659 }
15660
15661 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15662 }
15663
15664 QualType ResultType = Method->getReturnType();
15666 ResultType = ResultType.getNonLValueExprType(Context);
15667
15668 assert(Method && "Member call to something that isn't a method?");
15669 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15670
15671 CallExpr *TheCall = nullptr;
15673 if (Method->isExplicitObjectMemberFunction()) {
15674 PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15675 NewArgs);
15676 // Build the actual expression node.
15677 ExprResult FnExpr =
15678 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15679 HadMultipleCandidates, MemExpr->getExprLoc());
15680 if (FnExpr.isInvalid())
15681 return ExprError();
15682
15683 TheCall =
15684 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15685 CurFPFeatureOverrides(), Proto->getNumParams());
15686 } else {
15687 // Convert the object argument (for a non-static member function call).
15688 // We only need to do this if there was actually an overload; otherwise
15689 // it was done at lookup.
15690 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15691 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15692 if (ObjectArg.isInvalid())
15693 return ExprError();
15694 MemExpr->setBase(ObjectArg.get());
15695 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15696 RParenLoc, CurFPFeatureOverrides(),
15697 Proto->getNumParams());
15698 }
15699
15700 // Check for a valid return type.
15701 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15702 TheCall, Method))
15703 return BuildRecoveryExpr(ResultType);
15704
15705 // Convert the rest of the arguments
15706 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15707 RParenLoc))
15708 return BuildRecoveryExpr(ResultType);
15709
15710 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15711
15712 if (CheckFunctionCall(Method, TheCall, Proto))
15713 return ExprError();
15714
15715 // In the case the method to call was not selected by the overloading
15716 // resolution process, we still need to handle the enable_if attribute. Do
15717 // that here, so it will not hide previous -- and more relevant -- errors.
15718 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15719 if (const EnableIfAttr *Attr =
15720 CheckEnableIf(Method, LParenLoc, Args, true)) {
15721 Diag(MemE->getMemberLoc(),
15722 diag::err_ovl_no_viable_member_function_in_call)
15723 << Method << Method->getSourceRange();
15724 Diag(Method->getLocation(),
15725 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15726 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15727 return ExprError();
15728 }
15729 }
15730
15731 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15732 TheCall->getDirectCallee()->isPureVirtual()) {
15733 const FunctionDecl *MD = TheCall->getDirectCallee();
15734
15735 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15736 MemExpr->performsVirtualDispatch(getLangOpts())) {
15737 Diag(MemExpr->getBeginLoc(),
15738 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15739 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15740 << MD->getParent();
15741
15742 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15743 if (getLangOpts().AppleKext)
15744 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15745 << MD->getParent() << MD->getDeclName();
15746 }
15747 }
15748
15749 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15750 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15751 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15752 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15753 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15754 MemExpr->getMemberLoc());
15755 }
15756
15757 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15758 TheCall->getDirectCallee());
15759}
15760
15761/// BuildCallToObjectOfClassType - Build a call to an object of class
15762/// type (C++ [over.call.object]), which can end up invoking an
15763/// overloaded function call operator (@c operator()) or performing a
15764/// user-defined conversion on the object argument.
15767 SourceLocation LParenLoc,
15768 MultiExprArg Args,
15769 SourceLocation RParenLoc) {
15770 if (checkPlaceholderForOverload(*this, Obj))
15771 return ExprError();
15772 ExprResult Object = Obj;
15773
15774 UnbridgedCastsSet UnbridgedCasts;
15775 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15776 return ExprError();
15777
15778 assert(Object.get()->getType()->isRecordType() &&
15779 "Requires object type argument");
15780
15781 // C++ [over.call.object]p1:
15782 // If the primary-expression E in the function call syntax
15783 // evaluates to a class object of type "cv T", then the set of
15784 // candidate functions includes at least the function call
15785 // operators of T. The function call operators of T are obtained by
15786 // ordinary lookup of the name operator() in the context of
15787 // (E).operator().
15788 OverloadCandidateSet CandidateSet(LParenLoc,
15790 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15791
15792 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15793 diag::err_incomplete_object_call, Object.get()))
15794 return true;
15795
15796 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15797 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15798 LookupQualifiedName(R, Record->getDecl());
15799 R.suppressAccessDiagnostics();
15800
15801 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15802 Oper != OperEnd; ++Oper) {
15803 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15804 Object.get()->Classify(Context), Args, CandidateSet,
15805 /*SuppressUserConversion=*/false);
15806 }
15807
15808 // When calling a lambda, both the call operator, and
15809 // the conversion operator to function pointer
15810 // are considered. But when constraint checking
15811 // on the call operator fails, it will also fail on the
15812 // conversion operator as the constraints are always the same.
15813 // As the user probably does not intend to perform a surrogate call,
15814 // we filter them out to produce better error diagnostics, ie to avoid
15815 // showing 2 failed overloads instead of one.
15816 bool IgnoreSurrogateFunctions = false;
15817 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15818 const OverloadCandidate &Candidate = *CandidateSet.begin();
15819 if (!Candidate.Viable &&
15821 IgnoreSurrogateFunctions = true;
15822 }
15823
15824 // C++ [over.call.object]p2:
15825 // In addition, for each (non-explicit in C++0x) conversion function
15826 // declared in T of the form
15827 //
15828 // operator conversion-type-id () cv-qualifier;
15829 //
15830 // where cv-qualifier is the same cv-qualification as, or a
15831 // greater cv-qualification than, cv, and where conversion-type-id
15832 // denotes the type "pointer to function of (P1,...,Pn) returning
15833 // R", or the type "reference to pointer to function of
15834 // (P1,...,Pn) returning R", or the type "reference to function
15835 // of (P1,...,Pn) returning R", a surrogate call function [...]
15836 // is also considered as a candidate function. Similarly,
15837 // surrogate call functions are added to the set of candidate
15838 // functions for each conversion function declared in an
15839 // accessible base class provided the function is not hidden
15840 // within T by another intervening declaration.
15841 const auto &Conversions =
15842 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15843 for (auto I = Conversions.begin(), E = Conversions.end();
15844 !IgnoreSurrogateFunctions && I != E; ++I) {
15845 NamedDecl *D = *I;
15846 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15847 if (isa<UsingShadowDecl>(D))
15848 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15849
15850 // Skip over templated conversion functions; they aren't
15851 // surrogates.
15852 if (isa<FunctionTemplateDecl>(D))
15853 continue;
15854
15855 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15856 if (!Conv->isExplicit()) {
15857 // Strip the reference type (if any) and then the pointer type (if
15858 // any) to get down to what might be a function type.
15859 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15860 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15861 ConvType = ConvPtrType->getPointeeType();
15862
15863 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15864 {
15865 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15866 Object.get(), Args, CandidateSet);
15867 }
15868 }
15869 }
15870
15871 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15872
15873 // Perform overload resolution.
15875 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15876 Best)) {
15877 case OR_Success:
15878 // Overload resolution succeeded; we'll build the appropriate call
15879 // below.
15880 break;
15881
15882 case OR_No_Viable_Function: {
15884 CandidateSet.empty()
15885 ? (PDiag(diag::err_ovl_no_oper)
15886 << Object.get()->getType() << /*call*/ 1
15887 << Object.get()->getSourceRange())
15888 : (PDiag(diag::err_ovl_no_viable_object_call)
15889 << Object.get()->getType() << Object.get()->getSourceRange());
15890 CandidateSet.NoteCandidates(
15891 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15892 OCD_AllCandidates, Args);
15893 break;
15894 }
15895 case OR_Ambiguous:
15896 if (!R.isAmbiguous())
15897 CandidateSet.NoteCandidates(
15898 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15899 PDiag(diag::err_ovl_ambiguous_object_call)
15900 << Object.get()->getType()
15901 << Object.get()->getSourceRange()),
15902 *this, OCD_AmbiguousCandidates, Args);
15903 break;
15904
15905 case OR_Deleted: {
15906 // FIXME: Is this diagnostic here really necessary? It seems that
15907 // 1. we don't have any tests for this diagnostic, and
15908 // 2. we already issue err_deleted_function_use for this later on anyway.
15909 StringLiteral *Msg = Best->Function->getDeletedMessage();
15910 CandidateSet.NoteCandidates(
15911 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15912 PDiag(diag::err_ovl_deleted_object_call)
15913 << Object.get()->getType() << (Msg != nullptr)
15914 << (Msg ? Msg->getString() : StringRef())
15915 << Object.get()->getSourceRange()),
15916 *this, OCD_AllCandidates, Args);
15917 break;
15918 }
15919 }
15920
15921 if (Best == CandidateSet.end())
15922 return true;
15923
15924 UnbridgedCasts.restore();
15925
15926 if (Best->Function == nullptr) {
15927 // Since there is no function declaration, this is one of the
15928 // surrogate candidates. Dig out the conversion function.
15929 CXXConversionDecl *Conv
15930 = cast<CXXConversionDecl>(
15931 Best->Conversions[0].UserDefined.ConversionFunction);
15932
15933 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15934 Best->FoundDecl);
15935 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15936 return ExprError();
15937 assert(Conv == Best->FoundDecl.getDecl() &&
15938 "Found Decl & conversion-to-functionptr should be same, right?!");
15939 // We selected one of the surrogate functions that converts the
15940 // object parameter to a function pointer. Perform the conversion
15941 // on the object argument, then let BuildCallExpr finish the job.
15942
15943 // Create an implicit member expr to refer to the conversion operator.
15944 // and then call it.
15945 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15946 Conv, HadMultipleCandidates);
15947 if (Call.isInvalid())
15948 return ExprError();
15949 // Record usage of conversion in an implicit cast.
15951 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15952 nullptr, VK_PRValue, CurFPFeatureOverrides());
15953
15954 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15955 }
15956
15957 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15958
15959 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15960 // that calls this method, using Object for the implicit object
15961 // parameter and passing along the remaining arguments.
15962 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15963
15964 // An error diagnostic has already been printed when parsing the declaration.
15965 if (Method->isInvalidDecl())
15966 return ExprError();
15967
15968 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15969 unsigned NumParams = Proto->getNumParams();
15970
15971 DeclarationNameInfo OpLocInfo(
15972 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15973 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15974 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15975 Obj, HadMultipleCandidates,
15976 OpLocInfo.getLoc(),
15977 OpLocInfo.getInfo());
15978 if (NewFn.isInvalid())
15979 return true;
15980
15981 SmallVector<Expr *, 8> MethodArgs;
15982 MethodArgs.reserve(NumParams + 1);
15983
15984 bool IsError = false;
15985
15986 // Initialize the object parameter.
15988 if (Method->isExplicitObjectMemberFunction()) {
15989 // FIXME: we should do that during the definition of the lambda when we can.
15990 DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15991 PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15992 } else {
15993 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15994 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15995 if (ObjRes.isInvalid())
15996 IsError = true;
15997 else
15998 Object = ObjRes;
15999 MethodArgs.push_back(Object.get());
16000 }
16001
16003 *this, MethodArgs, Method, Args, LParenLoc);
16004
16005 // If this is a variadic call, handle args passed through "...".
16006 if (Proto->isVariadic()) {
16007 // Promote the arguments (C99 6.5.2.2p7).
16008 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16009 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
16010 nullptr);
16011 IsError |= Arg.isInvalid();
16012 MethodArgs.push_back(Arg.get());
16013 }
16014 }
16015
16016 if (IsError)
16017 return true;
16018
16019 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16020
16021 // Once we've built TheCall, all of the expressions are properly owned.
16022 QualType ResultTy = Method->getReturnType();
16024 ResultTy = ResultTy.getNonLValueExprType(Context);
16025
16027 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16028 CurFPFeatureOverrides());
16029
16030 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16031 return true;
16032
16033 if (CheckFunctionCall(Method, TheCall, Proto))
16034 return true;
16035
16036 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16037}
16038
16039/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
16040/// (if one exists), where @c Base is an expression of class type and
16041/// @c Member is the name of the member we're trying to find.
16044 bool *NoArrowOperatorFound) {
16045 assert(Base->getType()->isRecordType() &&
16046 "left-hand side must have class type");
16047
16049 return ExprError();
16050
16051 SourceLocation Loc = Base->getExprLoc();
16052
16053 // C++ [over.ref]p1:
16054 //
16055 // [...] An expression x->m is interpreted as (x.operator->())->m
16056 // for a class object x of type T if T::operator->() exists and if
16057 // the operator is selected as the best match function by the
16058 // overload resolution mechanism (13.3).
16059 DeclarationName OpName =
16060 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16062
16063 if (RequireCompleteType(Loc, Base->getType(),
16064 diag::err_typecheck_incomplete_tag, Base))
16065 return ExprError();
16066
16067 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16068 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16070
16071 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16072 Oper != OperEnd; ++Oper) {
16073 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16074 std::nullopt, CandidateSet,
16075 /*SuppressUserConversion=*/false);
16076 }
16077
16078 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16079
16080 // Perform overload resolution.
16082 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16083 case OR_Success:
16084 // Overload resolution succeeded; we'll build the call below.
16085 break;
16086
16087 case OR_No_Viable_Function: {
16088 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16089 if (CandidateSet.empty()) {
16090 QualType BaseType = Base->getType();
16091 if (NoArrowOperatorFound) {
16092 // Report this specific error to the caller instead of emitting a
16093 // diagnostic, as requested.
16094 *NoArrowOperatorFound = true;
16095 return ExprError();
16096 }
16097 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16098 << BaseType << Base->getSourceRange();
16099 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16100 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16101 << FixItHint::CreateReplacement(OpLoc, ".");
16102 }
16103 } else
16104 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16105 << "operator->" << Base->getSourceRange();
16106 CandidateSet.NoteCandidates(*this, Base, Cands);
16107 return ExprError();
16108 }
16109 case OR_Ambiguous:
16110 if (!R.isAmbiguous())
16111 CandidateSet.NoteCandidates(
16112 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16113 << "->" << Base->getType()
16114 << Base->getSourceRange()),
16116 return ExprError();
16117
16118 case OR_Deleted: {
16119 StringLiteral *Msg = Best->Function->getDeletedMessage();
16120 CandidateSet.NoteCandidates(
16121 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16122 << "->" << (Msg != nullptr)
16123 << (Msg ? Msg->getString() : StringRef())
16124 << Base->getSourceRange()),
16125 *this, OCD_AllCandidates, Base);
16126 return ExprError();
16127 }
16128 }
16129
16130 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16131
16132 // Convert the object parameter.
16133 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16134
16135 if (Method->isExplicitObjectMemberFunction()) {
16136 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16137 if (R.isInvalid())
16138 return ExprError();
16139 Base = R.get();
16140 } else {
16141 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16142 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16143 if (BaseResult.isInvalid())
16144 return ExprError();
16145 Base = BaseResult.get();
16146 }
16147
16148 // Build the operator call.
16149 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16150 Base, HadMultipleCandidates, OpLoc);
16151 if (FnExpr.isInvalid())
16152 return ExprError();
16153
16154 QualType ResultTy = Method->getReturnType();
16156 ResultTy = ResultTy.getNonLValueExprType(Context);
16157
16158 CallExpr *TheCall =
16159 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16160 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16161
16162 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16163 return ExprError();
16164
16165 if (CheckFunctionCall(Method, TheCall,
16166 Method->getType()->castAs<FunctionProtoType>()))
16167 return ExprError();
16168
16169 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16170}
16171
16172/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
16173/// a literal operator described by the provided lookup results.
16175 DeclarationNameInfo &SuffixInfo,
16176 ArrayRef<Expr*> Args,
16177 SourceLocation LitEndLoc,
16178 TemplateArgumentListInfo *TemplateArgs) {
16179 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16180
16181 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16183 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16184 TemplateArgs);
16185
16186 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16187
16188 // Perform overload resolution. This will usually be trivial, but might need
16189 // to perform substitutions for a literal operator template.
16191 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16192 case OR_Success:
16193 case OR_Deleted:
16194 break;
16195
16197 CandidateSet.NoteCandidates(
16198 PartialDiagnosticAt(UDSuffixLoc,
16199 PDiag(diag::err_ovl_no_viable_function_in_call)
16200 << R.getLookupName()),
16201 *this, OCD_AllCandidates, Args);
16202 return ExprError();
16203
16204 case OR_Ambiguous:
16205 CandidateSet.NoteCandidates(
16206 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16207 << R.getLookupName()),
16208 *this, OCD_AmbiguousCandidates, Args);
16209 return ExprError();
16210 }
16211
16212 FunctionDecl *FD = Best->Function;
16213 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16214 nullptr, HadMultipleCandidates,
16215 SuffixInfo.getLoc(),
16216 SuffixInfo.getInfo());
16217 if (Fn.isInvalid())
16218 return true;
16219
16220 // Check the argument types. This should almost always be a no-op, except
16221 // that array-to-pointer decay is applied to string literals.
16222 Expr *ConvArgs[2];
16223 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16224 ExprResult InputInit = PerformCopyInitialization(
16226 SourceLocation(), Args[ArgIdx]);
16227 if (InputInit.isInvalid())
16228 return true;
16229 ConvArgs[ArgIdx] = InputInit.get();
16230 }
16231
16232 QualType ResultTy = FD->getReturnType();
16234 ResultTy = ResultTy.getNonLValueExprType(Context);
16235
16237 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16238 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16239
16240 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16241 return ExprError();
16242
16243 if (CheckFunctionCall(FD, UDL, nullptr))
16244 return ExprError();
16245
16246 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16247}
16248
16249/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16250/// given LookupResult is non-empty, it is assumed to describe a member which
16251/// will be invoked. Otherwise, the function will be found via argument
16252/// dependent lookup.
16253/// CallExpr is set to a valid expression and FRS_Success returned on success,
16254/// otherwise CallExpr is set to ExprError() and some non-success value
16255/// is returned.
16258 SourceLocation RangeLoc,
16259 const DeclarationNameInfo &NameInfo,
16260 LookupResult &MemberLookup,
16261 OverloadCandidateSet *CandidateSet,
16262 Expr *Range, ExprResult *CallExpr) {
16263 Scope *S = nullptr;
16264
16266 if (!MemberLookup.empty()) {
16267 ExprResult MemberRef =
16268 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16269 /*IsPtr=*/false, CXXScopeSpec(),
16270 /*TemplateKWLoc=*/SourceLocation(),
16271 /*FirstQualifierInScope=*/nullptr,
16272 MemberLookup,
16273 /*TemplateArgs=*/nullptr, S);
16274 if (MemberRef.isInvalid()) {
16275 *CallExpr = ExprError();
16276 return FRS_DiagnosticIssued;
16277 }
16278 *CallExpr =
16279 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16280 if (CallExpr->isInvalid()) {
16281 *CallExpr = ExprError();
16282 return FRS_DiagnosticIssued;
16283 }
16284 } else {
16285 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16287 NameInfo, UnresolvedSet<0>());
16288 if (FnR.isInvalid())
16289 return FRS_DiagnosticIssued;
16290 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16291
16292 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16293 CandidateSet, CallExpr);
16294 if (CandidateSet->empty() || CandidateSetError) {
16295 *CallExpr = ExprError();
16296 return FRS_NoViableFunction;
16297 }
16299 OverloadingResult OverloadResult =
16300 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16301
16302 if (OverloadResult == OR_No_Viable_Function) {
16303 *CallExpr = ExprError();
16304 return FRS_NoViableFunction;
16305 }
16306 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16307 Loc, nullptr, CandidateSet, &Best,
16308 OverloadResult,
16309 /*AllowTypoCorrection=*/false);
16310 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16311 *CallExpr = ExprError();
16312 return FRS_DiagnosticIssued;
16313 }
16314 }
16315 return FRS_Success;
16316}
16317
16318
16319/// FixOverloadedFunctionReference - E is an expression that refers to
16320/// a C++ overloaded function (possibly with some parentheses and
16321/// perhaps a '&' around it). We have resolved the overloaded function
16322/// to the function declaration Fn, so patch up the expression E to
16323/// refer (possibly indirectly) to Fn. Returns the new expr.
16325 FunctionDecl *Fn) {
16326 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16327 ExprResult SubExpr =
16328 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16329 if (SubExpr.isInvalid())
16330 return ExprError();
16331 if (SubExpr.get() == PE->getSubExpr())
16332 return PE;
16333
16334 return new (Context)
16335 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16336 }
16337
16338 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16339 ExprResult SubExpr =
16340 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16341 if (SubExpr.isInvalid())
16342 return ExprError();
16343 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16344 SubExpr.get()->getType()) &&
16345 "Implicit cast type cannot be determined from overload");
16346 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16347 if (SubExpr.get() == ICE->getSubExpr())
16348 return ICE;
16349
16350 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16351 SubExpr.get(), nullptr, ICE->getValueKind(),
16352 CurFPFeatureOverrides());
16353 }
16354
16355 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16356 if (!GSE->isResultDependent()) {
16357 ExprResult SubExpr =
16358 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16359 if (SubExpr.isInvalid())
16360 return ExprError();
16361 if (SubExpr.get() == GSE->getResultExpr())
16362 return GSE;
16363
16364 // Replace the resulting type information before rebuilding the generic
16365 // selection expression.
16366 ArrayRef<Expr *> A = GSE->getAssocExprs();
16367 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16368 unsigned ResultIdx = GSE->getResultIndex();
16369 AssocExprs[ResultIdx] = SubExpr.get();
16370
16371 if (GSE->isExprPredicate())
16373 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16374 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16375 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16376 ResultIdx);
16378 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16379 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16380 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16381 ResultIdx);
16382 }
16383 // Rather than fall through to the unreachable, return the original generic
16384 // selection expression.
16385 return GSE;
16386 }
16387
16388 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16389 assert(UnOp->getOpcode() == UO_AddrOf &&
16390 "Can only take the address of an overloaded function");
16391 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16392 if (Method->isStatic()) {
16393 // Do nothing: static member functions aren't any different
16394 // from non-member functions.
16395 } else {
16396 // Fix the subexpression, which really has to be an
16397 // UnresolvedLookupExpr holding an overloaded member function
16398 // or template.
16399 ExprResult SubExpr =
16400 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16401 if (SubExpr.isInvalid())
16402 return ExprError();
16403 if (SubExpr.get() == UnOp->getSubExpr())
16404 return UnOp;
16405
16406 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16407 SubExpr.get(), Method))
16408 return ExprError();
16409
16410 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16411 "fixed to something other than a decl ref");
16412 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16413 "fixed to a member ref with no nested name qualifier");
16414
16415 // We have taken the address of a pointer to member
16416 // function. Perform the computation here so that we get the
16417 // appropriate pointer to member type.
16418 QualType ClassType
16419 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16420 QualType MemPtrType
16421 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16422 // Under the MS ABI, lock down the inheritance model now.
16423 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16424 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16425
16426 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16427 MemPtrType, VK_PRValue, OK_Ordinary,
16428 UnOp->getOperatorLoc(), false,
16429 CurFPFeatureOverrides());
16430 }
16431 }
16432 ExprResult SubExpr =
16433 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16434 if (SubExpr.isInvalid())
16435 return ExprError();
16436 if (SubExpr.get() == UnOp->getSubExpr())
16437 return UnOp;
16438
16439 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16440 SubExpr.get());
16441 }
16442
16443 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16444 // FIXME: avoid copy.
16445 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16446 if (ULE->hasExplicitTemplateArgs()) {
16447 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16448 TemplateArgs = &TemplateArgsBuffer;
16449 }
16450
16451 QualType Type = Fn->getType();
16452 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16453
16454 // FIXME: Duplicated from BuildDeclarationNameExpr.
16455 if (unsigned BID = Fn->getBuiltinID()) {
16456 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16457 Type = Context.BuiltinFnTy;
16458 ValueKind = VK_PRValue;
16459 }
16460 }
16461
16462 DeclRefExpr *DRE = BuildDeclRefExpr(
16463 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16464 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16465 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16466 return DRE;
16467 }
16468
16469 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16470 // FIXME: avoid copy.
16471 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16472 if (MemExpr->hasExplicitTemplateArgs()) {
16473 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16474 TemplateArgs = &TemplateArgsBuffer;
16475 }
16476
16477 Expr *Base;
16478
16479 // If we're filling in a static method where we used to have an
16480 // implicit member access, rewrite to a simple decl ref.
16481 if (MemExpr->isImplicitAccess()) {
16482 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16483 DeclRefExpr *DRE = BuildDeclRefExpr(
16484 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16485 MemExpr->getQualifierLoc(), Found.getDecl(),
16486 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16487 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16488 return DRE;
16489 } else {
16490 SourceLocation Loc = MemExpr->getMemberLoc();
16491 if (MemExpr->getQualifier())
16492 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16493 Base =
16494 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16495 }
16496 } else
16497 Base = MemExpr->getBase();
16498
16499 ExprValueKind valueKind;
16500 QualType type;
16501 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16502 valueKind = VK_LValue;
16503 type = Fn->getType();
16504 } else {
16505 valueKind = VK_PRValue;
16506 type = Context.BoundMemberTy;
16507 }
16508
16509 return BuildMemberExpr(
16510 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16511 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16512 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16513 type, valueKind, OK_Ordinary, TemplateArgs);
16514 }
16515
16516 llvm_unreachable("Invalid reference to overloaded function");
16517}
16518
16520 DeclAccessPair Found,
16521 FunctionDecl *Fn) {
16522 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16523}
16524
16525bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16527 if (!PartialOverloading || !Function)
16528 return true;
16529 if (Function->isVariadic())
16530 return false;
16531 if (const auto *Proto =
16532 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16533 if (Proto->isTemplateVariadic())
16534 return false;
16535 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16536 if (const auto *Proto =
16537 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16538 if (Proto->isTemplateVariadic())
16539 return false;
16540 return true;
16541}
16542
16544 DeclarationName Name,
16545 OverloadCandidateSet &CandidateSet,
16546 FunctionDecl *Fn, MultiExprArg Args,
16547 bool IsMember) {
16548 StringLiteral *Msg = Fn->getDeletedMessage();
16549 CandidateSet.NoteCandidates(
16550 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16551 << IsMember << Name << (Msg != nullptr)
16552 << (Msg ? Msg->getString() : StringRef())
16553 << Range),
16554 *this, OCD_AllCandidates, Args);
16555}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3284
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
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.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:143
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.
static std::string getName(const CallEvent &Call)
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5703
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 isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static 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 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 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 isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
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 ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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 ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
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 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs)
General arity mismatch diagnosis over a candidate in a candidate set.
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 ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
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 ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
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 CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs)
Additional arity mismatch diagnosis specific to a function overload candidates.
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
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 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 NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch)
Defines the SourceManager interface.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
__device__ __2f16 b
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:867
iterator end()
Definition: Lookup.h:891
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:883
iterator begin()
Definition: Lookup.h:890
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:888
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:397
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1100
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.
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1103
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
CanQualType DoubleTy
Definition: ASTContext.h:1103
CanQualType LongDoubleTy
Definition: ASTContext.h:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
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 DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1590
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
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...
bool canBindObjCObjectType(QualType To, QualType From)
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1103
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>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2271
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
Definition: ASTContext.h:1092
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:758
CanQualType Float128Ty
Definition: ASTContext.h:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1278
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType CharTy
Definition: ASTContext.h:1093
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType SignedCharTy
Definition: ASTContext.h:1100
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1119
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2063
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
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.
Definition: ASTContext.h:2340
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1102
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1287
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1101
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1568
CanQualType ShortTy
Definition: ASTContext.h:1100
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
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...
CanQualType Char32Ty
Definition: ASTContext.h:1099
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2151
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:757
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
Definition: ASTContext.h:1100
CanQualType WCharTy
Definition: ASTContext.h:1094
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1097
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
QualType getElementType() const
Definition: Type.h:3526
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7185
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
StringRef getOpcodeStr() const
Definition: Expr.h:3905
bool isCompoundAssignmentOp() const
Definition: Expr.h:3983
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:4781
Pointer to a block type.
Definition: Type.h:3345
This class is used for builtin types like 'int'.
Definition: Type.h:2977
Kind getKind() const
Definition: Type.h:3019
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2898
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
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:626
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:2455
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2214
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2576
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2565
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2186
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:562
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:1022
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1833
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
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:1494
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3142
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1508
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
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 isAtLeastAsQualifiedAs(CanQual< T > Other) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
bool isVolatileQualified() const
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
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: Type.h:3082
QualType getElementType() const
Definition: Type.h:3092
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:4803
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3552
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1938
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
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:1447
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:239
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:235
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1116
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isInvalidDecl() const
Definition: DeclBase.h:594
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:575
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:570
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:746
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:731
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:722
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3868
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4073
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
EnumDecl * getDecl() const
Definition: Type.h:5578
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1921
const Expr * getExpr() const
Definition: DeclCXX.h:1906
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2144
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
static Classification makeSimpleLValue()
Create a simple, modifiably lvalue.
Definition: Expr.h:388
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool isPRValue() const
Definition: Expr.h:278
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3279
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4079
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
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:3918
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3058
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
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:97
Represents a function declaration or definition.
Definition: Decl.h:1971
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2600
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
param_iterator param_end()
Definition: Decl.h:2697
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2668
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3536
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3576
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:4113
unsigned getMinRequiredExplicitArguments() const
Returns the minimum number of non-object arguments needed to call this function.
Definition: Decl.cpp:3740
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
param_iterator param_begin()
Definition: Decl.h:2696
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4239
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3314
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4106
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3735
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2433
bool isDeletedAsWritten() const
Definition: Decl.h:2507
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3572
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2348
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4397
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
bool isConsteval() const
Definition: Decl.h:2445
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3580
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:2772
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2662
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:3585
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3889
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2596
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
unsigned getNumParams() const
Definition: Type.h:4885
Qualifiers getMethodQuals() const
Definition: Type.h:5026
QualType getParamType(unsigned i) const
Definition: Type.h:4887
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
ArrayRef< QualType > param_types() const
Definition: Type.h:5040
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4363
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4437
bool getNoReturn() const
Definition: Type.h:4411
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
ExtInfo getExtInfo() const
Definition: Type.h:4581
CallingConv getCallConv() const
Definition: Type.h:4580
QualType getReturnType() const
Definition: Type.h:4569
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4593
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:4470
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:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
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:594
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:691
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
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:742
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:602
bool hasInitializerListContainerType() const
Definition: Overload.h:724
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:655
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:731
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:606
QualType getInitializerListContainerType() const
Definition: Overload.h:734
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:4847
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4954
unsigned getNumInits() const
Definition: Expr.h:4877
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2466
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2484
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, NonTypeTemplateParmDecl *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:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3420
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:625
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:603
DeclClass * getAsSingle() const
Definition: Lookup.h:556
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:662
bool isAmbiguous() const
Definition: Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:639
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3361
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3269
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3390
Expr * getBase() const
Definition: Expr.h:3249
void setBase(Expr *E)
Definition: Expr.h:3248
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3283
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1798
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3367
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3259
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
QualType getPointeeType() const
Definition: Type.h:3472
const Type * getClass() const
Definition: Type.h:3486
Describes a module or submodule.
Definition: Module.h:105
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:244
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6948
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
unsigned param_size() const
Definition: DeclObjC.h:347
bool isVariadic() const
Definition: DeclObjC.h:431
Represents a pointer to an Objective C object.
Definition: Type.h:7004
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7093
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7062
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7016
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7056
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1787
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7068
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1137
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1164
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions=std::nullopt)
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1178
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1130
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1001
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:996
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:1145
SourceLocation getLocation() const
Definition: Overload.h:1128
CandidateSetKind getKind() const
Definition: Overload.h:1129
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:2976
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3091
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3127
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3036
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3088
decls_iterator decls_begin() const
Definition: ExprCXX.h:3068
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3079
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3101
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3097
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3147
decls_iterator decls_end() const
Definition: ExprCXX.h:3071
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3085
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2938
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4875
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7433
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7537
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
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: Type.h:7556
QualType getCanonicalType() const
Definition: Type.h:7407
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1092
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7527
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7428
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7476
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7401
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7387
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7295
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7302
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4272
bool hasAtomic() const
Definition: Type.h:844
bool hasRestrict() const
Definition: Type.h:843
QualifiersAndAtomic withVolatile()
Definition: Type.h:856
QualifiersAndAtomic withAtomic()
Definition: Type.h:863
bool hasVolatile() const
Definition: Type.h:841
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
GC getObjCGCAttr() const
Definition: Type.h:505
bool hasOnlyConst() const
Definition: Type.h:444
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
void removeObjCLifetime()
Definition: Type.h:537
bool hasConst() const
Definition: Type.h:443
void addRestrict()
Definition: Type.h:466
bool hasRestrict() const
Definition: Type.h:463
void removeObjCGCAttr()
Definition: Type.h:509
void removeUnaligned()
Definition: Type.h:501
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
bool hasVolatile() const
Definition: Type.h:453
bool hasObjCGCAttr() const
Definition: Type.h:504
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
Qualifiers withoutObjCLifetime() const
Definition: Type.h:519
bool empty() const
Definition: Type.h:633
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:754
void addVolatile()
Definition: Type.h:456
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:534
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3438
Represents a struct/union/class.
Definition: Decl.h:4169
field_range fields() const
Definition: Decl.h:4375
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
QualType getPointeeType() const
Definition: Type.h:3394
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
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: SemaCUDA.h:176
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
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:372
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:314
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:320
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:227
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:8056
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4681
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4710
RAII class to control scope of DeferDiags.
Definition: Sema.h:7905
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:9508
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9538
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
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.
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2476
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:7921
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:7388
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
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:167
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:998
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
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:8139
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8142
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8148
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8146
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...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
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:1420
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.
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:1499
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:858
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
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 isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
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...
ASTContext & getASTContext() const
Definition: Sema.h:527
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)
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:645
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....
ForRangeStatus
Definition: Sema.h:8356
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
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...
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AllowedExplicit
Definition: Sema.h:7947
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:775
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
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:9267
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
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...
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...
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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,...
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.
Definition: SemaExpr.cpp:6651
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
const LangOptions & LangOpts
Definition: Sema.h:856
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.
Definition: SemaExpr.cpp:6919
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
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)
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.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
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.
Definition: SemaExpr.cpp:10019
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.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
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...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:651
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3432
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11732
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
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:996
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8535
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.
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6091
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6130
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6109
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6093
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6126
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20258
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21227
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:10484
AssignmentAction
Definition: Sema.h:5196
@ AA_Converting
Definition: Sema.h:5200
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 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...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5714
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7794
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7840
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
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:11707
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3334
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,...
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:8026
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8031
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:8032
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:8030
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:8029
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.
OverloadKind
Definition: Sema.h:7923
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 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...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:861
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2414
DiagnosticsEngine & Diags
Definition: Sema.h:860
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
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...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21454
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
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.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:10647
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, 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...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6733
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:267
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:357
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:355
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:327
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
QualType getFromType() const
Definition: Overload.h:370
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:332
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:309
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:294
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:354
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:304
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:337
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:288
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:299
ImplicitConversionKind Element
Element - Between the second and third conversion a vector or matrix element conversion may occur.
Definition: Overload.h:284
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
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:347
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition: Overload.h:319
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:323
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:314
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...
void setAllToTypes(QualType T)
Definition: Overload.h:364
QualType getToType(unsigned Idx) const
Definition: Overload.h:374
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
StringRef getString() const
Definition: Expr.h:1850
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:634
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:687
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:672
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
Represents a template argument.
Definition: TemplateBase.h:61
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.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
Definition: TemplateName.h:219
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.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6085
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3415
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2396
bool isBlockPointerType() const
Definition: Type.h:7616
bool isVoidType() const
Definition: Type.h:7901
bool isBooleanType() const
Definition: Type.h:8029
bool isObjCBuiltinType() const
Definition: Type.h:7791
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
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:1887
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
bool isIncompleteArrayType() const
Definition: Type.h:7682
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isFloat16Type() const
Definition: Type.h:7910
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:666
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool isRValueReferenceType() const
Definition: Type.h:7628
bool isConstantArrayType() const
Definition: Type.h:7678
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8056
bool isArrayType() const
Definition: Type.h:7674
bool isCharType() const
Definition: Type.cpp:2077
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:7966
bool isArithmeticType() const
Definition: Type.cpp:2269
bool isPointerType() const
Definition: Type.h:7608
bool isArrayParameterType() const
Definition: Type.h:7690
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7941
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isEnumeralType() const
Definition: Type.h:7706
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
bool isObjCQualifiedIdType() const
Definition: Type.h:7761
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8016
bool isExtVectorType() const
Definition: Type.h:7718
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2113
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7748
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2657
bool isLValueReferenceType() const
Definition: Type.h:7624
bool isBitIntType() const
Definition: Type.h:7836
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2326
bool isAnyComplexType() const
Definition: Type.h:7710
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7954
bool isHalfType() const
Definition: Type.h:7905
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7883
bool isQueueT() const
Definition: Type.h:7817
bool isMemberPointerType() const
Definition: Type.h:7656
bool isObjCIdType() const
Definition: Type.h:7773
bool isMatrixType() const
Definition: Type.h:7728
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2401
bool isEventT() const
Definition: Type.h:7809
bool isBFloat16Type() const
Definition: Type.h:7922
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool isVectorType() const
Definition: Type.h:7714
bool isObjCClassType() const
Definition: Type.h:7779
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
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:2184
bool isAnyPointerType() const
Definition: Type.h:7612
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isSamplerT() const
Definition: Type.h:7805
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1429
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4838
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1405
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3173
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:3249
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3241
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3912
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4020
QualType getBaseType() const
Definition: ExprCXX.h:3994
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4004
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:3985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4030
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4024
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
unsigned size() const
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
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:637
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:900
QualType getType() const
Definition: Decl.h:717
Represents a GCC generic vector type.
Definition: Type.h:3965
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...
Definition: AttrIterator.h:33
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:60
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:217
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
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:131
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:774
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:802
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:811
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:794
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:798
@ 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:839
@ ovl_fail_too_few_arguments
Definition: Overload.h:776
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:818
@ ovl_fail_too_many_arguments
Definition: Overload.h:775
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:826
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:835
@ ovl_fail_bad_conversion
Definition: Overload.h:777
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:807
@ ovl_fail_bad_deduction
Definition: Overload.h:778
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:822
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:831
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:815
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:783
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:212
@ ICR_Conversion
Conversion.
Definition: Overload.h:220
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:229
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:232
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:223
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:226
@ ICR_Promotion
Promotion.
Definition: Overload.h:217
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:214
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:236
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:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
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
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
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_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:202
@ 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:205
@ 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_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
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
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:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:431
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:243
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:373
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1241
@ None
The alignment was not explicit in code.
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.
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:443
ConversionSet::const_iterator const_iterator
Definition: Overload.h:479
ConversionSet & conversions()
Definition: Overload.h:462
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:470
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:445
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:528
QualType getFromType() const
Definition: Overload.h:527
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
std::optional< unsigned > getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, 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.
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.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
Extra information about a function prototype.
Definition: Type.h:4731
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4739
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1006
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition: Overload.h:1019
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1055
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1028
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1045
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:848
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:903
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:945
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:933
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:891
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:862
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:900
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:858
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:853
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:877
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:907
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:874
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:924
unsigned getNumParams() const
Definition: Overload.h:958
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:915
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:911
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:871
DeductionFailureInfo DeductionFailure
Definition: Overload.h:918
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:886
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:866
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:929
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9804
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:9892
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9924
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8156
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6379
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition: Overload.h:398
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:410
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:432
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:423
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:418
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:437
void dump() const
dump - Print this user-defined conversion sequence to standard error.