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