clang 20.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaCUDA.h"
34#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include <algorithm>
44#include <cassert>
45#include <cstddef>
46#include <cstdlib>
47#include <optional>
48
49using namespace clang;
50using namespace sema;
51
53
55 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
56 return P->hasAttr<PassObjectSizeAttr>();
57 });
58}
59
60/// A convenience routine for creating a decayed reference to a function.
62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
65 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
66 return ExprError();
67 // If FoundDecl is different from Fn (such as if one is a template
68 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // called on both.
70 // FIXME: This would be more comprehensively addressed by modifying
71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 // being used.
73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
74 return ExprError();
75 DeclRefExpr *DRE = new (S.Context)
76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
77 if (HadMultipleCandidates)
78 DRE->setHadMultipleCandidates(true);
79
81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 DRE->setType(Fn->getType());
85 }
86 }
87 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
88 CK_FunctionToPointerDecay);
89}
90
91static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
92 bool InOverloadResolution,
94 bool CStyle,
95 bool AllowObjCWritebackConversion);
96
98 QualType &ToType,
99 bool InOverloadResolution,
101 bool CStyle);
103IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 OverloadCandidateSet& Conversions,
106 AllowedExplicit AllowExplicit,
107 bool AllowObjCConversionOnExplicit);
108
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
113
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
123
124/// GetConversionRank - Retrieve the implicit conversion rank
125/// corresponding to the given implicit conversion kind.
127 static const ImplicitConversionRank Rank[] = {
154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
173 ImplicitConversionKind Dimension) {
175 if (Rank == ICR_HLSL_Scalar_Widening) {
176 if (Base == ICR_Promotion)
178 if (Base == ICR_Conversion)
180 }
181 if (Rank == ICR_HLSL_Dimension_Reduction) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 return Rank;
188}
189
190/// GetImplicitConversionName - Return the name of this kind of
191/// implicit conversion.
193 static const char *const Name[] = {
194 "No conversion",
195 "Lvalue-to-rvalue",
196 "Array-to-pointer",
197 "Function-to-pointer",
198 "Function pointer conversion",
199 "Qualification",
200 "Integral promotion",
201 "Floating point promotion",
202 "Complex promotion",
203 "Integral conversion",
204 "Floating conversion",
205 "Complex conversion",
206 "Floating-integral conversion",
207 "Pointer conversion",
208 "Pointer-to-member conversion",
209 "Boolean conversion",
210 "Compatible-types conversion",
211 "Derived-to-base conversion",
212 "Vector conversion",
213 "SVE Vector conversion",
214 "RVV Vector conversion",
215 "Vector splat",
216 "Complex-real conversion",
217 "Block Pointer conversion",
218 "Transparent Union Conversion",
219 "Writeback conversion",
220 "OpenCL Zero Event Conversion",
221 "OpenCL Zero Queue Conversion",
222 "C specific type conversion",
223 "Incompatible pointer conversion",
224 "Fixed point conversion",
225 "HLSL vector truncation",
226 "Non-decaying array conversion",
227 "HLSL vector splat",
228 };
229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
230 return Name[Kind];
231}
232
233/// StandardConversionSequence - Set the standard conversion
234/// sequence to the identity conversion.
242 ReferenceBinding = false;
243 DirectBinding = false;
244 IsLvalueReference = true;
245 BindsToFunctionLvalue = false;
246 BindsToRvalue = false;
249 CopyConstructor = nullptr;
250}
251
252/// getRank - Retrieve the rank of this standard conversion sequence
253/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
254/// implicit conversions.
257 if (GetConversionRank(First) > Rank)
258 Rank = GetConversionRank(First);
259 if (GetConversionRank(Second) > Rank)
261 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
263 if (GetConversionRank(Third) > Rank)
264 Rank = GetConversionRank(Third);
265 return Rank;
266}
267
268/// isPointerConversionToBool - Determines whether this conversion is
269/// a conversion of a pointer or pointer-to-member to bool. This is
270/// used as part of the ranking of standard conversion sequences
271/// (C++ 13.3.3.2p4).
273 // Note that FromType has not necessarily been transformed by the
274 // array-to-pointer or function-to-pointer implicit conversions, so
275 // check for their presence as well as checking whether FromType is
276 // a pointer.
277 if (getToType(1)->isBooleanType() &&
278 (getFromType()->isPointerType() ||
279 getFromType()->isMemberPointerType() ||
280 getFromType()->isObjCObjectPointerType() ||
281 getFromType()->isBlockPointerType() ||
283 return true;
284
285 return false;
286}
287
288/// isPointerConversionToVoidPointer - Determines whether this
289/// conversion is a conversion of a pointer to a void pointer. This is
290/// used as part of the ranking of standard conversion sequences (C++
291/// 13.3.3.2p4).
292bool
295 QualType FromType = getFromType();
296 QualType ToType = getToType(1);
297
298 // Note that FromType has not necessarily been transformed by the
299 // array-to-pointer implicit conversion, so check for its presence
300 // and redo the conversion to get a pointer.
302 FromType = Context.getArrayDecayedType(FromType);
303
304 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
305 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
306 return ToPtrType->getPointeeType()->isVoidType();
307
308 return false;
309}
310
311/// Skip any implicit casts which could be either part of a narrowing conversion
312/// or after one in an implicit conversion.
314 const Expr *Converted) {
315 // We can have cleanups wrapping the converted expression; these need to be
316 // preserved so that destructors run if necessary.
317 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
318 Expr *Inner =
319 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
320 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
321 EWC->getObjects());
322 }
323
324 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
325 switch (ICE->getCastKind()) {
326 case CK_NoOp:
327 case CK_IntegralCast:
328 case CK_IntegralToBoolean:
329 case CK_IntegralToFloating:
330 case CK_BooleanToSignedIntegral:
331 case CK_FloatingToIntegral:
332 case CK_FloatingToBoolean:
333 case CK_FloatingCast:
334 Converted = ICE->getSubExpr();
335 continue;
336
337 default:
338 return Converted;
339 }
340 }
341
342 return Converted;
343}
344
345/// Check if this standard conversion sequence represents a narrowing
346/// conversion, according to C++11 [dcl.init.list]p7.
347///
348/// \param Ctx The AST context.
349/// \param Converted The result of applying this standard conversion sequence.
350/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
351/// value of the expression prior to the narrowing conversion.
352/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
353/// type of the expression prior to the narrowing conversion.
354/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
355/// from floating point types to integral types should be ignored.
357 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
358 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
359 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
360 "narrowing check outside C++");
361
362 // C++11 [dcl.init.list]p7:
363 // A narrowing conversion is an implicit conversion ...
364 QualType FromType = getToType(0);
365 QualType ToType = getToType(1);
366
367 // A conversion to an enumeration type is narrowing if the conversion to
368 // the underlying type is narrowing. This only arises for expressions of
369 // the form 'Enum{init}'.
370 if (auto *ET = ToType->getAs<EnumType>())
371 ToType = ET->getDecl()->getIntegerType();
372
373 switch (Second) {
374 // 'bool' is an integral type; dispatch to the right place to handle it.
376 if (FromType->isRealFloatingType())
377 goto FloatingIntegralConversion;
379 goto IntegralConversion;
380 // -- from a pointer type or pointer-to-member type to bool, or
381 return NK_Type_Narrowing;
382
383 // -- from a floating-point type to an integer type, or
384 //
385 // -- from an integer type or unscoped enumeration type to a floating-point
386 // type, except where the source is a constant expression and the actual
387 // value after conversion will fit into the target type and will produce
388 // the original value when converted back to the original type, or
390 FloatingIntegralConversion:
391 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
392 return NK_Type_Narrowing;
393 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
394 ToType->isRealFloatingType()) {
395 if (IgnoreFloatToIntegralConversion)
396 return NK_Not_Narrowing;
397 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
398 assert(Initializer && "Unknown conversion expression");
399
400 // If it's value-dependent, we can't tell whether it's narrowing.
401 if (Initializer->isValueDependent())
403
404 if (std::optional<llvm::APSInt> IntConstantValue =
405 Initializer->getIntegerConstantExpr(Ctx)) {
406 // Convert the integer to the floating type.
407 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
408 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
409 llvm::APFloat::rmNearestTiesToEven);
410 // And back.
411 llvm::APSInt ConvertedValue = *IntConstantValue;
412 bool ignored;
413 Result.convertToInteger(ConvertedValue,
414 llvm::APFloat::rmTowardZero, &ignored);
415 // If the resulting value is different, this was a narrowing conversion.
416 if (*IntConstantValue != ConvertedValue) {
417 ConstantValue = APValue(*IntConstantValue);
418 ConstantType = Initializer->getType();
420 }
421 } else {
422 // Variables are always narrowings.
424 }
425 }
426 return NK_Not_Narrowing;
427
428 // -- from long double to double or float, or from double to float, except
429 // where the source is a constant expression and the actual value after
430 // conversion is within the range of values that can be represented (even
431 // if it cannot be represented exactly), or
433 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
434 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
435 // FromType is larger than ToType.
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
437
438 // If it's value-dependent, we can't tell whether it's narrowing.
439 if (Initializer->isValueDependent())
441
443 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
444 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
445 // Constant!
446 if (Ctx.getLangOpts().C23)
447 ConstantValue = R.Val;
448 assert(ConstantValue.isFloat());
449 llvm::APFloat FloatVal = ConstantValue.getFloat();
450 // Convert the source value into the target type.
451 bool ignored;
452 llvm::APFloat Converted = FloatVal;
453 llvm::APFloat::opStatus ConvertStatus =
454 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
455 llvm::APFloat::rmNearestTiesToEven, &ignored);
456 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
457 llvm::APFloat::rmNearestTiesToEven, &ignored);
458 if (Ctx.getLangOpts().C23) {
459 if (FloatVal.isNaN() && Converted.isNaN() &&
460 !FloatVal.isSignaling() && !Converted.isSignaling()) {
461 // Quiet NaNs are considered the same value, regardless of
462 // payloads.
463 return NK_Not_Narrowing;
464 }
465 // For normal values, check exact equality.
466 if (!Converted.bitwiseIsEqual(FloatVal)) {
467 ConstantType = Initializer->getType();
469 }
470 } else {
471 // If there was no overflow, the source value is within the range of
472 // values that can be represented.
473 if (ConvertStatus & llvm::APFloat::opOverflow) {
474 ConstantType = Initializer->getType();
476 }
477 }
478 } else {
480 }
481 }
482 return NK_Not_Narrowing;
483
484 // -- from an integer type or unscoped enumeration type to an integer type
485 // that cannot represent all the values of the original type, except where
486 // (CWG2627) -- the source is a bit-field whose width w is less than that
487 // of its type (or, for an enumeration type, its underlying type) and the
488 // target type can represent all the values of a hypothetical extended
489 // integer type with width w and with the same signedness as the original
490 // type or
491 // -- the source is a constant expression and the actual value after
492 // conversion will fit into the target type and will produce the original
493 // value when converted back to the original type.
495 IntegralConversion: {
496 assert(FromType->isIntegralOrUnscopedEnumerationType());
497 assert(ToType->isIntegralOrUnscopedEnumerationType());
498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
499 unsigned FromWidth = Ctx.getIntWidth(FromType);
500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
501 const unsigned ToWidth = Ctx.getIntWidth(ToType);
502
503 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
504 bool ToSigned, unsigned ToWidth) {
505 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
506 !(FromSigned && !ToSigned);
507 };
508
509 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
510 return NK_Not_Narrowing;
511
512 // Not all values of FromType can be represented in ToType.
513 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
514
515 bool DependentBitField = false;
516 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
517 if (BitField->getBitWidth()->isValueDependent())
518 DependentBitField = true;
519 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(Ctx);
520 BitFieldWidth < FromWidth) {
521 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
522 return NK_Not_Narrowing;
523
524 // The initializer will be truncated to the bit-field width
525 FromWidth = BitFieldWidth;
526 }
527 }
528
529 // If it's value-dependent, we can't tell whether it's narrowing.
530 if (Initializer->isValueDependent())
532
533 std::optional<llvm::APSInt> OptInitializerValue =
534 Initializer->getIntegerConstantExpr(Ctx);
535 if (!OptInitializerValue) {
536 // If the bit-field width was dependent, it might end up being small
537 // enough to fit in the target type (unless the target type is unsigned
538 // and the source type is signed, in which case it will never fit)
539 if (DependentBitField && !(FromSigned && !ToSigned))
541
542 // Otherwise, such a conversion is always narrowing
544 }
545 llvm::APSInt &InitializerValue = *OptInitializerValue;
546 bool Narrowing = false;
547 if (FromWidth < ToWidth) {
548 // Negative -> unsigned is narrowing. Otherwise, more bits is never
549 // narrowing.
550 if (InitializerValue.isSigned() && InitializerValue.isNegative())
551 Narrowing = true;
552 } else {
553 // Add a bit to the InitializerValue so we don't have to worry about
554 // signed vs. unsigned comparisons.
555 InitializerValue =
556 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
557 // Convert the initializer to and from the target width and signed-ness.
558 llvm::APSInt ConvertedValue = InitializerValue;
559 ConvertedValue = ConvertedValue.trunc(ToWidth);
560 ConvertedValue.setIsSigned(ToSigned);
561 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
562 ConvertedValue.setIsSigned(InitializerValue.isSigned());
563 // If the result is different, this was a narrowing conversion.
564 if (ConvertedValue != InitializerValue)
565 Narrowing = true;
566 }
567 if (Narrowing) {
568 ConstantType = Initializer->getType();
569 ConstantValue = APValue(InitializerValue);
571 }
572
573 return NK_Not_Narrowing;
574 }
575 case ICK_Complex_Real:
576 if (FromType->isComplexType() && !ToType->isComplexType())
577 return NK_Type_Narrowing;
578 return NK_Not_Narrowing;
579
581 if (Ctx.getLangOpts().C23) {
582 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
584 if (Initializer->EvaluateAsRValue(R, Ctx)) {
585 ConstantValue = R.Val;
586 assert(ConstantValue.isFloat());
587 llvm::APFloat FloatVal = ConstantValue.getFloat();
588 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
589 // value, the unqualified versions of the type of the initializer and
590 // the corresponding real type of the object declared shall be
591 // compatible.
592 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
593 ConstantType = Initializer->getType();
595 }
596 }
597 }
598 return NK_Not_Narrowing;
599 default:
600 // Other kinds of conversions are not narrowings.
601 return NK_Not_Narrowing;
602 }
603}
604
605/// dump - Print this standard conversion sequence to standard
606/// error. Useful for debugging overloading issues.
607LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
608 raw_ostream &OS = llvm::errs();
609 bool PrintedSomething = false;
610 if (First != ICK_Identity) {
612 PrintedSomething = true;
613 }
614
615 if (Second != ICK_Identity) {
616 if (PrintedSomething) {
617 OS << " -> ";
618 }
620
621 if (CopyConstructor) {
622 OS << " (by copy constructor)";
623 } else if (DirectBinding) {
624 OS << " (direct reference binding)";
625 } else if (ReferenceBinding) {
626 OS << " (reference binding)";
627 }
628 PrintedSomething = true;
629 }
630
631 if (Third != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636 PrintedSomething = true;
637 }
638
639 if (!PrintedSomething) {
640 OS << "No conversions required";
641 }
642}
643
644/// dump - Print this user-defined conversion sequence to standard
645/// error. Useful for debugging overloading issues.
647 raw_ostream &OS = llvm::errs();
648 if (Before.First || Before.Second || Before.Third) {
649 Before.dump();
650 OS << " -> ";
651 }
653 OS << '\'' << *ConversionFunction << '\'';
654 else
655 OS << "aggregate initialization";
656 if (After.First || After.Second || After.Third) {
657 OS << " -> ";
658 After.dump();
659 }
660}
661
662/// dump - Print this implicit conversion sequence to standard
663/// error. Useful for debugging overloading issues.
665 raw_ostream &OS = llvm::errs();
667 OS << "Worst list element conversion: ";
668 switch (ConversionKind) {
670 OS << "Standard conversion: ";
671 Standard.dump();
672 break;
674 OS << "User-defined conversion: ";
676 break;
678 OS << "Ellipsis conversion";
679 break;
681 OS << "Ambiguous conversion";
682 break;
683 case BadConversion:
684 OS << "Bad conversion";
685 break;
686 }
687
688 OS << "\n";
689}
690
692 new (&conversions()) ConversionSet();
693}
694
696 conversions().~ConversionSet();
697}
698
699void
704}
705
706namespace {
707 // Structure used by DeductionFailureInfo to store
708 // template argument information.
709 struct DFIArguments {
710 TemplateArgument FirstArg;
711 TemplateArgument SecondArg;
712 };
713 // Structure used by DeductionFailureInfo to store
714 // template parameter and template argument information.
715 struct DFIParamWithArguments : DFIArguments {
716 TemplateParameter Param;
717 };
718 // Structure used by DeductionFailureInfo to store template argument
719 // information and the index of the problematic call argument.
720 struct DFIDeducedMismatchArgs : DFIArguments {
721 TemplateArgumentList *TemplateArgs;
722 unsigned CallArgIndex;
723 };
724 // Structure used by DeductionFailureInfo to store information about
725 // unsatisfied constraints.
726 struct CNSInfo {
727 TemplateArgumentList *TemplateArgs;
728 ConstraintSatisfaction Satisfaction;
729 };
730}
731
732/// Convert from Sema's representation of template deduction information
733/// to the form used in overload-candidate information.
737 TemplateDeductionInfo &Info) {
739 Result.Result = static_cast<unsigned>(TDK);
740 Result.HasDiagnostic = false;
741 switch (TDK) {
748 Result.Data = nullptr;
749 break;
750
753 Result.Data = Info.Param.getOpaqueValue();
754 break;
755
758 // FIXME: Should allocate from normal heap so that we can free this later.
759 auto *Saved = new (Context) DFIDeducedMismatchArgs;
760 Saved->FirstArg = Info.FirstArg;
761 Saved->SecondArg = Info.SecondArg;
762 Saved->TemplateArgs = Info.takeSugared();
763 Saved->CallArgIndex = Info.CallArgIndex;
764 Result.Data = Saved;
765 break;
766 }
767
769 // FIXME: Should allocate from normal heap so that we can free this later.
770 DFIArguments *Saved = new (Context) DFIArguments;
771 Saved->FirstArg = Info.FirstArg;
772 Saved->SecondArg = Info.SecondArg;
773 Result.Data = Saved;
774 break;
775 }
776
778 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
781 // FIXME: Should allocate from normal heap so that we can free this later.
782 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
783 Saved->Param = Info.Param;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Result.Data = Saved;
787 break;
788 }
789
791 Result.Data = Info.takeSugared();
792 if (Info.hasSFINAEDiagnostic()) {
796 Result.HasDiagnostic = true;
797 }
798 break;
799
801 CNSInfo *Saved = new (Context) CNSInfo;
802 Saved->TemplateArgs = Info.takeSugared();
803 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
804 Result.Data = Saved;
805 break;
806 }
807
811 llvm_unreachable("not a deduction failure");
812 }
813
814 return Result;
815}
816
818 switch (static_cast<TemplateDeductionResult>(Result)) {
828 break;
829
836 // FIXME: Destroy the data?
837 Data = nullptr;
838 break;
839
841 // FIXME: Destroy the template argument list?
842 Data = nullptr;
844 Diag->~PartialDiagnosticAt();
845 HasDiagnostic = false;
846 }
847 break;
848
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
858 // Unhandled
861 break;
862 }
863}
864
866 if (HasDiagnostic)
867 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
868 return nullptr;
869}
870
872 switch (static_cast<TemplateDeductionResult>(Result)) {
885 return TemplateParameter();
886
889 return TemplateParameter::getFromOpaqueValue(Data);
890
894 return static_cast<DFIParamWithArguments*>(Data)->Param;
895
896 // Unhandled
899 break;
900 }
901
902 return TemplateParameter();
903}
904
906 switch (static_cast<TemplateDeductionResult>(Result)) {
920 return nullptr;
921
924 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
925
927 return static_cast<TemplateArgumentList*>(Data);
928
930 return static_cast<CNSInfo*>(Data)->TemplateArgs;
931
932 // Unhandled
935 break;
936 }
937
938 return nullptr;
939}
940
942 switch (static_cast<TemplateDeductionResult>(Result)) {
954 return nullptr;
955
962 return &static_cast<DFIArguments*>(Data)->FirstArg;
963
964 // Unhandled
967 break;
968 }
969
970 return nullptr;
971}
972
974 switch (static_cast<TemplateDeductionResult>(Result)) {
987 return nullptr;
988
994 return &static_cast<DFIArguments*>(Data)->SecondArg;
995
996 // Unhandled
999 break;
1000 }
1001
1002 return nullptr;
1003}
1004
1005std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1006 switch (static_cast<TemplateDeductionResult>(Result)) {
1009 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1010
1011 default:
1012 return std::nullopt;
1013 }
1014}
1015
1017 const FunctionDecl *Y) {
1018 if (!X || !Y)
1019 return false;
1020 if (X->getNumParams() != Y->getNumParams())
1021 return false;
1022 // FIXME: when do rewritten comparison operators
1023 // with explicit object parameters correspond?
1024 // https://cplusplus.github.io/CWG/issues/2797.html
1025 for (unsigned I = 0; I < X->getNumParams(); ++I)
1026 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1027 Y->getParamDecl(I)->getType()))
1028 return false;
1029 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1030 auto *FTY = Y->getDescribedFunctionTemplate();
1031 if (!FTY)
1032 return false;
1033 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1034 FTY->getTemplateParameters()))
1035 return false;
1036 }
1037 return true;
1038}
1039
1041 Expr *FirstOperand, FunctionDecl *EqFD) {
1042 assert(EqFD->getOverloadedOperator() ==
1043 OverloadedOperatorKind::OO_EqualEqual);
1044 // C++2a [over.match.oper]p4:
1045 // A non-template function or function template F named operator== is a
1046 // rewrite target with first operand o unless a search for the name operator!=
1047 // in the scope S from the instantiation context of the operator expression
1048 // finds a function or function template that would correspond
1049 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1050 // scope of the class type of o if F is a class member, and the namespace
1051 // scope of which F is a member otherwise. A function template specialization
1052 // named operator== is a rewrite target if its function template is a rewrite
1053 // target.
1055 OverloadedOperatorKind::OO_ExclaimEqual);
1056 if (isa<CXXMethodDecl>(EqFD)) {
1057 // If F is a class member, search scope is class type of first operand.
1058 QualType RHS = FirstOperand->getType();
1059 auto *RHSRec = RHS->getAs<RecordType>();
1060 if (!RHSRec)
1061 return true;
1062 LookupResult Members(S, NotEqOp, OpLoc,
1064 S.LookupQualifiedName(Members, RHSRec->getDecl());
1065 Members.suppressAccessDiagnostics();
1066 for (NamedDecl *Op : Members)
1067 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1068 return false;
1069 return true;
1070 }
1071 // Otherwise the search scope is the namespace scope of which F is a member.
1072 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1073 auto *NotEqFD = Op->getAsFunction();
1074 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1075 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1076 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1078 cast<Decl>(Op->getLexicalDeclContext())))
1079 return false;
1080 }
1081 return true;
1082}
1083
1087 return false;
1088 return Op == OO_EqualEqual || Op == OO_Spaceship;
1089}
1090
1092 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1093 auto Op = FD->getOverloadedOperator();
1094 if (!allowsReversed(Op))
1095 return false;
1096 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1097 assert(OriginalArgs.size() == 2);
1099 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1100 return false;
1101 }
1102 // Don't bother adding a reversed candidate that can never be a better
1103 // match than the non-reversed version.
1104 return FD->getNumNonObjectParams() != 2 ||
1106 FD->getParamDecl(1)->getType()) ||
1107 FD->hasAttr<EnableIfAttr>();
1108}
1109
1110void OverloadCandidateSet::destroyCandidates() {
1111 for (iterator i = begin(), e = end(); i != e; ++i) {
1112 for (auto &C : i->Conversions)
1113 C.~ImplicitConversionSequence();
1114 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1115 i->DeductionFailure.Destroy();
1116 }
1117}
1118
1120 destroyCandidates();
1121 SlabAllocator.Reset();
1122 NumInlineBytesUsed = 0;
1123 Candidates.clear();
1124 Functions.clear();
1125 Kind = CSK;
1126}
1127
1128namespace {
1129 class UnbridgedCastsSet {
1130 struct Entry {
1131 Expr **Addr;
1132 Expr *Saved;
1133 };
1134 SmallVector<Entry, 2> Entries;
1135
1136 public:
1137 void save(Sema &S, Expr *&E) {
1138 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1139 Entry entry = { &E, E };
1140 Entries.push_back(entry);
1142 }
1143
1144 void restore() {
1146 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1147 *i->Addr = i->Saved;
1148 }
1149 };
1150}
1151
1152/// checkPlaceholderForOverload - Do any interesting placeholder-like
1153/// preprocessing on the given expression.
1154///
1155/// \param unbridgedCasts a collection to which to add unbridged casts;
1156/// without this, they will be immediately diagnosed as errors
1157///
1158/// Return true on unrecoverable error.
1159static bool
1161 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1162 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1163 // We can't handle overloaded expressions here because overload
1164 // resolution might reasonably tweak them.
1165 if (placeholder->getKind() == BuiltinType::Overload) return false;
1166
1167 // If the context potentially accepts unbridged ARC casts, strip
1168 // the unbridged cast and add it to the collection for later restoration.
1169 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1170 unbridgedCasts) {
1171 unbridgedCasts->save(S, E);
1172 return false;
1173 }
1174
1175 // Go ahead and check everything else.
1176 ExprResult result = S.CheckPlaceholderExpr(E);
1177 if (result.isInvalid())
1178 return true;
1179
1180 E = result.get();
1181 return false;
1182 }
1183
1184 // Nothing to do.
1185 return false;
1186}
1187
1188/// checkArgPlaceholdersForOverload - Check a set of call operands for
1189/// placeholders.
1191 UnbridgedCastsSet &unbridged) {
1192 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1193 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1194 return true;
1195
1196 return false;
1197}
1198
1201 NamedDecl *&Match, bool NewIsUsingDecl) {
1202 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1203 I != E; ++I) {
1204 NamedDecl *OldD = *I;
1205
1206 bool OldIsUsingDecl = false;
1207 if (isa<UsingShadowDecl>(OldD)) {
1208 OldIsUsingDecl = true;
1209
1210 // We can always introduce two using declarations into the same
1211 // context, even if they have identical signatures.
1212 if (NewIsUsingDecl) continue;
1213
1214 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1215 }
1216
1217 // A using-declaration does not conflict with another declaration
1218 // if one of them is hidden.
1219 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1220 continue;
1221
1222 // If either declaration was introduced by a using declaration,
1223 // we'll need to use slightly different rules for matching.
1224 // Essentially, these rules are the normal rules, except that
1225 // function templates hide function templates with different
1226 // return types or template parameter lists.
1227 bool UseMemberUsingDeclRules =
1228 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1229 !New->getFriendObjectKind();
1230
1231 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1232 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1233 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1234 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1235 continue;
1236 }
1237
1238 if (!isa<FunctionTemplateDecl>(OldD) &&
1239 !shouldLinkPossiblyHiddenDecl(*I, New))
1240 continue;
1241
1242 Match = *I;
1243 return Ovl_Match;
1244 }
1245
1246 // Builtins that have custom typechecking or have a reference should
1247 // not be overloadable or redeclarable.
1248 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1249 Match = *I;
1250 return Ovl_NonFunction;
1251 }
1252 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1253 // We can overload with these, which can show up when doing
1254 // redeclaration checks for UsingDecls.
1255 assert(Old.getLookupKind() == LookupUsingDeclName);
1256 } else if (isa<TagDecl>(OldD)) {
1257 // We can always overload with tags by hiding them.
1258 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1259 // Optimistically assume that an unresolved using decl will
1260 // overload; if it doesn't, we'll have to diagnose during
1261 // template instantiation.
1262 //
1263 // Exception: if the scope is dependent and this is not a class
1264 // member, the using declaration can only introduce an enumerator.
1265 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1266 Match = *I;
1267 return Ovl_NonFunction;
1268 }
1269 } else {
1270 // (C++ 13p1):
1271 // Only function declarations can be overloaded; object and type
1272 // declarations cannot be overloaded.
1273 Match = *I;
1274 return Ovl_NonFunction;
1275 }
1276 }
1277
1278 // C++ [temp.friend]p1:
1279 // For a friend function declaration that is not a template declaration:
1280 // -- if the name of the friend is a qualified or unqualified template-id,
1281 // [...], otherwise
1282 // -- if the name of the friend is a qualified-id and a matching
1283 // non-template function is found in the specified class or namespace,
1284 // the friend declaration refers to that function, otherwise,
1285 // -- if the name of the friend is a qualified-id and a matching function
1286 // template is found in the specified class or namespace, the friend
1287 // declaration refers to the deduced specialization of that function
1288 // template, otherwise
1289 // -- the name shall be an unqualified-id [...]
1290 // If we get here for a qualified friend declaration, we've just reached the
1291 // third bullet. If the type of the friend is dependent, skip this lookup
1292 // until instantiation.
1293 if (New->getFriendObjectKind() && New->getQualifier() &&
1296 !New->getType()->isDependentType()) {
1297 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1298 TemplateSpecResult.addAllDecls(Old);
1299 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1300 /*QualifiedFriend*/true)) {
1301 New->setInvalidDecl();
1302 return Ovl_Overload;
1303 }
1304
1305 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1306 return Ovl_Match;
1307 }
1308
1309 return Ovl_Overload;
1310}
1311
1312static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1313 FunctionDecl *Old,
1314 bool UseMemberUsingDeclRules,
1315 bool ConsiderCudaAttrs,
1316 bool UseOverrideRules = false) {
1317 // C++ [basic.start.main]p2: This function shall not be overloaded.
1318 if (New->isMain())
1319 return false;
1320
1321 // MSVCRT user defined entry points cannot be overloaded.
1322 if (New->isMSVCRTEntryPoint())
1323 return false;
1324
1325 NamedDecl *OldDecl = Old;
1326 NamedDecl *NewDecl = New;
1329
1330 // C++ [temp.fct]p2:
1331 // A function template can be overloaded with other function templates
1332 // and with normal (non-template) functions.
1333 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1334 return true;
1335
1336 // Is the function New an overload of the function Old?
1337 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1338 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1339
1340 // Compare the signatures (C++ 1.3.10) of the two functions to
1341 // determine whether they are overloads. If we find any mismatch
1342 // in the signature, they are overloads.
1343
1344 // If either of these functions is a K&R-style function (no
1345 // prototype), then we consider them to have matching signatures.
1346 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1347 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1348 return false;
1349
1350 const auto *OldType = cast<FunctionProtoType>(OldQType);
1351 const auto *NewType = cast<FunctionProtoType>(NewQType);
1352
1353 // The signature of a function includes the types of its
1354 // parameters (C++ 1.3.10), which includes the presence or absence
1355 // of the ellipsis; see C++ DR 357).
1356 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1357 return true;
1358
1359 // For member-like friends, the enclosing class is part of the signature.
1360 if ((New->isMemberLikeConstrainedFriend() ||
1363 return true;
1364
1365 // Compare the parameter lists.
1366 // This can only be done once we have establish that friend functions
1367 // inhabit the same context, otherwise we might tried to instantiate
1368 // references to non-instantiated entities during constraint substitution.
1369 // GH78101.
1370 if (NewTemplate) {
1371 OldDecl = OldTemplate;
1372 NewDecl = NewTemplate;
1373 // C++ [temp.over.link]p4:
1374 // The signature of a function template consists of its function
1375 // signature, its return type and its template parameter list. The names
1376 // of the template parameters are significant only for establishing the
1377 // relationship between the template parameters and the rest of the
1378 // signature.
1379 //
1380 // We check the return type and template parameter lists for function
1381 // templates first; the remaining checks follow.
1382 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1383 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1384 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1385 bool SameReturnType = SemaRef.Context.hasSameType(
1387 // FIXME(GH58571): Match template parameter list even for non-constrained
1388 // template heads. This currently ensures that the code prior to C++20 is
1389 // not newly broken.
1390 bool ConstraintsInTemplateHead =
1393 // C++ [namespace.udecl]p11:
1394 // The set of declarations named by a using-declarator that inhabits a
1395 // class C does not include member functions and member function
1396 // templates of a base class that "correspond" to (and thus would
1397 // conflict with) a declaration of a function or function template in
1398 // C.
1399 // Comparing return types is not required for the "correspond" check to
1400 // decide whether a member introduced by a shadow declaration is hidden.
1401 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1402 !SameTemplateParameterList)
1403 return true;
1404 if (!UseMemberUsingDeclRules &&
1405 (!SameTemplateParameterList || !SameReturnType))
1406 return true;
1407 }
1408
1409 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1410 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1411
1412 int OldParamsOffset = 0;
1413 int NewParamsOffset = 0;
1414
1415 // When determining if a method is an overload from a base class, act as if
1416 // the implicit object parameter are of the same type.
1417
1418 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1420 auto ThisType = M->getFunctionObjectParameterReferenceType();
1421 if (ThisType.isConstQualified())
1422 Q.removeConst();
1423 return Q;
1424 }
1425
1426 // We do not allow overloading based off of '__restrict'.
1427 Q.removeRestrict();
1428
1429 // We may not have applied the implicit const for a constexpr member
1430 // function yet (because we haven't yet resolved whether this is a static
1431 // or non-static member function). Add it now, on the assumption that this
1432 // is a redeclaration of OldMethod.
1433 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1434 (M->isConstexpr() || M->isConsteval()) &&
1435 !isa<CXXConstructorDecl>(NewMethod))
1436 Q.addConst();
1437 return Q;
1438 };
1439
1440 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1441 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1442 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1443
1444 if (OldMethod->isExplicitObjectMemberFunction()) {
1445 BS.Quals.removeVolatile();
1446 DS.Quals.removeVolatile();
1447 }
1448
1449 return BS.Quals == DS.Quals;
1450 };
1451
1452 auto CompareType = [&](QualType Base, QualType D) {
1453 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1454 auto DS = D.getNonReferenceType().getCanonicalType().split();
1455
1456 if (!AreQualifiersEqual(BS, DS))
1457 return false;
1458
1459 if (OldMethod->isImplicitObjectMemberFunction() &&
1460 OldMethod->getParent() != NewMethod->getParent()) {
1461 QualType ParentType =
1462 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1463 .getCanonicalType();
1464 if (ParentType.getTypePtr() != BS.Ty)
1465 return false;
1466 BS.Ty = DS.Ty;
1467 }
1468
1469 // FIXME: should we ignore some type attributes here?
1470 if (BS.Ty != DS.Ty)
1471 return false;
1472
1473 if (Base->isLValueReferenceType())
1474 return D->isLValueReferenceType();
1475 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1476 };
1477
1478 // If the function is a class member, its signature includes the
1479 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1480 auto DiagnoseInconsistentRefQualifiers = [&]() {
1481 if (SemaRef.LangOpts.CPlusPlus23)
1482 return false;
1483 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1484 return false;
1485 if (OldMethod->isExplicitObjectMemberFunction() ||
1486 NewMethod->isExplicitObjectMemberFunction())
1487 return false;
1488 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1489 NewMethod->getRefQualifier() == RQ_None)) {
1490 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1491 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1492 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1493 return true;
1494 }
1495 return false;
1496 };
1497
1498 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1499 OldParamsOffset++;
1500 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1501 NewParamsOffset++;
1502
1503 if (OldType->getNumParams() - OldParamsOffset !=
1504 NewType->getNumParams() - NewParamsOffset ||
1506 {OldType->param_type_begin() + OldParamsOffset,
1507 OldType->param_type_end()},
1508 {NewType->param_type_begin() + NewParamsOffset,
1509 NewType->param_type_end()},
1510 nullptr)) {
1511 return true;
1512 }
1513
1514 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1515 !NewMethod->isStatic()) {
1516 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1517 const CXXMethodDecl *New) {
1518 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1519 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1520
1521 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1522 return F->getRefQualifier() == RQ_None &&
1523 !F->isExplicitObjectMemberFunction();
1524 };
1525
1526 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1527 CompareType(OldObjectType.getNonReferenceType(),
1528 NewObjectType.getNonReferenceType()))
1529 return true;
1530 return CompareType(OldObjectType, NewObjectType);
1531 }(OldMethod, NewMethod);
1532
1533 if (!HaveCorrespondingObjectParameters) {
1534 if (DiagnoseInconsistentRefQualifiers())
1535 return true;
1536 // CWG2554
1537 // and, if at least one is an explicit object member function, ignoring
1538 // object parameters
1539 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1540 !OldMethod->isExplicitObjectMemberFunction()))
1541 return true;
1542 }
1543 }
1544
1545 if (!UseOverrideRules &&
1547 Expr *NewRC = New->getTrailingRequiresClause(),
1548 *OldRC = Old->getTrailingRequiresClause();
1549 if ((NewRC != nullptr) != (OldRC != nullptr))
1550 return true;
1551 if (NewRC &&
1552 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1553 return true;
1554 }
1555
1556 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1557 NewMethod->isImplicitObjectMemberFunction()) {
1558 if (DiagnoseInconsistentRefQualifiers())
1559 return true;
1560 }
1561
1562 // Though pass_object_size is placed on parameters and takes an argument, we
1563 // consider it to be a function-level modifier for the sake of function
1564 // identity. Either the function has one or more parameters with
1565 // pass_object_size or it doesn't.
1568 return true;
1569
1570 // enable_if attributes are an order-sensitive part of the signature.
1572 NewI = New->specific_attr_begin<EnableIfAttr>(),
1573 NewE = New->specific_attr_end<EnableIfAttr>(),
1574 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1575 OldE = Old->specific_attr_end<EnableIfAttr>();
1576 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1577 if (NewI == NewE || OldI == OldE)
1578 return true;
1579 llvm::FoldingSetNodeID NewID, OldID;
1580 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1581 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1582 if (NewID != OldID)
1583 return true;
1584 }
1585
1586 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1587 // Don't allow overloading of destructors. (In theory we could, but it
1588 // would be a giant change to clang.)
1589 if (!isa<CXXDestructorDecl>(New)) {
1590 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1591 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1592 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1593 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1594 "Unexpected invalid target.");
1595
1596 // Allow overloading of functions with same signature and different CUDA
1597 // target attributes.
1598 if (NewTarget != OldTarget)
1599 return true;
1600 }
1601 }
1602 }
1603
1604 // The signatures match; this is not an overload.
1605 return false;
1606}
1607
1609 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1610 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1611 ConsiderCudaAttrs);
1612}
1613
1615 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1616 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1617 /*UseMemberUsingDeclRules=*/false,
1618 /*ConsiderCudaAttrs=*/true,
1619 /*UseOverrideRules=*/true);
1620}
1621
1622/// Tries a user-defined conversion from From to ToType.
1623///
1624/// Produces an implicit conversion sequence for when a standard conversion
1625/// is not an option. See TryImplicitConversion for more information.
1628 bool SuppressUserConversions,
1629 AllowedExplicit AllowExplicit,
1630 bool InOverloadResolution,
1631 bool CStyle,
1632 bool AllowObjCWritebackConversion,
1633 bool AllowObjCConversionOnExplicit) {
1635
1636 if (SuppressUserConversions) {
1637 // We're not in the case above, so there is no conversion that
1638 // we can perform.
1640 return ICS;
1641 }
1642
1643 // Attempt user-defined conversion.
1644 OverloadCandidateSet Conversions(From->getExprLoc(),
1646 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1647 Conversions, AllowExplicit,
1648 AllowObjCConversionOnExplicit)) {
1649 case OR_Success:
1650 case OR_Deleted:
1651 ICS.setUserDefined();
1652 // C++ [over.ics.user]p4:
1653 // A conversion of an expression of class type to the same class
1654 // type is given Exact Match rank, and a conversion of an
1655 // expression of class type to a base class of that type is
1656 // given Conversion rank, in spite of the fact that a copy
1657 // constructor (i.e., a user-defined conversion function) is
1658 // called for those cases.
1659 if (CXXConstructorDecl *Constructor
1660 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1661 QualType FromType;
1662 SourceLocation FromLoc;
1663 // C++11 [over.ics.list]p6, per DR2137:
1664 // C++17 [over.ics.list]p6:
1665 // If C is not an initializer-list constructor and the initializer list
1666 // has a single element of type cv U, where U is X or a class derived
1667 // from X, the implicit conversion sequence has Exact Match rank if U is
1668 // X, or Conversion rank if U is derived from X.
1669 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1670 InitList && InitList->getNumInits() == 1 &&
1671 !S.isInitListConstructor(Constructor)) {
1672 const Expr *SingleInit = InitList->getInit(0);
1673 FromType = SingleInit->getType();
1674 FromLoc = SingleInit->getBeginLoc();
1675 } else {
1676 FromType = From->getType();
1677 FromLoc = From->getBeginLoc();
1678 }
1679 QualType FromCanon =
1681 QualType ToCanon
1683 if ((FromCanon == ToCanon ||
1684 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1685 // Turn this into a "standard" conversion sequence, so that it
1686 // gets ranked with standard conversion sequences.
1688 ICS.setStandard();
1690 ICS.Standard.setFromType(FromType);
1691 ICS.Standard.setAllToTypes(ToType);
1692 ICS.Standard.CopyConstructor = Constructor;
1694 if (ToCanon != FromCanon)
1696 }
1697 }
1698 break;
1699
1700 case OR_Ambiguous:
1701 ICS.setAmbiguous();
1702 ICS.Ambiguous.setFromType(From->getType());
1703 ICS.Ambiguous.setToType(ToType);
1704 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1705 Cand != Conversions.end(); ++Cand)
1706 if (Cand->Best)
1707 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1708 break;
1709
1710 // Fall through.
1713 break;
1714 }
1715
1716 return ICS;
1717}
1718
1719/// TryImplicitConversion - Attempt to perform an implicit conversion
1720/// from the given expression (Expr) to the given type (ToType). This
1721/// function returns an implicit conversion sequence that can be used
1722/// to perform the initialization. Given
1723///
1724/// void f(float f);
1725/// void g(int i) { f(i); }
1726///
1727/// this routine would produce an implicit conversion sequence to
1728/// describe the initialization of f from i, which will be a standard
1729/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1730/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1731//
1732/// Note that this routine only determines how the conversion can be
1733/// performed; it does not actually perform the conversion. As such,
1734/// it will not produce any diagnostics if no conversion is available,
1735/// but will instead return an implicit conversion sequence of kind
1736/// "BadConversion".
1737///
1738/// If @p SuppressUserConversions, then user-defined conversions are
1739/// not permitted.
1740/// If @p AllowExplicit, then explicit user-defined conversions are
1741/// permitted.
1742///
1743/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1744/// writeback conversion, which allows __autoreleasing id* parameters to
1745/// be initialized with __strong id* or __weak id* arguments.
1748 bool SuppressUserConversions,
1749 AllowedExplicit AllowExplicit,
1750 bool InOverloadResolution,
1751 bool CStyle,
1752 bool AllowObjCWritebackConversion,
1753 bool AllowObjCConversionOnExplicit) {
1755 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1756 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1757 ICS.setStandard();
1758 return ICS;
1759 }
1760
1761 if (!S.getLangOpts().CPlusPlus) {
1763 return ICS;
1764 }
1765
1766 // C++ [over.ics.user]p4:
1767 // A conversion of an expression of class type to the same class
1768 // type is given Exact Match rank, and a conversion of an
1769 // expression of class type to a base class of that type is
1770 // given Conversion rank, in spite of the fact that a copy/move
1771 // constructor (i.e., a user-defined conversion function) is
1772 // called for those cases.
1773 QualType FromType = From->getType();
1774 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1775 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1776 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1777 ICS.setStandard();
1779 ICS.Standard.setFromType(FromType);
1780 ICS.Standard.setAllToTypes(ToType);
1781
1782 // We don't actually check at this point whether there is a valid
1783 // copy/move constructor, since overloading just assumes that it
1784 // exists. When we actually perform initialization, we'll find the
1785 // appropriate constructor to copy the returned object, if needed.
1786 ICS.Standard.CopyConstructor = nullptr;
1787
1788 // Determine whether this is considered a derived-to-base conversion.
1789 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1791
1792 return ICS;
1793 }
1794
1795 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1796 FromType->isHLSLAttributedResourceType()) {
1797 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1798 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1799 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1800 FromResType->getWrappedType()) &&
1801 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1802 FromResType->getContainedType()) &&
1803 ToResType->getAttrs() == FromResType->getAttrs()) {
1804 ICS.setStandard();
1806 ICS.Standard.setFromType(FromType);
1807 ICS.Standard.setAllToTypes(ToType);
1808 return ICS;
1809 }
1810 }
1811
1812 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1813 AllowExplicit, InOverloadResolution, CStyle,
1814 AllowObjCWritebackConversion,
1815 AllowObjCConversionOnExplicit);
1816}
1817
1820 bool SuppressUserConversions,
1821 AllowedExplicit AllowExplicit,
1822 bool InOverloadResolution,
1823 bool CStyle,
1824 bool AllowObjCWritebackConversion) {
1825 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1826 AllowExplicit, InOverloadResolution, CStyle,
1827 AllowObjCWritebackConversion,
1828 /*AllowObjCConversionOnExplicit=*/false);
1829}
1830
1832 AssignmentAction Action,
1833 bool AllowExplicit) {
1834 if (checkPlaceholderForOverload(*this, From))
1835 return ExprError();
1836
1837 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1838 bool AllowObjCWritebackConversion =
1839 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1840 Action == AssignmentAction::Sending);
1841 if (getLangOpts().ObjC)
1842 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1843 From->getType(), From);
1845 *this, From, ToType,
1846 /*SuppressUserConversions=*/false,
1847 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1848 /*InOverloadResolution=*/false,
1849 /*CStyle=*/false, AllowObjCWritebackConversion,
1850 /*AllowObjCConversionOnExplicit=*/false);
1851 return PerformImplicitConversion(From, ToType, ICS, Action);
1852}
1853
1855 QualType &ResultTy) {
1856 if (Context.hasSameUnqualifiedType(FromType, ToType))
1857 return false;
1858
1859 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1860 // or F(t noexcept) -> F(t)
1861 // where F adds one of the following at most once:
1862 // - a pointer
1863 // - a member pointer
1864 // - a block pointer
1865 // Changes here need matching changes in FindCompositePointerType.
1866 CanQualType CanTo = Context.getCanonicalType(ToType);
1867 CanQualType CanFrom = Context.getCanonicalType(FromType);
1868 Type::TypeClass TyClass = CanTo->getTypeClass();
1869 if (TyClass != CanFrom->getTypeClass()) return false;
1870 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1871 if (TyClass == Type::Pointer) {
1872 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1873 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1874 } else if (TyClass == Type::BlockPointer) {
1875 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1876 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1877 } else if (TyClass == Type::MemberPointer) {
1878 auto ToMPT = CanTo.castAs<MemberPointerType>();
1879 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1880 // A function pointer conversion cannot change the class of the function.
1881 if (ToMPT->getClass() != FromMPT->getClass())
1882 return false;
1883 CanTo = ToMPT->getPointeeType();
1884 CanFrom = FromMPT->getPointeeType();
1885 } else {
1886 return false;
1887 }
1888
1889 TyClass = CanTo->getTypeClass();
1890 if (TyClass != CanFrom->getTypeClass()) return false;
1891 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1892 return false;
1893 }
1894
1895 const auto *FromFn = cast<FunctionType>(CanFrom);
1896 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1897
1898 const auto *ToFn = cast<FunctionType>(CanTo);
1899 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1900
1901 bool Changed = false;
1902
1903 // Drop 'noreturn' if not present in target type.
1904 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1905 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1906 Changed = true;
1907 }
1908
1909 // Drop 'noexcept' if not present in target type.
1910 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1911 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1912 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1913 FromFn = cast<FunctionType>(
1914 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1915 EST_None)
1916 .getTypePtr());
1917 Changed = true;
1918 }
1919
1920 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1921 // only if the ExtParameterInfo lists of the two function prototypes can be
1922 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1924 bool CanUseToFPT, CanUseFromFPT;
1925 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1926 CanUseFromFPT, NewParamInfos) &&
1927 CanUseToFPT && !CanUseFromFPT) {
1928 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1929 ExtInfo.ExtParameterInfos =
1930 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1931 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1932 FromFPT->getParamTypes(), ExtInfo);
1933 FromFn = QT->getAs<FunctionType>();
1934 Changed = true;
1935 }
1936
1937 // For C, when called from checkPointerTypesForAssignment,
1938 // we need to not alter FromFn, or else even an innocuous cast
1939 // like dropping effects will fail. In C++ however we do want to
1940 // alter FromFn (because of the way PerformImplicitConversion works).
1941 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1942 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1943
1944 // Transparently add/drop effects; here we are concerned with
1945 // language rules/canonicalization. Adding/dropping effects is a warning.
1946 const auto FromFX = FromFPT->getFunctionEffects();
1947 const auto ToFX = ToFPT->getFunctionEffects();
1948 if (FromFX != ToFX) {
1949 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1950 ExtInfo.FunctionEffects = ToFX;
1951 QualType QT = Context.getFunctionType(
1952 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1953 FromFn = QT->getAs<FunctionType>();
1954 Changed = true;
1955 }
1956 }
1957 }
1958
1959 if (!Changed)
1960 return false;
1961
1962 assert(QualType(FromFn, 0).isCanonical());
1963 if (QualType(FromFn, 0) != CanTo) return false;
1964
1965 ResultTy = ToType;
1966 return true;
1967}
1968
1969/// Determine whether the conversion from FromType to ToType is a valid
1970/// floating point conversion.
1971///
1972static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1973 QualType ToType) {
1974 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1975 return false;
1976 // FIXME: disable conversions between long double, __ibm128 and __float128
1977 // if their representation is different until there is back end support
1978 // We of course allow this conversion if long double is really double.
1979
1980 // Conversions between bfloat16 and float16 are currently not supported.
1981 if ((FromType->isBFloat16Type() &&
1982 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1983 (ToType->isBFloat16Type() &&
1984 (FromType->isFloat16Type() || FromType->isHalfType())))
1985 return false;
1986
1987 // Conversions between IEEE-quad and IBM-extended semantics are not
1988 // permitted.
1989 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1990 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1991 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1992 &ToSem == &llvm::APFloat::IEEEquad()) ||
1993 (&FromSem == &llvm::APFloat::IEEEquad() &&
1994 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1995 return false;
1996 return true;
1997}
1998
1999static bool IsVectorElementConversion(Sema &S, QualType FromType,
2000 QualType ToType,
2001 ImplicitConversionKind &ICK, Expr *From) {
2002 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2003 return true;
2004
2005 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2007 return true;
2008 }
2009
2010 if (IsFloatingPointConversion(S, FromType, ToType)) {
2012 return true;
2013 }
2014
2015 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2017 return true;
2018 }
2019
2020 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2022 ToType->isRealFloatingType())) {
2024 return true;
2025 }
2026
2027 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2029 return true;
2030 }
2031
2032 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2033 ToType->isIntegralType(S.Context)) {
2035 return true;
2036 }
2037
2038 return false;
2039}
2040
2041/// Determine whether the conversion from FromType to ToType is a valid
2042/// vector conversion.
2043///
2044/// \param ICK Will be set to the vector conversion kind, if this is a vector
2045/// conversion.
2046static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2048 ImplicitConversionKind &ElConv, Expr *From,
2049 bool InOverloadResolution, bool CStyle) {
2050 // We need at least one of these types to be a vector type to have a vector
2051 // conversion.
2052 if (!ToType->isVectorType() && !FromType->isVectorType())
2053 return false;
2054
2055 // Identical types require no conversions.
2056 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2057 return false;
2058
2059 // HLSL allows implicit truncation of vector types.
2060 if (S.getLangOpts().HLSL) {
2061 auto *ToExtType = ToType->getAs<ExtVectorType>();
2062 auto *FromExtType = FromType->getAs<ExtVectorType>();
2063
2064 // If both arguments are vectors, handle possible vector truncation and
2065 // element conversion.
2066 if (ToExtType && FromExtType) {
2067 unsigned FromElts = FromExtType->getNumElements();
2068 unsigned ToElts = ToExtType->getNumElements();
2069 if (FromElts < ToElts)
2070 return false;
2071 if (FromElts == ToElts)
2072 ElConv = ICK_Identity;
2073 else
2075
2076 QualType FromElTy = FromExtType->getElementType();
2077 QualType ToElTy = ToExtType->getElementType();
2078 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2079 return true;
2080 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2081 }
2082 if (FromExtType && !ToExtType) {
2084 QualType FromElTy = FromExtType->getElementType();
2085 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2086 return true;
2087 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2088 }
2089 // Fallthrough for the case where ToType is a vector and FromType is not.
2090 }
2091
2092 // There are no conversions between extended vector types, only identity.
2093 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2094 if (FromType->getAs<ExtVectorType>()) {
2095 // There are no conversions between extended vector types other than the
2096 // identity conversion.
2097 return false;
2098 }
2099
2100 // Vector splat from any arithmetic type to a vector.
2101 if (FromType->isArithmeticType()) {
2102 if (S.getLangOpts().HLSL) {
2103 ElConv = ICK_HLSL_Vector_Splat;
2104 QualType ToElTy = ToExtType->getElementType();
2105 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2106 }
2107 ICK = ICK_Vector_Splat;
2108 return true;
2109 }
2110 }
2111
2112 if (ToType->isSVESizelessBuiltinType() ||
2113 FromType->isSVESizelessBuiltinType())
2114 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2115 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2117 return true;
2118 }
2119
2120 if (ToType->isRVVSizelessBuiltinType() ||
2121 FromType->isRVVSizelessBuiltinType())
2122 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2123 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2125 return true;
2126 }
2127
2128 // We can perform the conversion between vector types in the following cases:
2129 // 1)vector types are equivalent AltiVec and GCC vector types
2130 // 2)lax vector conversions are permitted and the vector types are of the
2131 // same size
2132 // 3)the destination type does not have the ARM MVE strict-polymorphism
2133 // attribute, which inhibits lax vector conversion for overload resolution
2134 // only
2135 if (ToType->isVectorType() && FromType->isVectorType()) {
2136 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2137 (S.isLaxVectorConversion(FromType, ToType) &&
2138 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2139 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2140 S.isLaxVectorConversion(FromType, ToType) &&
2141 S.anyAltivecTypes(FromType, ToType) &&
2142 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2143 !InOverloadResolution && !CStyle) {
2144 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2145 << FromType << ToType;
2146 }
2148 return true;
2149 }
2150 }
2151
2152 return false;
2153}
2154
2155static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2156 bool InOverloadResolution,
2158 bool CStyle);
2159
2160/// IsStandardConversion - Determines whether there is a standard
2161/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2162/// expression From to the type ToType. Standard conversion sequences
2163/// only consider non-class types; for conversions that involve class
2164/// types, use TryImplicitConversion. If a conversion exists, SCS will
2165/// contain the standard conversion sequence required to perform this
2166/// conversion and this routine will return true. Otherwise, this
2167/// routine will return false and the value of SCS is unspecified.
2168static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2169 bool InOverloadResolution,
2171 bool CStyle,
2172 bool AllowObjCWritebackConversion) {
2173 QualType FromType = From->getType();
2174
2175 // Standard conversions (C++ [conv])
2177 SCS.IncompatibleObjC = false;
2178 SCS.setFromType(FromType);
2179 SCS.CopyConstructor = nullptr;
2180
2181 // There are no standard conversions for class types in C++, so
2182 // abort early. When overloading in C, however, we do permit them.
2183 if (S.getLangOpts().CPlusPlus &&
2184 (FromType->isRecordType() || ToType->isRecordType()))
2185 return false;
2186
2187 // The first conversion can be an lvalue-to-rvalue conversion,
2188 // array-to-pointer conversion, or function-to-pointer conversion
2189 // (C++ 4p1).
2190
2191 if (FromType == S.Context.OverloadTy) {
2192 DeclAccessPair AccessPair;
2193 if (FunctionDecl *Fn
2194 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2195 AccessPair)) {
2196 // We were able to resolve the address of the overloaded function,
2197 // so we can convert to the type of that function.
2198 FromType = Fn->getType();
2199 SCS.setFromType(FromType);
2200
2201 // we can sometimes resolve &foo<int> regardless of ToType, so check
2202 // if the type matches (identity) or we are converting to bool
2204 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2205 QualType resultTy;
2206 // if the function type matches except for [[noreturn]], it's ok
2207 if (!S.IsFunctionConversion(FromType,
2208 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2209 // otherwise, only a boolean conversion is standard
2210 if (!ToType->isBooleanType())
2211 return false;
2212 }
2213
2214 // Check if the "from" expression is taking the address of an overloaded
2215 // function and recompute the FromType accordingly. Take advantage of the
2216 // fact that non-static member functions *must* have such an address-of
2217 // expression.
2218 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2219 if (Method && !Method->isStatic() &&
2220 !Method->isExplicitObjectMemberFunction()) {
2221 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2222 "Non-unary operator on non-static member address");
2223 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2224 == UO_AddrOf &&
2225 "Non-address-of operator on non-static member address");
2226 const Type *ClassType
2228 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2229 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2230 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2231 UO_AddrOf &&
2232 "Non-address-of operator for overloaded function expression");
2233 FromType = S.Context.getPointerType(FromType);
2234 }
2235 } else {
2236 return false;
2237 }
2238 }
2239
2240 bool argIsLValue = From->isGLValue();
2241 // To handle conversion from ArrayParameterType to ConstantArrayType
2242 // this block must be above the one below because Array parameters
2243 // do not decay and when handling HLSLOutArgExprs and
2244 // the From expression is an LValue.
2245 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2246 ToType->isConstantArrayType()) {
2247 // HLSL constant array parameters do not decay, so if the argument is a
2248 // constant array and the parameter is an ArrayParameterType we have special
2249 // handling here.
2250 if (ToType->isArrayParameterType()) {
2251 FromType = S.Context.getArrayParameterType(FromType);
2253 } else if (FromType->isArrayParameterType()) {
2254 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2255 FromType = APT->getConstantArrayType(S.Context);
2257 } else {
2258 SCS.First = ICK_Identity;
2259 }
2260
2261 if (S.Context.getCanonicalType(FromType) !=
2262 S.Context.getCanonicalType(ToType))
2263 return false;
2264
2265 SCS.setAllToTypes(ToType);
2266 return true;
2267 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2268 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2269 // Lvalue-to-rvalue conversion (C++11 4.1):
2270 // A glvalue (3.10) of a non-function, non-array type T can
2271 // be converted to a prvalue.
2272
2274
2275 // C11 6.3.2.1p2:
2276 // ... if the lvalue has atomic type, the value has the non-atomic version
2277 // of the type of the lvalue ...
2278 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2279 FromType = Atomic->getValueType();
2280
2281 // If T is a non-class type, the type of the rvalue is the
2282 // cv-unqualified version of T. Otherwise, the type of the rvalue
2283 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2284 // just strip the qualifiers because they don't matter.
2285 FromType = FromType.getUnqualifiedType();
2286 } else if (FromType->isArrayType()) {
2287 // Array-to-pointer conversion (C++ 4.2)
2289
2290 // An lvalue or rvalue of type "array of N T" or "array of unknown
2291 // bound of T" can be converted to an rvalue of type "pointer to
2292 // T" (C++ 4.2p1).
2293 FromType = S.Context.getArrayDecayedType(FromType);
2294
2295 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2296 // This conversion is deprecated in C++03 (D.4)
2298
2299 // For the purpose of ranking in overload resolution
2300 // (13.3.3.1.1), this conversion is considered an
2301 // array-to-pointer conversion followed by a qualification
2302 // conversion (4.4). (C++ 4.2p2)
2303 SCS.Second = ICK_Identity;
2306 SCS.setAllToTypes(FromType);
2307 return true;
2308 }
2309 } else if (FromType->isFunctionType() && argIsLValue) {
2310 // Function-to-pointer conversion (C++ 4.3).
2312
2313 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2314 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2316 return false;
2317
2318 // An lvalue of function type T can be converted to an rvalue of
2319 // type "pointer to T." The result is a pointer to the
2320 // function. (C++ 4.3p1).
2321 FromType = S.Context.getPointerType(FromType);
2322 } else {
2323 // We don't require any conversions for the first step.
2324 SCS.First = ICK_Identity;
2325 }
2326 SCS.setToType(0, FromType);
2327
2328 // The second conversion can be an integral promotion, floating
2329 // point promotion, integral conversion, floating point conversion,
2330 // floating-integral conversion, pointer conversion,
2331 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2332 // For overloading in C, this can also be a "compatible-type"
2333 // conversion.
2334 bool IncompatibleObjC = false;
2336 ImplicitConversionKind DimensionICK = ICK_Identity;
2337 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2338 // The unqualified versions of the types are the same: there's no
2339 // conversion to do.
2340 SCS.Second = ICK_Identity;
2341 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2342 // Integral promotion (C++ 4.5).
2344 FromType = ToType.getUnqualifiedType();
2345 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2346 // Floating point promotion (C++ 4.6).
2348 FromType = ToType.getUnqualifiedType();
2349 } else if (S.IsComplexPromotion(FromType, ToType)) {
2350 // Complex promotion (Clang extension)
2352 FromType = ToType.getUnqualifiedType();
2353 } else if (ToType->isBooleanType() &&
2354 (FromType->isArithmeticType() ||
2355 FromType->isAnyPointerType() ||
2356 FromType->isBlockPointerType() ||
2357 FromType->isMemberPointerType())) {
2358 // Boolean conversions (C++ 4.12).
2360 FromType = S.Context.BoolTy;
2361 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2362 ToType->isIntegralType(S.Context)) {
2363 // Integral conversions (C++ 4.7).
2365 FromType = ToType.getUnqualifiedType();
2366 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2367 // Complex conversions (C99 6.3.1.6)
2369 FromType = ToType.getUnqualifiedType();
2370 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2371 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2372 // Complex-real conversions (C99 6.3.1.7)
2374 FromType = ToType.getUnqualifiedType();
2375 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2376 // Floating point conversions (C++ 4.8).
2378 FromType = ToType.getUnqualifiedType();
2379 } else if ((FromType->isRealFloatingType() &&
2380 ToType->isIntegralType(S.Context)) ||
2382 ToType->isRealFloatingType())) {
2383
2384 // Floating-integral conversions (C++ 4.9).
2386 FromType = ToType.getUnqualifiedType();
2387 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2389 } else if (AllowObjCWritebackConversion &&
2390 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2392 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2393 FromType, IncompatibleObjC)) {
2394 // Pointer conversions (C++ 4.10).
2396 SCS.IncompatibleObjC = IncompatibleObjC;
2397 FromType = FromType.getUnqualifiedType();
2398 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2399 InOverloadResolution, FromType)) {
2400 // Pointer to member conversions (4.11).
2402 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2403 From, InOverloadResolution, CStyle)) {
2404 SCS.Second = SecondICK;
2405 SCS.Dimension = DimensionICK;
2406 FromType = ToType.getUnqualifiedType();
2407 } else if (!S.getLangOpts().CPlusPlus &&
2408 S.Context.typesAreCompatible(ToType, FromType)) {
2409 // Compatible conversions (Clang extension for C function overloading)
2411 FromType = ToType.getUnqualifiedType();
2413 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2415 FromType = ToType;
2416 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2417 CStyle)) {
2418 // tryAtomicConversion has updated the standard conversion sequence
2419 // appropriately.
2420 return true;
2421 } else if (ToType->isEventT() &&
2423 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2425 FromType = ToType;
2426 } else if (ToType->isQueueT() &&
2428 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2430 FromType = ToType;
2431 } else if (ToType->isSamplerT() &&
2434 FromType = ToType;
2435 } else if ((ToType->isFixedPointType() &&
2436 FromType->isConvertibleToFixedPointType()) ||
2437 (FromType->isFixedPointType() &&
2438 ToType->isConvertibleToFixedPointType())) {
2440 FromType = ToType;
2441 } else {
2442 // No second conversion required.
2443 SCS.Second = ICK_Identity;
2444 }
2445 SCS.setToType(1, FromType);
2446
2447 // The third conversion can be a function pointer conversion or a
2448 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2449 bool ObjCLifetimeConversion;
2450 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2451 // Function pointer conversions (removing 'noexcept') including removal of
2452 // 'noreturn' (Clang extension).
2454 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2455 ObjCLifetimeConversion)) {
2457 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2458 FromType = ToType;
2459 } else {
2460 // No conversion required
2461 SCS.Third = ICK_Identity;
2462 }
2463
2464 // C++ [over.best.ics]p6:
2465 // [...] Any difference in top-level cv-qualification is
2466 // subsumed by the initialization itself and does not constitute
2467 // a conversion. [...]
2468 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2469 QualType CanonTo = S.Context.getCanonicalType(ToType);
2470 if (CanonFrom.getLocalUnqualifiedType()
2471 == CanonTo.getLocalUnqualifiedType() &&
2472 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2473 FromType = ToType;
2474 CanonFrom = CanonTo;
2475 }
2476
2477 SCS.setToType(2, FromType);
2478
2479 if (CanonFrom == CanonTo)
2480 return true;
2481
2482 // If we have not converted the argument type to the parameter type,
2483 // this is a bad conversion sequence, unless we're resolving an overload in C.
2484 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2485 return false;
2486
2487 ExprResult ER = ExprResult{From};
2490 /*Diagnose=*/false,
2491 /*DiagnoseCFAudited=*/false,
2492 /*ConvertRHS=*/false);
2493 ImplicitConversionKind SecondConv;
2494 switch (Conv) {
2495 case Sema::Compatible:
2496 SecondConv = ICK_C_Only_Conversion;
2497 break;
2498 // For our purposes, discarding qualifiers is just as bad as using an
2499 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2500 // qualifiers, as well.
2505 break;
2506 default:
2507 return false;
2508 }
2509
2510 // First can only be an lvalue conversion, so we pretend that this was the
2511 // second conversion. First should already be valid from earlier in the
2512 // function.
2513 SCS.Second = SecondConv;
2514 SCS.setToType(1, ToType);
2515
2516 // Third is Identity, because Second should rank us worse than any other
2517 // conversion. This could also be ICK_Qualification, but it's simpler to just
2518 // lump everything in with the second conversion, and we don't gain anything
2519 // from making this ICK_Qualification.
2520 SCS.Third = ICK_Identity;
2521 SCS.setToType(2, ToType);
2522 return true;
2523}
2524
2525static bool
2527 QualType &ToType,
2528 bool InOverloadResolution,
2530 bool CStyle) {
2531
2532 const RecordType *UT = ToType->getAsUnionType();
2533 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2534 return false;
2535 // The field to initialize within the transparent union.
2536 RecordDecl *UD = UT->getDecl();
2537 // It's compatible if the expression matches any of the fields.
2538 for (const auto *it : UD->fields()) {
2539 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2540 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2541 ToType = it->getType();
2542 return true;
2543 }
2544 }
2545 return false;
2546}
2547
2548bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2549 const BuiltinType *To = ToType->getAs<BuiltinType>();
2550 // All integers are built-in.
2551 if (!To) {
2552 return false;
2553 }
2554
2555 // An rvalue of type char, signed char, unsigned char, short int, or
2556 // unsigned short int can be converted to an rvalue of type int if
2557 // int can represent all the values of the source type; otherwise,
2558 // the source rvalue can be converted to an rvalue of type unsigned
2559 // int (C++ 4.5p1).
2560 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2561 !FromType->isEnumeralType()) {
2562 if ( // We can promote any signed, promotable integer type to an int
2563 (FromType->isSignedIntegerType() ||
2564 // We can promote any unsigned integer type whose size is
2565 // less than int to an int.
2566 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2567 return To->getKind() == BuiltinType::Int;
2568 }
2569
2570 return To->getKind() == BuiltinType::UInt;
2571 }
2572
2573 // C++11 [conv.prom]p3:
2574 // A prvalue of an unscoped enumeration type whose underlying type is not
2575 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2576 // following types that can represent all the values of the enumeration
2577 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2578 // unsigned int, long int, unsigned long int, long long int, or unsigned
2579 // long long int. If none of the types in that list can represent all the
2580 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2581 // type can be converted to an rvalue a prvalue of the extended integer type
2582 // with lowest integer conversion rank (4.13) greater than the rank of long
2583 // long in which all the values of the enumeration can be represented. If
2584 // there are two such extended types, the signed one is chosen.
2585 // C++11 [conv.prom]p4:
2586 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2587 // can be converted to a prvalue of its underlying type. Moreover, if
2588 // integral promotion can be applied to its underlying type, a prvalue of an
2589 // unscoped enumeration type whose underlying type is fixed can also be
2590 // converted to a prvalue of the promoted underlying type.
2591 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2592 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2593 // provided for a scoped enumeration.
2594 if (FromEnumType->getDecl()->isScoped())
2595 return false;
2596
2597 // We can perform an integral promotion to the underlying type of the enum,
2598 // even if that's not the promoted type. Note that the check for promoting
2599 // the underlying type is based on the type alone, and does not consider
2600 // the bitfield-ness of the actual source expression.
2601 if (FromEnumType->getDecl()->isFixed()) {
2602 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2603 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2604 IsIntegralPromotion(nullptr, Underlying, ToType);
2605 }
2606
2607 // We have already pre-calculated the promotion type, so this is trivial.
2608 if (ToType->isIntegerType() &&
2609 isCompleteType(From->getBeginLoc(), FromType))
2610 return Context.hasSameUnqualifiedType(
2611 ToType, FromEnumType->getDecl()->getPromotionType());
2612
2613 // C++ [conv.prom]p5:
2614 // If the bit-field has an enumerated type, it is treated as any other
2615 // value of that type for promotion purposes.
2616 //
2617 // ... so do not fall through into the bit-field checks below in C++.
2618 if (getLangOpts().CPlusPlus)
2619 return false;
2620 }
2621
2622 // C++0x [conv.prom]p2:
2623 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2624 // to an rvalue a prvalue of the first of the following types that can
2625 // represent all the values of its underlying type: int, unsigned int,
2626 // long int, unsigned long int, long long int, or unsigned long long int.
2627 // If none of the types in that list can represent all the values of its
2628 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2629 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2630 // type.
2631 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2632 ToType->isIntegerType()) {
2633 // Determine whether the type we're converting from is signed or
2634 // unsigned.
2635 bool FromIsSigned = FromType->isSignedIntegerType();
2636 uint64_t FromSize = Context.getTypeSize(FromType);
2637
2638 // The types we'll try to promote to, in the appropriate
2639 // order. Try each of these types.
2640 QualType PromoteTypes[6] = {
2641 Context.IntTy, Context.UnsignedIntTy,
2642 Context.LongTy, Context.UnsignedLongTy ,
2643 Context.LongLongTy, Context.UnsignedLongLongTy
2644 };
2645 for (int Idx = 0; Idx < 6; ++Idx) {
2646 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2647 if (FromSize < ToSize ||
2648 (FromSize == ToSize &&
2649 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2650 // We found the type that we can promote to. If this is the
2651 // type we wanted, we have a promotion. Otherwise, no
2652 // promotion.
2653 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2654 }
2655 }
2656 }
2657
2658 // An rvalue for an integral bit-field (9.6) can be converted to an
2659 // rvalue of type int if int can represent all the values of the
2660 // bit-field; otherwise, it can be converted to unsigned int if
2661 // unsigned int can represent all the values of the bit-field. If
2662 // the bit-field is larger yet, no integral promotion applies to
2663 // it. If the bit-field has an enumerated type, it is treated as any
2664 // other value of that type for promotion purposes (C++ 4.5p3).
2665 // FIXME: We should delay checking of bit-fields until we actually perform the
2666 // conversion.
2667 //
2668 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2669 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2670 // bit-fields and those whose underlying type is larger than int) for GCC
2671 // compatibility.
2672 if (From) {
2673 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2674 std::optional<llvm::APSInt> BitWidth;
2675 if (FromType->isIntegralType(Context) &&
2676 (BitWidth =
2677 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2678 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2679 ToSize = Context.getTypeSize(ToType);
2680
2681 // Are we promoting to an int from a bitfield that fits in an int?
2682 if (*BitWidth < ToSize ||
2683 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2684 return To->getKind() == BuiltinType::Int;
2685 }
2686
2687 // Are we promoting to an unsigned int from an unsigned bitfield
2688 // that fits into an unsigned int?
2689 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2690 return To->getKind() == BuiltinType::UInt;
2691 }
2692
2693 return false;
2694 }
2695 }
2696 }
2697
2698 // An rvalue of type bool can be converted to an rvalue of type int,
2699 // with false becoming zero and true becoming one (C++ 4.5p4).
2700 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2701 return true;
2702 }
2703
2704 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2705 // integral type.
2706 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2707 ToType->isIntegerType())
2708 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2709
2710 return false;
2711}
2712
2714 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2715 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2716 /// An rvalue of type float can be converted to an rvalue of type
2717 /// double. (C++ 4.6p1).
2718 if (FromBuiltin->getKind() == BuiltinType::Float &&
2719 ToBuiltin->getKind() == BuiltinType::Double)
2720 return true;
2721
2722 // C99 6.3.1.5p1:
2723 // When a float is promoted to double or long double, or a
2724 // double is promoted to long double [...].
2725 if (!getLangOpts().CPlusPlus &&
2726 (FromBuiltin->getKind() == BuiltinType::Float ||
2727 FromBuiltin->getKind() == BuiltinType::Double) &&
2728 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2729 ToBuiltin->getKind() == BuiltinType::Float128 ||
2730 ToBuiltin->getKind() == BuiltinType::Ibm128))
2731 return true;
2732
2733 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2734 // or not native half types are enabled.
2735 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2736 (ToBuiltin->getKind() == BuiltinType::Float ||
2737 ToBuiltin->getKind() == BuiltinType::Double))
2738 return true;
2739
2740 // Half can be promoted to float.
2741 if (!getLangOpts().NativeHalfType &&
2742 FromBuiltin->getKind() == BuiltinType::Half &&
2743 ToBuiltin->getKind() == BuiltinType::Float)
2744 return true;
2745 }
2746
2747 return false;
2748}
2749
2751 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2752 if (!FromComplex)
2753 return false;
2754
2755 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2756 if (!ToComplex)
2757 return false;
2758
2759 return IsFloatingPointPromotion(FromComplex->getElementType(),
2760 ToComplex->getElementType()) ||
2761 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2762 ToComplex->getElementType());
2763}
2764
2765/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2766/// the pointer type FromPtr to a pointer to type ToPointee, with the
2767/// same type qualifiers as FromPtr has on its pointee type. ToType,
2768/// if non-empty, will be a pointer to ToType that may or may not have
2769/// the right set of qualifiers on its pointee.
2770///
2771static QualType
2773 QualType ToPointee, QualType ToType,
2774 ASTContext &Context,
2775 bool StripObjCLifetime = false) {
2776 assert((FromPtr->getTypeClass() == Type::Pointer ||
2777 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2778 "Invalid similarly-qualified pointer type");
2779
2780 /// Conversions to 'id' subsume cv-qualifier conversions.
2781 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2782 return ToType.getUnqualifiedType();
2783
2784 QualType CanonFromPointee
2785 = Context.getCanonicalType(FromPtr->getPointeeType());
2786 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2787 Qualifiers Quals = CanonFromPointee.getQualifiers();
2788
2789 if (StripObjCLifetime)
2790 Quals.removeObjCLifetime();
2791
2792 // Exact qualifier match -> return the pointer type we're converting to.
2793 if (CanonToPointee.getLocalQualifiers() == Quals) {
2794 // ToType is exactly what we need. Return it.
2795 if (!ToType.isNull())
2796 return ToType.getUnqualifiedType();
2797
2798 // Build a pointer to ToPointee. It has the right qualifiers
2799 // already.
2800 if (isa<ObjCObjectPointerType>(ToType))
2801 return Context.getObjCObjectPointerType(ToPointee);
2802 return Context.getPointerType(ToPointee);
2803 }
2804
2805 // Just build a canonical type that has the right qualifiers.
2806 QualType QualifiedCanonToPointee
2807 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2808
2809 if (isa<ObjCObjectPointerType>(ToType))
2810 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2811 return Context.getPointerType(QualifiedCanonToPointee);
2812}
2813
2815 bool InOverloadResolution,
2816 ASTContext &Context) {
2817 // Handle value-dependent integral null pointer constants correctly.
2818 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2819 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2821 return !InOverloadResolution;
2822
2823 return Expr->isNullPointerConstant(Context,
2824 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2826}
2827
2829 bool InOverloadResolution,
2830 QualType& ConvertedType,
2831 bool &IncompatibleObjC) {
2832 IncompatibleObjC = false;
2833 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2834 IncompatibleObjC))
2835 return true;
2836
2837 // Conversion from a null pointer constant to any Objective-C pointer type.
2838 if (ToType->isObjCObjectPointerType() &&
2839 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2840 ConvertedType = ToType;
2841 return true;
2842 }
2843
2844 // Blocks: Block pointers can be converted to void*.
2845 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2846 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2847 ConvertedType = ToType;
2848 return true;
2849 }
2850 // Blocks: A null pointer constant can be converted to a block
2851 // pointer type.
2852 if (ToType->isBlockPointerType() &&
2853 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2854 ConvertedType = ToType;
2855 return true;
2856 }
2857
2858 // If the left-hand-side is nullptr_t, the right side can be a null
2859 // pointer constant.
2860 if (ToType->isNullPtrType() &&
2861 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2862 ConvertedType = ToType;
2863 return true;
2864 }
2865
2866 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2867 if (!ToTypePtr)
2868 return false;
2869
2870 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2871 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2872 ConvertedType = ToType;
2873 return true;
2874 }
2875
2876 // Beyond this point, both types need to be pointers
2877 // , including objective-c pointers.
2878 QualType ToPointeeType = ToTypePtr->getPointeeType();
2879 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2880 !getLangOpts().ObjCAutoRefCount) {
2881 ConvertedType = BuildSimilarlyQualifiedPointerType(
2882 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2883 Context);
2884 return true;
2885 }
2886 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2887 if (!FromTypePtr)
2888 return false;
2889
2890 QualType FromPointeeType = FromTypePtr->getPointeeType();
2891
2892 // If the unqualified pointee types are the same, this can't be a
2893 // pointer conversion, so don't do all of the work below.
2894 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2895 return false;
2896
2897 // An rvalue of type "pointer to cv T," where T is an object type,
2898 // can be converted to an rvalue of type "pointer to cv void" (C++
2899 // 4.10p2).
2900 if (FromPointeeType->isIncompleteOrObjectType() &&
2901 ToPointeeType->isVoidType()) {
2902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2903 ToPointeeType,
2904 ToType, Context,
2905 /*StripObjCLifetime=*/true);
2906 return true;
2907 }
2908
2909 // MSVC allows implicit function to void* type conversion.
2910 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2911 ToPointeeType->isVoidType()) {
2912 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2913 ToPointeeType,
2914 ToType, Context);
2915 return true;
2916 }
2917
2918 // When we're overloading in C, we allow a special kind of pointer
2919 // conversion for compatible-but-not-identical pointee types.
2920 if (!getLangOpts().CPlusPlus &&
2921 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2922 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2923 ToPointeeType,
2924 ToType, Context);
2925 return true;
2926 }
2927
2928 // C++ [conv.ptr]p3:
2929 //
2930 // An rvalue of type "pointer to cv D," where D is a class type,
2931 // can be converted to an rvalue of type "pointer to cv B," where
2932 // B is a base class (clause 10) of D. If B is an inaccessible
2933 // (clause 11) or ambiguous (10.2) base class of D, a program that
2934 // necessitates this conversion is ill-formed. The result of the
2935 // conversion is a pointer to the base class sub-object of the
2936 // derived class object. The null pointer value is converted to
2937 // the null pointer value of the destination type.
2938 //
2939 // Note that we do not check for ambiguity or inaccessibility
2940 // here. That is handled by CheckPointerConversion.
2941 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2942 ToPointeeType->isRecordType() &&
2943 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2944 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2945 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2946 ToPointeeType,
2947 ToType, Context);
2948 return true;
2949 }
2950
2951 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2952 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2954 ToPointeeType,
2955 ToType, Context);
2956 return true;
2957 }
2958
2959 return false;
2960}
2961
2962/// Adopt the given qualifiers for the given type.
2964 Qualifiers TQs = T.getQualifiers();
2965
2966 // Check whether qualifiers already match.
2967 if (TQs == Qs)
2968 return T;
2969
2970 if (Qs.compatiblyIncludes(TQs, Context))
2971 return Context.getQualifiedType(T, Qs);
2972
2973 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2974}
2975
2977 QualType& ConvertedType,
2978 bool &IncompatibleObjC) {
2979 if (!getLangOpts().ObjC)
2980 return false;
2981
2982 // The set of qualifiers on the type we're converting from.
2983 Qualifiers FromQualifiers = FromType.getQualifiers();
2984
2985 // First, we handle all conversions on ObjC object pointer types.
2986 const ObjCObjectPointerType* ToObjCPtr =
2987 ToType->getAs<ObjCObjectPointerType>();
2988 const ObjCObjectPointerType *FromObjCPtr =
2989 FromType->getAs<ObjCObjectPointerType>();
2990
2991 if (ToObjCPtr && FromObjCPtr) {
2992 // If the pointee types are the same (ignoring qualifications),
2993 // then this is not a pointer conversion.
2994 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2995 FromObjCPtr->getPointeeType()))
2996 return false;
2997
2998 // Conversion between Objective-C pointers.
2999 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3000 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3001 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3002 if (getLangOpts().CPlusPlus && LHS && RHS &&
3004 FromObjCPtr->getPointeeType(), getASTContext()))
3005 return false;
3006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3007 ToObjCPtr->getPointeeType(),
3008 ToType, Context);
3009 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3010 return true;
3011 }
3012
3013 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3014 // Okay: this is some kind of implicit downcast of Objective-C
3015 // interfaces, which is permitted. However, we're going to
3016 // complain about it.
3017 IncompatibleObjC = true;
3018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3019 ToObjCPtr->getPointeeType(),
3020 ToType, Context);
3021 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3022 return true;
3023 }
3024 }
3025 // Beyond this point, both types need to be C pointers or block pointers.
3026 QualType ToPointeeType;
3027 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3028 ToPointeeType = ToCPtr->getPointeeType();
3029 else if (const BlockPointerType *ToBlockPtr =
3030 ToType->getAs<BlockPointerType>()) {
3031 // Objective C++: We're able to convert from a pointer to any object
3032 // to a block pointer type.
3033 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3034 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3035 return true;
3036 }
3037 ToPointeeType = ToBlockPtr->getPointeeType();
3038 }
3039 else if (FromType->getAs<BlockPointerType>() &&
3040 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3041 // Objective C++: We're able to convert from a block pointer type to a
3042 // pointer to any object.
3043 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3044 return true;
3045 }
3046 else
3047 return false;
3048
3049 QualType FromPointeeType;
3050 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3051 FromPointeeType = FromCPtr->getPointeeType();
3052 else if (const BlockPointerType *FromBlockPtr =
3053 FromType->getAs<BlockPointerType>())
3054 FromPointeeType = FromBlockPtr->getPointeeType();
3055 else
3056 return false;
3057
3058 // If we have pointers to pointers, recursively check whether this
3059 // is an Objective-C conversion.
3060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3062 IncompatibleObjC)) {
3063 // We always complain about this conversion.
3064 IncompatibleObjC = true;
3065 ConvertedType = Context.getPointerType(ConvertedType);
3066 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3067 return true;
3068 }
3069 // Allow conversion of pointee being objective-c pointer to another one;
3070 // as in I* to id.
3071 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3072 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3073 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3074 IncompatibleObjC)) {
3075
3076 ConvertedType = Context.getPointerType(ConvertedType);
3077 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3078 return true;
3079 }
3080
3081 // If we have pointers to functions or blocks, check whether the only
3082 // differences in the argument and result types are in Objective-C
3083 // pointer conversions. If so, we permit the conversion (but
3084 // complain about it).
3085 const FunctionProtoType *FromFunctionType
3086 = FromPointeeType->getAs<FunctionProtoType>();
3087 const FunctionProtoType *ToFunctionType
3088 = ToPointeeType->getAs<FunctionProtoType>();
3089 if (FromFunctionType && ToFunctionType) {
3090 // If the function types are exactly the same, this isn't an
3091 // Objective-C pointer conversion.
3092 if (Context.getCanonicalType(FromPointeeType)
3093 == Context.getCanonicalType(ToPointeeType))
3094 return false;
3095
3096 // Perform the quick checks that will tell us whether these
3097 // function types are obviously different.
3098 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3099 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3100 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3101 return false;
3102
3103 bool HasObjCConversion = false;
3104 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3105 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3106 // Okay, the types match exactly. Nothing to do.
3107 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3108 ToFunctionType->getReturnType(),
3109 ConvertedType, IncompatibleObjC)) {
3110 // Okay, we have an Objective-C pointer conversion.
3111 HasObjCConversion = true;
3112 } else {
3113 // Function types are too different. Abort.
3114 return false;
3115 }
3116
3117 // Check argument types.
3118 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3119 ArgIdx != NumArgs; ++ArgIdx) {
3120 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3121 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3122 if (Context.getCanonicalType(FromArgType)
3123 == Context.getCanonicalType(ToArgType)) {
3124 // Okay, the types match exactly. Nothing to do.
3125 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3126 ConvertedType, IncompatibleObjC)) {
3127 // Okay, we have an Objective-C pointer conversion.
3128 HasObjCConversion = true;
3129 } else {
3130 // Argument types are too different. Abort.
3131 return false;
3132 }
3133 }
3134
3135 if (HasObjCConversion) {
3136 // We had an Objective-C conversion. Allow this pointer
3137 // conversion, but complain about it.
3138 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3139 IncompatibleObjC = true;
3140 return true;
3141 }
3142 }
3143
3144 return false;
3145}
3146
3148 QualType& ConvertedType) {
3149 QualType ToPointeeType;
3150 if (const BlockPointerType *ToBlockPtr =
3151 ToType->getAs<BlockPointerType>())
3152 ToPointeeType = ToBlockPtr->getPointeeType();
3153 else
3154 return false;
3155
3156 QualType FromPointeeType;
3157 if (const BlockPointerType *FromBlockPtr =
3158 FromType->getAs<BlockPointerType>())
3159 FromPointeeType = FromBlockPtr->getPointeeType();
3160 else
3161 return false;
3162 // We have pointer to blocks, check whether the only
3163 // differences in the argument and result types are in Objective-C
3164 // pointer conversions. If so, we permit the conversion.
3165
3166 const FunctionProtoType *FromFunctionType
3167 = FromPointeeType->getAs<FunctionProtoType>();
3168 const FunctionProtoType *ToFunctionType
3169 = ToPointeeType->getAs<FunctionProtoType>();
3170
3171 if (!FromFunctionType || !ToFunctionType)
3172 return false;
3173
3174 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3175 return true;
3176
3177 // Perform the quick checks that will tell us whether these
3178 // function types are obviously different.
3179 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3180 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3181 return false;
3182
3183 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3184 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3185 if (FromEInfo != ToEInfo)
3186 return false;
3187
3188 bool IncompatibleObjC = false;
3189 if (Context.hasSameType(FromFunctionType->getReturnType(),
3190 ToFunctionType->getReturnType())) {
3191 // Okay, the types match exactly. Nothing to do.
3192 } else {
3193 QualType RHS = FromFunctionType->getReturnType();
3194 QualType LHS = ToFunctionType->getReturnType();
3195 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3196 !RHS.hasQualifiers() && LHS.hasQualifiers())
3197 LHS = LHS.getUnqualifiedType();
3198
3199 if (Context.hasSameType(RHS,LHS)) {
3200 // OK exact match.
3201 } else if (isObjCPointerConversion(RHS, LHS,
3202 ConvertedType, IncompatibleObjC)) {
3203 if (IncompatibleObjC)
3204 return false;
3205 // Okay, we have an Objective-C pointer conversion.
3206 }
3207 else
3208 return false;
3209 }
3210
3211 // Check argument types.
3212 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3213 ArgIdx != NumArgs; ++ArgIdx) {
3214 IncompatibleObjC = false;
3215 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3216 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3217 if (Context.hasSameType(FromArgType, ToArgType)) {
3218 // Okay, the types match exactly. Nothing to do.
3219 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3220 ConvertedType, IncompatibleObjC)) {
3221 if (IncompatibleObjC)
3222 return false;
3223 // Okay, we have an Objective-C pointer conversion.
3224 } else
3225 // Argument types are too different. Abort.
3226 return false;
3227 }
3228
3230 bool CanUseToFPT, CanUseFromFPT;
3231 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3232 CanUseToFPT, CanUseFromFPT,
3233 NewParamInfos))
3234 return false;
3235
3236 ConvertedType = ToType;
3237 return true;
3238}
3239
3240enum {
3249
3250/// Attempts to get the FunctionProtoType from a Type. Handles
3251/// MemberFunctionPointers properly.
3253 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3254 return FPT;
3255
3256 if (auto *MPT = FromType->getAs<MemberPointerType>())
3257 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3258
3259 return nullptr;
3260}
3261
3263 QualType FromType, QualType ToType) {
3264 // If either type is not valid, include no extra info.
3265 if (FromType.isNull() || ToType.isNull()) {
3266 PDiag << ft_default;
3267 return;
3268 }
3269
3270 // Get the function type from the pointers.
3271 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3272 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3273 *ToMember = ToType->castAs<MemberPointerType>();
3274 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3275 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3276 << QualType(FromMember->getClass(), 0);
3277 return;
3278 }
3279 FromType = FromMember->getPointeeType();
3280 ToType = ToMember->getPointeeType();
3281 }
3282
3283 if (FromType->isPointerType())
3284 FromType = FromType->getPointeeType();
3285 if (ToType->isPointerType())
3286 ToType = ToType->getPointeeType();
3287
3288 // Remove references.
3289 FromType = FromType.getNonReferenceType();
3290 ToType = ToType.getNonReferenceType();
3291
3292 // Don't print extra info for non-specialized template functions.
3293 if (FromType->isInstantiationDependentType() &&
3294 !FromType->getAs<TemplateSpecializationType>()) {
3295 PDiag << ft_default;
3296 return;
3297 }
3298
3299 // No extra info for same types.
3300 if (Context.hasSameType(FromType, ToType)) {
3301 PDiag << ft_default;
3302 return;
3303 }
3304
3305 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3306 *ToFunction = tryGetFunctionProtoType(ToType);
3307
3308 // Both types need to be function types.
3309 if (!FromFunction || !ToFunction) {
3310 PDiag << ft_default;
3311 return;
3312 }
3313
3314 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3315 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3316 << FromFunction->getNumParams();
3317 return;
3318 }
3319
3320 // Handle different parameter types.
3321 unsigned ArgPos;
3322 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3323 PDiag << ft_parameter_mismatch << ArgPos + 1
3324 << ToFunction->getParamType(ArgPos)
3325 << FromFunction->getParamType(ArgPos);
3326 return;
3327 }
3328
3329 // Handle different return type.
3330 if (!Context.hasSameType(FromFunction->getReturnType(),
3331 ToFunction->getReturnType())) {
3332 PDiag << ft_return_type << ToFunction->getReturnType()
3333 << FromFunction->getReturnType();
3334 return;
3335 }
3336
3337 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3338 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3339 << FromFunction->getMethodQuals();
3340 return;
3341 }
3342
3343 // Handle exception specification differences on canonical type (in C++17
3344 // onwards).
3345 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3346 ->isNothrow() !=
3347 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3348 ->isNothrow()) {
3349 PDiag << ft_noexcept;
3350 return;
3351 }
3352
3353 // Unable to find a difference, so add no extra info.
3354 PDiag << ft_default;
3355}
3356
3358 ArrayRef<QualType> New, unsigned *ArgPos,
3359 bool Reversed) {
3360 assert(llvm::size(Old) == llvm::size(New) &&
3361 "Can't compare parameters of functions with different number of "
3362 "parameters!");
3363
3364 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3365 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3366 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3367
3368 // Ignore address spaces in pointee type. This is to disallow overloading
3369 // on __ptr32/__ptr64 address spaces.
3370 QualType OldType =
3371 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3372 QualType NewType =
3373 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3374
3375 if (!Context.hasSameType(OldType, NewType)) {
3376 if (ArgPos)
3377 *ArgPos = Idx;
3378 return false;
3379 }
3380 }
3381 return true;
3382}
3383
3385 const FunctionProtoType *NewType,
3386 unsigned *ArgPos, bool Reversed) {
3387 return FunctionParamTypesAreEqual(OldType->param_types(),
3388 NewType->param_types(), ArgPos, Reversed);
3389}
3390
3392 const FunctionDecl *NewFunction,
3393 unsigned *ArgPos,
3394 bool Reversed) {
3395
3396 if (OldFunction->getNumNonObjectParams() !=
3397 NewFunction->getNumNonObjectParams())
3398 return false;
3399
3400 unsigned OldIgnore =
3402 unsigned NewIgnore =
3404
3405 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3406 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3407
3408 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3409 NewPT->param_types().slice(NewIgnore),
3410 ArgPos, Reversed);
3411}
3412
3414 CastKind &Kind,
3415 CXXCastPath& BasePath,
3416 bool IgnoreBaseAccess,
3417 bool Diagnose) {
3418 QualType FromType = From->getType();
3419 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3420
3421 Kind = CK_BitCast;
3422
3423 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3426 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3427 DiagRuntimeBehavior(From->getExprLoc(), From,
3428 PDiag(diag::warn_impcast_bool_to_null_pointer)
3429 << ToType << From->getSourceRange());
3430 else if (!isUnevaluatedContext())
3431 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3432 << ToType << From->getSourceRange();
3433 }
3434 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3435 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3436 QualType FromPointeeType = FromPtrType->getPointeeType(),
3437 ToPointeeType = ToPtrType->getPointeeType();
3438
3439 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3441 // We must have a derived-to-base conversion. Check an
3442 // ambiguous or inaccessible conversion.
3443 unsigned InaccessibleID = 0;
3444 unsigned AmbiguousID = 0;
3445 if (Diagnose) {
3446 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3447 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3448 }
3449 if (CheckDerivedToBaseConversion(
3450 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3451 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3452 &BasePath, IgnoreBaseAccess))
3453 return true;
3454
3455 // The conversion was successful.
3456 Kind = CK_DerivedToBase;
3457 }
3458
3459 if (Diagnose && !IsCStyleOrFunctionalCast &&
3460 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3461 assert(getLangOpts().MSVCCompat &&
3462 "this should only be possible with MSVCCompat!");
3463 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3464 << From->getSourceRange();
3465 }
3466 }
3467 } else if (const ObjCObjectPointerType *ToPtrType =
3468 ToType->getAs<ObjCObjectPointerType>()) {
3469 if (const ObjCObjectPointerType *FromPtrType =
3470 FromType->getAs<ObjCObjectPointerType>()) {
3471 // Objective-C++ conversions are always okay.
3472 // FIXME: We should have a different class of conversions for the
3473 // Objective-C++ implicit conversions.
3474 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3475 return false;
3476 } else if (FromType->isBlockPointerType()) {
3477 Kind = CK_BlockPointerToObjCPointerCast;
3478 } else {
3479 Kind = CK_CPointerToObjCPointerCast;
3480 }
3481 } else if (ToType->isBlockPointerType()) {
3482 if (!FromType->isBlockPointerType())
3483 Kind = CK_AnyPointerToBlockPointerCast;
3484 }
3485
3486 // We shouldn't fall into this case unless it's valid for other
3487 // reasons.
3489 Kind = CK_NullToPointer;
3490
3491 return false;
3492}
3493
3495 QualType ToType,
3496 bool InOverloadResolution,
3497 QualType &ConvertedType) {
3498 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3499 if (!ToTypePtr)
3500 return false;
3501
3502 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3503 if (From->isNullPointerConstant(Context,
3504 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3506 ConvertedType = ToType;
3507 return true;
3508 }
3509
3510 // Otherwise, both types have to be member pointers.
3511 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3512 if (!FromTypePtr)
3513 return false;
3514
3515 // A pointer to member of B can be converted to a pointer to member of D,
3516 // where D is derived from B (C++ 4.11p2).
3517 QualType FromClass(FromTypePtr->getClass(), 0);
3518 QualType ToClass(ToTypePtr->getClass(), 0);
3519
3520 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3521 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3522 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3523 ToClass.getTypePtr());
3524 return true;
3525 }
3526
3527 return false;
3528}
3529
3531 CastKind &Kind,
3532 CXXCastPath &BasePath,
3533 bool IgnoreBaseAccess) {
3534 QualType FromType = From->getType();
3535 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3536 if (!FromPtrType) {
3537 // This must be a null pointer to member pointer conversion
3538 assert(From->isNullPointerConstant(Context,
3540 "Expr must be null pointer constant!");
3541 Kind = CK_NullToMemberPointer;
3542 return false;
3543 }
3544
3545 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3546 assert(ToPtrType && "No member pointer cast has a target type "
3547 "that is not a member pointer.");
3548
3549 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3550 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3551
3552 // FIXME: What about dependent types?
3553 assert(FromClass->isRecordType() && "Pointer into non-class.");
3554 assert(ToClass->isRecordType() && "Pointer into non-class.");
3555
3556 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3557 /*DetectVirtual=*/true);
3558 bool DerivationOkay =
3559 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3560 assert(DerivationOkay &&
3561 "Should not have been called if derivation isn't OK.");
3562 (void)DerivationOkay;
3563
3564 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3565 getUnqualifiedType())) {
3566 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3567 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3568 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3569 return true;
3570 }
3571
3572 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3573 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3574 << FromClass << ToClass << QualType(VBase, 0)
3575 << From->getSourceRange();
3576 return true;
3577 }
3578
3579 if (!IgnoreBaseAccess)
3580 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3581 Paths.front(),
3582 diag::err_downcast_from_inaccessible_base);
3583
3584 // Must be a base to derived member conversion.
3585 BuildBasePathArray(Paths, BasePath);
3586 Kind = CK_BaseToDerivedMemberPointer;
3587 return false;
3588}
3589
3590/// Determine whether the lifetime conversion between the two given
3591/// qualifiers sets is nontrivial.
3593 Qualifiers ToQuals) {
3594 // Converting anything to const __unsafe_unretained is trivial.
3595 if (ToQuals.hasConst() &&
3597 return false;
3598
3599 return true;
3600}
3601
3602/// Perform a single iteration of the loop for checking if a qualification
3603/// conversion is valid.
3604///
3605/// Specifically, check whether any change between the qualifiers of \p
3606/// FromType and \p ToType is permissible, given knowledge about whether every
3607/// outer layer is const-qualified.
3609 bool CStyle, bool IsTopLevel,
3610 bool &PreviousToQualsIncludeConst,
3611 bool &ObjCLifetimeConversion,
3612 const ASTContext &Ctx) {
3613 Qualifiers FromQuals = FromType.getQualifiers();
3614 Qualifiers ToQuals = ToType.getQualifiers();
3615
3616 // Ignore __unaligned qualifier.
3617 FromQuals.removeUnaligned();
3618
3619 // Objective-C ARC:
3620 // Check Objective-C lifetime conversions.
3621 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3622 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3623 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3624 ObjCLifetimeConversion = true;
3625 FromQuals.removeObjCLifetime();
3626 ToQuals.removeObjCLifetime();
3627 } else {
3628 // Qualification conversions cannot cast between different
3629 // Objective-C lifetime qualifiers.
3630 return false;
3631 }
3632 }
3633
3634 // Allow addition/removal of GC attributes but not changing GC attributes.
3635 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3636 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3637 FromQuals.removeObjCGCAttr();
3638 ToQuals.removeObjCGCAttr();
3639 }
3640
3641 // -- for every j > 0, if const is in cv 1,j then const is in cv
3642 // 2,j, and similarly for volatile.
3643 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3644 return false;
3645
3646 // If address spaces mismatch:
3647 // - in top level it is only valid to convert to addr space that is a
3648 // superset in all cases apart from C-style casts where we allow
3649 // conversions between overlapping address spaces.
3650 // - in non-top levels it is not a valid conversion.
3651 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3652 (!IsTopLevel ||
3653 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3654 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3655 return false;
3656
3657 // -- if the cv 1,j and cv 2,j are different, then const is in
3658 // every cv for 0 < k < j.
3659 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3660 !PreviousToQualsIncludeConst)
3661 return false;
3662
3663 // The following wording is from C++20, where the result of the conversion
3664 // is T3, not T2.
3665 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3666 // "array of unknown bound of"
3667 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3668 return false;
3669
3670 // -- if the resulting P3,i is different from P1,i [...], then const is
3671 // added to every cv 3_k for 0 < k < i.
3672 if (!CStyle && FromType->isConstantArrayType() &&
3673 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3674 return false;
3675
3676 // Keep track of whether all prior cv-qualifiers in the "to" type
3677 // include const.
3678 PreviousToQualsIncludeConst =
3679 PreviousToQualsIncludeConst && ToQuals.hasConst();
3680 return true;
3681}
3682
3683bool
3685 bool CStyle, bool &ObjCLifetimeConversion) {
3686 FromType = Context.getCanonicalType(FromType);
3687 ToType = Context.getCanonicalType(ToType);
3688 ObjCLifetimeConversion = false;
3689
3690 // If FromType and ToType are the same type, this is not a
3691 // qualification conversion.
3692 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3693 return false;
3694
3695 // (C++ 4.4p4):
3696 // A conversion can add cv-qualifiers at levels other than the first
3697 // in multi-level pointers, subject to the following rules: [...]
3698 bool PreviousToQualsIncludeConst = true;
3699 bool UnwrappedAnyPointer = false;
3700 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3701 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3702 !UnwrappedAnyPointer,
3703 PreviousToQualsIncludeConst,
3704 ObjCLifetimeConversion, getASTContext()))
3705 return false;
3706 UnwrappedAnyPointer = true;
3707 }
3708
3709 // We are left with FromType and ToType being the pointee types
3710 // after unwrapping the original FromType and ToType the same number
3711 // of times. If we unwrapped any pointers, and if FromType and
3712 // ToType have the same unqualified type (since we checked
3713 // qualifiers above), then this is a qualification conversion.
3714 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3715}
3716
3717/// - Determine whether this is a conversion from a scalar type to an
3718/// atomic type.
3719///
3720/// If successful, updates \c SCS's second and third steps in the conversion
3721/// sequence to finish the conversion.
3722static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3723 bool InOverloadResolution,
3725 bool CStyle) {
3726 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3727 if (!ToAtomic)
3728 return false;
3729
3731 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3732 InOverloadResolution, InnerSCS,
3733 CStyle, /*AllowObjCWritebackConversion=*/false))
3734 return false;
3735
3736 SCS.Second = InnerSCS.Second;
3737 SCS.setToType(1, InnerSCS.getToType(1));
3738 SCS.Third = InnerSCS.Third;
3741 SCS.setToType(2, InnerSCS.getToType(2));
3742 return true;
3743}
3744
3746 CXXConstructorDecl *Constructor,
3747 QualType Type) {
3748 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3749 if (CtorType->getNumParams() > 0) {
3750 QualType FirstArg = CtorType->getParamType(0);
3751 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3752 return true;
3753 }
3754 return false;
3755}
3756
3757static OverloadingResult
3759 CXXRecordDecl *To,
3761 OverloadCandidateSet &CandidateSet,
3762 bool AllowExplicit) {
3764 for (auto *D : S.LookupConstructors(To)) {
3765 auto Info = getConstructorInfo(D);
3766 if (!Info)
3767 continue;
3768
3769 bool Usable = !Info.Constructor->isInvalidDecl() &&
3770 S.isInitListConstructor(Info.Constructor);
3771 if (Usable) {
3772 bool SuppressUserConversions = false;
3773 if (Info.ConstructorTmpl)
3774 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3775 /*ExplicitArgs*/ nullptr, From,
3776 CandidateSet, SuppressUserConversions,
3777 /*PartialOverloading*/ false,
3778 AllowExplicit);
3779 else
3780 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3781 CandidateSet, SuppressUserConversions,
3782 /*PartialOverloading*/ false, AllowExplicit);
3783 }
3784 }
3785
3786 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3787
3789 switch (auto Result =
3790 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3791 case OR_Deleted:
3792 case OR_Success: {
3793 // Record the standard conversion we used and the conversion function.
3794 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3795 QualType ThisType = Constructor->getFunctionObjectParameterType();
3796 // Initializer lists don't have conversions as such.
3798 User.HadMultipleCandidates = HadMultipleCandidates;
3799 User.ConversionFunction = Constructor;
3800 User.FoundConversionFunction = Best->FoundDecl;
3802 User.After.setFromType(ThisType);
3803 User.After.setAllToTypes(ToType);
3804 return Result;
3805 }
3806
3808 return OR_No_Viable_Function;
3809 case OR_Ambiguous:
3810 return OR_Ambiguous;
3811 }
3812
3813 llvm_unreachable("Invalid OverloadResult!");
3814}
3815
3816/// Determines whether there is a user-defined conversion sequence
3817/// (C++ [over.ics.user]) that converts expression From to the type
3818/// ToType. If such a conversion exists, User will contain the
3819/// user-defined conversion sequence that performs such a conversion
3820/// and this routine will return true. Otherwise, this routine returns
3821/// false and User is unspecified.
3822///
3823/// \param AllowExplicit true if the conversion should consider C++0x
3824/// "explicit" conversion functions as well as non-explicit conversion
3825/// functions (C++0x [class.conv.fct]p2).
3826///
3827/// \param AllowObjCConversionOnExplicit true if the conversion should
3828/// allow an extra Objective-C pointer conversion on uses of explicit
3829/// constructors. Requires \c AllowExplicit to also be set.
3830static OverloadingResult
3833 OverloadCandidateSet &CandidateSet,
3834 AllowedExplicit AllowExplicit,
3835 bool AllowObjCConversionOnExplicit) {
3836 assert(AllowExplicit != AllowedExplicit::None ||
3837 !AllowObjCConversionOnExplicit);
3839
3840 // Whether we will only visit constructors.
3841 bool ConstructorsOnly = false;
3842
3843 // If the type we are conversion to is a class type, enumerate its
3844 // constructors.
3845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3846 // C++ [over.match.ctor]p1:
3847 // When objects of class type are direct-initialized (8.5), or
3848 // copy-initialized from an expression of the same or a
3849 // derived class type (8.5), overload resolution selects the
3850 // constructor. [...] For copy-initialization, the candidate
3851 // functions are all the converting constructors (12.3.1) of
3852 // that class. The argument list is the expression-list within
3853 // the parentheses of the initializer.
3854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3855 (From->getType()->getAs<RecordType>() &&
3856 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3857 ConstructorsOnly = true;
3858
3859 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3860 // We're not going to find any constructors.
3861 } else if (CXXRecordDecl *ToRecordDecl
3862 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3863
3864 Expr **Args = &From;
3865 unsigned NumArgs = 1;
3866 bool ListInitializing = false;
3867 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3868 // But first, see if there is an init-list-constructor that will work.
3870 S, From, ToType, ToRecordDecl, User, CandidateSet,
3871 AllowExplicit == AllowedExplicit::All);
3873 return Result;
3874 // Never mind.
3875 CandidateSet.clear(
3877
3878 // If we're list-initializing, we pass the individual elements as
3879 // arguments, not the entire list.
3880 Args = InitList->getInits();
3881 NumArgs = InitList->getNumInits();
3882 ListInitializing = true;
3883 }
3884
3885 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3886 auto Info = getConstructorInfo(D);
3887 if (!Info)
3888 continue;
3889
3890 bool Usable = !Info.Constructor->isInvalidDecl();
3891 if (!ListInitializing)
3892 Usable = Usable && Info.Constructor->isConvertingConstructor(
3893 /*AllowExplicit*/ true);
3894 if (Usable) {
3895 bool SuppressUserConversions = !ConstructorsOnly;
3896 // C++20 [over.best.ics.general]/4.5:
3897 // if the target is the first parameter of a constructor [of class
3898 // X] and the constructor [...] is a candidate by [...] the second
3899 // phase of [over.match.list] when the initializer list has exactly
3900 // one element that is itself an initializer list, [...] and the
3901 // conversion is to X or reference to cv X, user-defined conversion
3902 // sequences are not cnosidered.
3903 if (SuppressUserConversions && ListInitializing) {
3904 SuppressUserConversions =
3905 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3906 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3907 ToType);
3908 }
3909 if (Info.ConstructorTmpl)
3911 Info.ConstructorTmpl, Info.FoundDecl,
3912 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3913 CandidateSet, SuppressUserConversions,
3914 /*PartialOverloading*/ false,
3915 AllowExplicit == AllowedExplicit::All);
3916 else
3917 // Allow one user-defined conversion when user specifies a
3918 // From->ToType conversion via an static cast (c-style, etc).
3919 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3920 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3921 SuppressUserConversions,
3922 /*PartialOverloading*/ false,
3923 AllowExplicit == AllowedExplicit::All);
3924 }
3925 }
3926 }
3927 }
3928
3929 // Enumerate conversion functions, if we're allowed to.
3930 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3931 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3932 // No conversion functions from incomplete types.
3933 } else if (const RecordType *FromRecordType =
3934 From->getType()->getAs<RecordType>()) {
3935 if (CXXRecordDecl *FromRecordDecl
3936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3937 // Add all of the conversion functions as candidates.
3938 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3939 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3940 DeclAccessPair FoundDecl = I.getPair();
3941 NamedDecl *D = FoundDecl.getDecl();
3942 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3943 if (isa<UsingShadowDecl>(D))
3944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3945
3946 CXXConversionDecl *Conv;
3947 FunctionTemplateDecl *ConvTemplate;
3948 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3949 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3950 else
3951 Conv = cast<CXXConversionDecl>(D);
3952
3953 if (ConvTemplate)
3955 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3956 CandidateSet, AllowObjCConversionOnExplicit,
3957 AllowExplicit != AllowedExplicit::None);
3958 else
3959 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3960 CandidateSet, AllowObjCConversionOnExplicit,
3961 AllowExplicit != AllowedExplicit::None);
3962 }
3963 }
3964 }
3965
3966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3967
3969 switch (auto Result =
3970 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3971 case OR_Success:
3972 case OR_Deleted:
3973 // Record the standard conversion we used and the conversion function.
3974 if (CXXConstructorDecl *Constructor
3975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3976 // C++ [over.ics.user]p1:
3977 // If the user-defined conversion is specified by a
3978 // constructor (12.3.1), the initial standard conversion
3979 // sequence converts the source type to the type required by
3980 // the argument of the constructor.
3981 //
3982 if (isa<InitListExpr>(From)) {
3983 // Initializer lists don't have conversions as such.
3985 } else {
3986 if (Best->Conversions[0].isEllipsis())
3987 User.EllipsisConversion = true;
3988 else {
3989 User.Before = Best->Conversions[0].Standard;
3990 User.EllipsisConversion = false;
3991 }
3992 }
3993 User.HadMultipleCandidates = HadMultipleCandidates;
3994 User.ConversionFunction = Constructor;
3995 User.FoundConversionFunction = Best->FoundDecl;
3997 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3998 User.After.setAllToTypes(ToType);
3999 return Result;
4000 }
4001 if (CXXConversionDecl *Conversion
4002 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4003 // C++ [over.ics.user]p1:
4004 //
4005 // [...] If the user-defined conversion is specified by a
4006 // conversion function (12.3.2), the initial standard
4007 // conversion sequence converts the source type to the
4008 // implicit object parameter of the conversion function.
4009 User.Before = Best->Conversions[0].Standard;
4010 User.HadMultipleCandidates = HadMultipleCandidates;
4011 User.ConversionFunction = Conversion;
4012 User.FoundConversionFunction = Best->FoundDecl;
4013 User.EllipsisConversion = false;
4014
4015 // C++ [over.ics.user]p2:
4016 // The second standard conversion sequence converts the
4017 // result of the user-defined conversion to the target type
4018 // for the sequence. Since an implicit conversion sequence
4019 // is an initialization, the special rules for
4020 // initialization by user-defined conversion apply when
4021 // selecting the best user-defined conversion for a
4022 // user-defined conversion sequence (see 13.3.3 and
4023 // 13.3.3.1).
4024 User.After = Best->FinalConversion;
4025 return Result;
4026 }
4027 llvm_unreachable("Not a constructor or conversion function?");
4028
4030 return OR_No_Viable_Function;
4031
4032 case OR_Ambiguous:
4033 return OR_Ambiguous;
4034 }
4035
4036 llvm_unreachable("Invalid OverloadResult!");
4037}
4038
4039bool
4042 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4044 OverloadingResult OvResult =
4045 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4046 CandidateSet, AllowedExplicit::None, false);
4047
4048 if (!(OvResult == OR_Ambiguous ||
4049 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4050 return false;
4051
4052 auto Cands = CandidateSet.CompleteCandidates(
4053 *this,
4055 From);
4056 if (OvResult == OR_Ambiguous)
4057 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4058 << From->getType() << ToType << From->getSourceRange();
4059 else { // OR_No_Viable_Function && !CandidateSet.empty()
4060 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4061 diag::err_typecheck_nonviable_condition_incomplete,
4062 From->getType(), From->getSourceRange()))
4063 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4064 << false << From->getType() << From->getSourceRange() << ToType;
4065 }
4066
4067 CandidateSet.NoteCandidates(
4068 *this, From, Cands);
4069 return true;
4070}
4071
4072// Helper for compareConversionFunctions that gets the FunctionType that the
4073// conversion-operator return value 'points' to, or nullptr.
4074static const FunctionType *
4076 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4077 const PointerType *RetPtrTy =
4078 ConvFuncTy->getReturnType()->getAs<PointerType>();
4079
4080 if (!RetPtrTy)
4081 return nullptr;
4082
4083 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4084}
4085
4086/// Compare the user-defined conversion functions or constructors
4087/// of two user-defined conversion sequences to determine whether any ordering
4088/// is possible.
4091 FunctionDecl *Function2) {
4092 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4093 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4094 if (!Conv1 || !Conv2)
4096
4097 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4099
4100 // Objective-C++:
4101 // If both conversion functions are implicitly-declared conversions from
4102 // a lambda closure type to a function pointer and a block pointer,
4103 // respectively, always prefer the conversion to a function pointer,
4104 // because the function pointer is more lightweight and is more likely
4105 // to keep code working.
4106 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4107 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4108 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4109 if (Block1 != Block2)
4110 return Block1 ? ImplicitConversionSequence::Worse
4112 }
4113
4114 // In order to support multiple calling conventions for the lambda conversion
4115 // operator (such as when the free and member function calling convention is
4116 // different), prefer the 'free' mechanism, followed by the calling-convention
4117 // of operator(). The latter is in place to support the MSVC-like solution of
4118 // defining ALL of the possible conversions in regards to calling-convention.
4119 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4120 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4121
4122 if (Conv1FuncRet && Conv2FuncRet &&
4123 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4124 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4125 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4126
4127 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4128 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4129
4130 CallingConv CallOpCC =
4131 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4133 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4135 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4136
4137 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4138 for (CallingConv CC : PrefOrder) {
4139 if (Conv1CC == CC)
4141 if (Conv2CC == CC)
4143 }
4144 }
4145
4147}
4148
4150 const ImplicitConversionSequence &ICS) {
4152 (ICS.isUserDefined() &&
4154}
4155
4156/// CompareImplicitConversionSequences - Compare two implicit
4157/// conversion sequences to determine whether one is better than the
4158/// other or if they are indistinguishable (C++ 13.3.3.2).
4161 const ImplicitConversionSequence& ICS1,
4162 const ImplicitConversionSequence& ICS2)
4163{
4164 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4165 // conversion sequences (as defined in 13.3.3.1)
4166 // -- a standard conversion sequence (13.3.3.1.1) is a better
4167 // conversion sequence than a user-defined conversion sequence or
4168 // an ellipsis conversion sequence, and
4169 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4170 // conversion sequence than an ellipsis conversion sequence
4171 // (13.3.3.1.3).
4172 //
4173 // C++0x [over.best.ics]p10:
4174 // For the purpose of ranking implicit conversion sequences as
4175 // described in 13.3.3.2, the ambiguous conversion sequence is
4176 // treated as a user-defined sequence that is indistinguishable
4177 // from any other user-defined conversion sequence.
4178
4179 // String literal to 'char *' conversion has been deprecated in C++03. It has
4180 // been removed from C++11. We still accept this conversion, if it happens at
4181 // the best viable function. Otherwise, this conversion is considered worse
4182 // than ellipsis conversion. Consider this as an extension; this is not in the
4183 // standard. For example:
4184 //
4185 // int &f(...); // #1
4186 // void f(char*); // #2
4187 // void g() { int &r = f("foo"); }
4188 //
4189 // In C++03, we pick #2 as the best viable function.
4190 // In C++11, we pick #1 as the best viable function, because ellipsis
4191 // conversion is better than string-literal to char* conversion (since there
4192 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4193 // convert arguments, #2 would be the best viable function in C++11.
4194 // If the best viable function has this conversion, a warning will be issued
4195 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4196
4197 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4200 // Ill-formedness must not differ
4201 ICS1.isBad() == ICS2.isBad())
4205
4206 if (ICS1.getKindRank() < ICS2.getKindRank())
4208 if (ICS2.getKindRank() < ICS1.getKindRank())
4210
4211 // The following checks require both conversion sequences to be of
4212 // the same kind.
4213 if (ICS1.getKind() != ICS2.getKind())
4215
4218
4219 // Two implicit conversion sequences of the same form are
4220 // indistinguishable conversion sequences unless one of the
4221 // following rules apply: (C++ 13.3.3.2p3):
4222
4223 // List-initialization sequence L1 is a better conversion sequence than
4224 // list-initialization sequence L2 if:
4225 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4226 // if not that,
4227 // — L1 and L2 convert to arrays of the same element type, and either the
4228 // number of elements n_1 initialized by L1 is less than the number of
4229 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4230 // an array of unknown bound and L1 does not,
4231 // even if one of the other rules in this paragraph would otherwise apply.
4232 if (!ICS1.isBad()) {
4233 bool StdInit1 = false, StdInit2 = false;
4236 nullptr);
4239 nullptr);
4240 if (StdInit1 != StdInit2)
4241 return StdInit1 ? ImplicitConversionSequence::Better
4243
4246 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4248 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4250 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4251 CAT2->getElementType())) {
4252 // Both to arrays of the same element type
4253 if (CAT1->getSize() != CAT2->getSize())
4254 // Different sized, the smaller wins
4255 return CAT1->getSize().ult(CAT2->getSize())
4260 // One is incomplete, it loses
4264 }
4265 }
4266 }
4267
4268 if (ICS1.isStandard())
4269 // Standard conversion sequence S1 is a better conversion sequence than
4270 // standard conversion sequence S2 if [...]
4272 ICS1.Standard, ICS2.Standard);
4273 else if (ICS1.isUserDefined()) {
4274 // User-defined conversion sequence U1 is a better conversion
4275 // sequence than another user-defined conversion sequence U2 if
4276 // they contain the same user-defined conversion function or
4277 // constructor and if the second standard conversion sequence of
4278 // U1 is better than the second standard conversion sequence of
4279 // U2 (C++ 13.3.3.2p3).
4283 ICS1.UserDefined.After,
4284 ICS2.UserDefined.After);
4285 else
4289 }
4290
4291 return Result;
4292}
4293
4294// Per 13.3.3.2p3, compare the given standard conversion sequences to
4295// determine if one is a proper subset of the other.
4298 const StandardConversionSequence& SCS1,
4299 const StandardConversionSequence& SCS2) {
4302
4303 // the identity conversion sequence is considered to be a subsequence of
4304 // any non-identity conversion sequence
4305 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4307 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4309
4310 if (SCS1.Second != SCS2.Second) {
4311 if (SCS1.Second == ICK_Identity)
4313 else if (SCS2.Second == ICK_Identity)
4315 else
4317 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4319
4320 if (SCS1.Third == SCS2.Third) {
4321 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4323 }
4324
4325 if (SCS1.Third == ICK_Identity)
4329
4330 if (SCS2.Third == ICK_Identity)
4334
4336}
4337
4338/// Determine whether one of the given reference bindings is better
4339/// than the other based on what kind of bindings they are.
4340static bool
4342 const StandardConversionSequence &SCS2) {
4343 // C++0x [over.ics.rank]p3b4:
4344 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4345 // implicit object parameter of a non-static member function declared
4346 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4347 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4348 // lvalue reference to a function lvalue and S2 binds an rvalue
4349 // reference*.
4350 //
4351 // FIXME: Rvalue references. We're going rogue with the above edits,
4352 // because the semantics in the current C++0x working paper (N3225 at the
4353 // time of this writing) break the standard definition of std::forward
4354 // and std::reference_wrapper when dealing with references to functions.
4355 // Proposed wording changes submitted to CWG for consideration.
4358 return false;
4359
4360 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4361 SCS2.IsLvalueReference) ||
4364}
4365
4367 None,
4370};
4371
4372/// Returns kind of fixed enum promotion the \a SCS uses.
4373static FixedEnumPromotion
4375
4376 if (SCS.Second != ICK_Integral_Promotion)
4377 return FixedEnumPromotion::None;
4378
4379 QualType FromType = SCS.getFromType();
4380 if (!FromType->isEnumeralType())
4381 return FixedEnumPromotion::None;
4382
4383 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4384 if (!Enum->isFixed())
4385 return FixedEnumPromotion::None;
4386
4387 QualType UnderlyingType = Enum->getIntegerType();
4388 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4389 return FixedEnumPromotion::ToUnderlyingType;
4390
4391 return FixedEnumPromotion::ToPromotedUnderlyingType;
4392}
4393
4394/// CompareStandardConversionSequences - Compare two standard
4395/// conversion sequences to determine whether one is better than the
4396/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4399 const StandardConversionSequence& SCS1,
4400 const StandardConversionSequence& SCS2)
4401{
4402 // Standard conversion sequence S1 is a better conversion sequence
4403 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4404
4405 // -- S1 is a proper subsequence of S2 (comparing the conversion
4406 // sequences in the canonical form defined by 13.3.3.1.1,
4407 // excluding any Lvalue Transformation; the identity conversion
4408 // sequence is considered to be a subsequence of any
4409 // non-identity conversion sequence) or, if not that,
4412 return CK;
4413
4414 // -- the rank of S1 is better than the rank of S2 (by the rules
4415 // defined below), or, if not that,
4416 ImplicitConversionRank Rank1 = SCS1.getRank();
4417 ImplicitConversionRank Rank2 = SCS2.getRank();
4418 if (Rank1 < Rank2)
4420 else if (Rank2 < Rank1)
4422
4423 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4424 // are indistinguishable unless one of the following rules
4425 // applies:
4426
4427 // A conversion that is not a conversion of a pointer, or
4428 // pointer to member, to bool is better than another conversion
4429 // that is such a conversion.
4431 return SCS2.isPointerConversionToBool()
4434
4435 // C++14 [over.ics.rank]p4b2:
4436 // This is retroactively applied to C++11 by CWG 1601.
4437 //
4438 // A conversion that promotes an enumeration whose underlying type is fixed
4439 // to its underlying type is better than one that promotes to the promoted
4440 // underlying type, if the two are different.
4443 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4444 FEP1 != FEP2)
4445 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4448
4449 // C++ [over.ics.rank]p4b2:
4450 //
4451 // If class B is derived directly or indirectly from class A,
4452 // conversion of B* to A* is better than conversion of B* to
4453 // void*, and conversion of A* to void* is better than conversion
4454 // of B* to void*.
4455 bool SCS1ConvertsToVoid
4457 bool SCS2ConvertsToVoid
4459 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4460 // Exactly one of the conversion sequences is a conversion to
4461 // a void pointer; it's the worse conversion.
4462 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4464 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4465 // Neither conversion sequence converts to a void pointer; compare
4466 // their derived-to-base conversions.
4468 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4469 return DerivedCK;
4470 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4471 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4472 // Both conversion sequences are conversions to void
4473 // pointers. Compare the source types to determine if there's an
4474 // inheritance relationship in their sources.
4475 QualType FromType1 = SCS1.getFromType();
4476 QualType FromType2 = SCS2.getFromType();
4477
4478 // Adjust the types we're converting from via the array-to-pointer
4479 // conversion, if we need to.
4480 if (SCS1.First == ICK_Array_To_Pointer)
4481 FromType1 = S.Context.getArrayDecayedType(FromType1);
4482 if (SCS2.First == ICK_Array_To_Pointer)
4483 FromType2 = S.Context.getArrayDecayedType(FromType2);
4484
4485 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4486 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4487
4488 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4490 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4492
4493 // Objective-C++: If one interface is more specific than the
4494 // other, it is the better one.
4495 const ObjCObjectPointerType* FromObjCPtr1
4496 = FromType1->getAs<ObjCObjectPointerType>();
4497 const ObjCObjectPointerType* FromObjCPtr2
4498 = FromType2->getAs<ObjCObjectPointerType>();
4499 if (FromObjCPtr1 && FromObjCPtr2) {
4500 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4501 FromObjCPtr2);
4502 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4503 FromObjCPtr1);
4504 if (AssignLeft != AssignRight) {
4505 return AssignLeft? ImplicitConversionSequence::Better
4507 }
4508 }
4509 }
4510
4511 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4512 // Check for a better reference binding based on the kind of bindings.
4513 if (isBetterReferenceBindingKind(SCS1, SCS2))
4515 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4517 }
4518
4519 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4520 // bullet 3).
4522 = CompareQualificationConversions(S, SCS1, SCS2))
4523 return QualCK;
4524
4525 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4526 // C++ [over.ics.rank]p3b4:
4527 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4528 // which the references refer are the same type except for
4529 // top-level cv-qualifiers, and the type to which the reference
4530 // initialized by S2 refers is more cv-qualified than the type
4531 // to which the reference initialized by S1 refers.
4532 QualType T1 = SCS1.getToType(2);
4533 QualType T2 = SCS2.getToType(2);
4534 T1 = S.Context.getCanonicalType(T1);
4535 T2 = S.Context.getCanonicalType(T2);
4536 Qualifiers T1Quals, T2Quals;
4537 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4538 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4539 if (UnqualT1 == UnqualT2) {
4540 // Objective-C++ ARC: If the references refer to objects with different
4541 // lifetimes, prefer bindings that don't change lifetime.
4547 }
4548
4549 // If the type is an array type, promote the element qualifiers to the
4550 // type for comparison.
4551 if (isa<ArrayType>(T1) && T1Quals)
4552 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4553 if (isa<ArrayType>(T2) && T2Quals)
4554 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4555 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4557 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4559 }
4560 }
4561
4562 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4563 // floating-to-integral conversion if the integral conversion
4564 // is between types of the same size.
4565 // For example:
4566 // void f(float);
4567 // void f(int);
4568 // int main {
4569 // long a;
4570 // f(a);
4571 // }
4572 // Here, MSVC will call f(int) instead of generating a compile error
4573 // as clang will do in standard mode.
4574 if (S.getLangOpts().MSVCCompat &&
4577 SCS2.Second == ICK_Floating_Integral &&
4578 S.Context.getTypeSize(SCS1.getFromType()) ==
4579 S.Context.getTypeSize(SCS1.getToType(2)))
4581
4582 // Prefer a compatible vector conversion over a lax vector conversion
4583 // For example:
4584 //
4585 // typedef float __v4sf __attribute__((__vector_size__(16)));
4586 // void f(vector float);
4587 // void f(vector signed int);
4588 // int main() {
4589 // __v4sf a;
4590 // f(a);
4591 // }
4592 // Here, we'd like to choose f(vector float) and not
4593 // report an ambiguous call error
4594 if (SCS1.Second == ICK_Vector_Conversion &&
4595 SCS2.Second == ICK_Vector_Conversion) {
4596 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4597 SCS1.getFromType(), SCS1.getToType(2));
4598 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 SCS2.getFromType(), SCS2.getToType(2));
4600
4601 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4602 return SCS1IsCompatibleVectorConversion
4605 }
4606
4607 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4609 bool SCS1IsCompatibleSVEVectorConversion =
4611 bool SCS2IsCompatibleSVEVectorConversion =
4613
4614 if (SCS1IsCompatibleSVEVectorConversion !=
4615 SCS2IsCompatibleSVEVectorConversion)
4616 return SCS1IsCompatibleSVEVectorConversion
4619 }
4620
4621 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4623 bool SCS1IsCompatibleRVVVectorConversion =
4625 bool SCS2IsCompatibleRVVVectorConversion =
4627
4628 if (SCS1IsCompatibleRVVVectorConversion !=
4629 SCS2IsCompatibleRVVVectorConversion)
4630 return SCS1IsCompatibleRVVVectorConversion
4633 }
4635}
4636
4637/// CompareQualificationConversions - Compares two standard conversion
4638/// sequences to determine whether they can be ranked based on their
4639/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4642 const StandardConversionSequence& SCS1,
4643 const StandardConversionSequence& SCS2) {
4644 // C++ [over.ics.rank]p3:
4645 // -- S1 and S2 differ only in their qualification conversion and
4646 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4647 // [C++98]
4648 // [...] and the cv-qualification signature of type T1 is a proper subset
4649 // of the cv-qualification signature of type T2, and S1 is not the
4650 // deprecated string literal array-to-pointer conversion (4.2).
4651 // [C++2a]
4652 // [...] where T1 can be converted to T2 by a qualification conversion.
4653 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4654 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4656
4657 // FIXME: the example in the standard doesn't use a qualification
4658 // conversion (!)
4659 QualType T1 = SCS1.getToType(2);
4660 QualType T2 = SCS2.getToType(2);
4661 T1 = S.Context.getCanonicalType(T1);
4662 T2 = S.Context.getCanonicalType(T2);
4663 assert(!T1->isReferenceType() && !T2->isReferenceType());
4664 Qualifiers T1Quals, T2Quals;
4665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4667
4668 // If the types are the same, we won't learn anything by unwrapping
4669 // them.
4670 if (UnqualT1 == UnqualT2)
4672
4673 // Don't ever prefer a standard conversion sequence that uses the deprecated
4674 // string literal array to pointer conversion.
4675 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4676 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4677
4678 // Objective-C++ ARC:
4679 // Prefer qualification conversions not involving a change in lifetime
4680 // to qualification conversions that do change lifetime.
4683 CanPick1 = false;
4686 CanPick2 = false;
4687
4688 bool ObjCLifetimeConversion;
4689 if (CanPick1 &&
4690 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4691 CanPick1 = false;
4692 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4693 // directions, so we can't short-cut this second check in general.
4694 if (CanPick2 &&
4695 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4696 CanPick2 = false;
4697
4698 if (CanPick1 != CanPick2)
4699 return CanPick1 ? ImplicitConversionSequence::Better
4702}
4703
4704/// CompareDerivedToBaseConversions - Compares two standard conversion
4705/// sequences to determine whether they can be ranked based on their
4706/// various kinds of derived-to-base conversions (C++
4707/// [over.ics.rank]p4b3). As part of these checks, we also look at
4708/// conversions between Objective-C interface types.
4711 const StandardConversionSequence& SCS1,
4712 const StandardConversionSequence& SCS2) {
4713 QualType FromType1 = SCS1.getFromType();
4714 QualType ToType1 = SCS1.getToType(1);
4715 QualType FromType2 = SCS2.getFromType();
4716 QualType ToType2 = SCS2.getToType(1);
4717
4718 // Adjust the types we're converting from via the array-to-pointer
4719 // conversion, if we need to.
4720 if (SCS1.First == ICK_Array_To_Pointer)
4721 FromType1 = S.Context.getArrayDecayedType(FromType1);
4722 if (SCS2.First == ICK_Array_To_Pointer)
4723 FromType2 = S.Context.getArrayDecayedType(FromType2);
4724
4725 // Canonicalize all of the types.
4726 FromType1 = S.Context.getCanonicalType(FromType1);
4727 ToType1 = S.Context.getCanonicalType(ToType1);
4728 FromType2 = S.Context.getCanonicalType(FromType2);
4729 ToType2 = S.Context.getCanonicalType(ToType2);
4730
4731 // C++ [over.ics.rank]p4b3:
4732 //
4733 // If class B is derived directly or indirectly from class A and
4734 // class C is derived directly or indirectly from B,
4735 //
4736 // Compare based on pointer conversions.
4737 if (SCS1.Second == ICK_Pointer_Conversion &&
4739 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4740 FromType1->isPointerType() && FromType2->isPointerType() &&
4741 ToType1->isPointerType() && ToType2->isPointerType()) {
4742 QualType FromPointee1 =
4744 QualType ToPointee1 =
4746 QualType FromPointee2 =
4748 QualType ToPointee2 =
4750
4751 // -- conversion of C* to B* is better than conversion of C* to A*,
4752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4753 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4755 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4757 }
4758
4759 // -- conversion of B* to A* is better than conversion of C* to A*,
4760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4765 }
4766 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4768 const ObjCObjectPointerType *FromPtr1
4769 = FromType1->getAs<ObjCObjectPointerType>();
4770 const ObjCObjectPointerType *FromPtr2
4771 = FromType2->getAs<ObjCObjectPointerType>();
4772 const ObjCObjectPointerType *ToPtr1
4773 = ToType1->getAs<ObjCObjectPointerType>();
4774 const ObjCObjectPointerType *ToPtr2
4775 = ToType2->getAs<ObjCObjectPointerType>();
4776
4777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4778 // Apply the same conversion ranking rules for Objective-C pointer types
4779 // that we do for C++ pointers to class types. However, we employ the
4780 // Objective-C pseudo-subtyping relationship used for assignment of
4781 // Objective-C pointer types.
4782 bool FromAssignLeft
4783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4784 bool FromAssignRight
4785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4786 bool ToAssignLeft
4787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4788 bool ToAssignRight
4789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4790
4791 // A conversion to an a non-id object pointer type or qualified 'id'
4792 // type is better than a conversion to 'id'.
4793 if (ToPtr1->isObjCIdType() &&
4794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4796 if (ToPtr2->isObjCIdType() &&
4797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4799
4800 // A conversion to a non-id object pointer type is better than a
4801 // conversion to a qualified 'id' type
4802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4806
4807 // A conversion to an a non-Class object pointer type or qualified 'Class'
4808 // type is better than a conversion to 'Class'.
4809 if (ToPtr1->isObjCClassType() &&
4810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4812 if (ToPtr2->isObjCClassType() &&
4813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4815
4816 // A conversion to a non-Class object pointer type is better than a
4817 // conversion to a qualified 'Class' type.
4818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4822
4823 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4824 if (S.Context.hasSameType(FromType1, FromType2) &&
4825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4826 (ToAssignLeft != ToAssignRight)) {
4827 if (FromPtr1->isSpecialized()) {
4828 // "conversion of B<A> * to B * is better than conversion of B * to
4829 // C *.
4830 bool IsFirstSame =
4831 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4832 bool IsSecondSame =
4833 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4834 if (IsFirstSame) {
4835 if (!IsSecondSame)
4837 } else if (IsSecondSame)
4839 }
4840 return ToAssignLeft? ImplicitConversionSequence::Worse
4842 }
4843
4844 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4845 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4846 (FromAssignLeft != FromAssignRight))
4847 return FromAssignLeft? ImplicitConversionSequence::Better
4849 }
4850 }
4851
4852 // Ranking of member-pointer types.
4853 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4854 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4855 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4856 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4857 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4858 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4859