clang 19.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/ASTLambda.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Template.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/Support/Casting.h"
43#include <algorithm>
44#include <cstddef>
45#include <cstdlib>
46#include <optional>
47
48using namespace clang;
49using namespace sema;
50
52
54 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
55 return P->hasAttr<PassObjectSizeAttr>();
56 });
57}
58
59/// A convenience routine for creating a decayed reference to a function.
61 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
62 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
63 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
64 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
65 return ExprError();
66 // If FoundDecl is different from Fn (such as if one is a template
67 // and the other a specialization), make sure DiagnoseUseOfDecl is
68 // called on both.
69 // FIXME: This would be more comprehensively addressed by modifying
70 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
71 // being used.
72 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
73 return ExprError();
74 DeclRefExpr *DRE = new (S.Context)
75 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
76 if (HadMultipleCandidates)
77 DRE->setHadMultipleCandidates(true);
78
80 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
81 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
82 S.ResolveExceptionSpec(Loc, FPT);
83 DRE->setType(Fn->getType());
84 }
85 }
86 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
87 CK_FunctionToPointerDecay);
88}
89
90static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
91 bool InOverloadResolution,
93 bool CStyle,
94 bool AllowObjCWritebackConversion);
95
97 QualType &ToType,
98 bool InOverloadResolution,
100 bool CStyle);
102IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
104 OverloadCandidateSet& Conversions,
105 AllowedExplicit AllowExplicit,
106 bool AllowObjCConversionOnExplicit);
107
110 const StandardConversionSequence& SCS1,
111 const StandardConversionSequence& SCS2);
112
115 const StandardConversionSequence& SCS1,
116 const StandardConversionSequence& SCS2);
117
120 const StandardConversionSequence& SCS1,
121 const StandardConversionSequence& SCS2);
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
126 static const ImplicitConversionRank Rank[] = {
153 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
154 // it was omitted by the patch that added
155 // ICK_Zero_Event_Conversion
156 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
157 // it was omitted by the patch that added
158 // ICK_Zero_Queue_Conversion
163 };
164 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
165 return Rank[(int)Kind];
166}
167
168/// GetImplicitConversionName - Return the name of this kind of
169/// implicit conversion.
171 static const char *const Name[] = {
172 "No conversion",
173 "Lvalue-to-rvalue",
174 "Array-to-pointer",
175 "Function-to-pointer",
176 "Function pointer conversion",
177 "Qualification",
178 "Integral promotion",
179 "Floating point promotion",
180 "Complex promotion",
181 "Integral conversion",
182 "Floating conversion",
183 "Complex conversion",
184 "Floating-integral conversion",
185 "Pointer conversion",
186 "Pointer-to-member conversion",
187 "Boolean conversion",
188 "Compatible-types conversion",
189 "Derived-to-base conversion",
190 "Vector conversion",
191 "SVE Vector conversion",
192 "RVV Vector conversion",
193 "Vector splat",
194 "Complex-real conversion",
195 "Block Pointer conversion",
196 "Transparent Union Conversion",
197 "Writeback conversion",
198 "OpenCL Zero Event Conversion",
199 "OpenCL Zero Queue Conversion",
200 "C specific type conversion",
201 "Incompatible pointer conversion",
202 "Fixed point conversion",
203 "HLSL vector truncation",
204 };
205 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
206 return Name[Kind];
207}
208
209/// StandardConversionSequence - Set the standard conversion
210/// sequence to the identity conversion.
218 ReferenceBinding = false;
219 DirectBinding = false;
220 IsLvalueReference = true;
221 BindsToFunctionLvalue = false;
222 BindsToRvalue = false;
225 CopyConstructor = nullptr;
226}
227
228/// getRank - Retrieve the rank of this standard conversion sequence
229/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
230/// implicit conversions.
233 if (GetConversionRank(First) > Rank)
234 Rank = GetConversionRank(First);
235 if (GetConversionRank(Second) > Rank)
237 if (GetConversionRank(Element) > Rank)
239 if (GetConversionRank(Third) > Rank)
240 Rank = GetConversionRank(Third);
241 return Rank;
242}
243
244/// isPointerConversionToBool - Determines whether this conversion is
245/// a conversion of a pointer or pointer-to-member to bool. This is
246/// used as part of the ranking of standard conversion sequences
247/// (C++ 13.3.3.2p4).
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer or function-to-pointer implicit conversions, so
251 // check for their presence as well as checking whether FromType is
252 // a pointer.
253 if (getToType(1)->isBooleanType() &&
254 (getFromType()->isPointerType() ||
255 getFromType()->isMemberPointerType() ||
256 getFromType()->isObjCObjectPointerType() ||
257 getFromType()->isBlockPointerType() ||
259 return true;
260
261 return false;
262}
263
264/// isPointerConversionToVoidPointer - Determines whether this
265/// conversion is a conversion of a pointer to a void pointer. This is
266/// used as part of the ranking of standard conversion sequences (C++
267/// 13.3.3.2p4).
268bool
271 QualType FromType = getFromType();
272 QualType ToType = getToType(1);
273
274 // Note that FromType has not necessarily been transformed by the
275 // array-to-pointer implicit conversion, so check for its presence
276 // and redo the conversion to get a pointer.
278 FromType = Context.getArrayDecayedType(FromType);
279
280 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
281 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
282 return ToPtrType->getPointeeType()->isVoidType();
283
284 return false;
285}
286
287/// Skip any implicit casts which could be either part of a narrowing conversion
288/// or after one in an implicit conversion.
290 const Expr *Converted) {
291 // We can have cleanups wrapping the converted expression; these need to be
292 // preserved so that destructors run if necessary.
293 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
294 Expr *Inner =
295 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
296 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
297 EWC->getObjects());
298 }
299
300 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
301 switch (ICE->getCastKind()) {
302 case CK_NoOp:
303 case CK_IntegralCast:
304 case CK_IntegralToBoolean:
305 case CK_IntegralToFloating:
306 case CK_BooleanToSignedIntegral:
307 case CK_FloatingToIntegral:
308 case CK_FloatingToBoolean:
309 case CK_FloatingCast:
310 Converted = ICE->getSubExpr();
311 continue;
312
313 default:
314 return Converted;
315 }
316 }
317
318 return Converted;
319}
320
321/// Check if this standard conversion sequence represents a narrowing
322/// conversion, according to C++11 [dcl.init.list]p7.
323///
324/// \param Ctx The AST context.
325/// \param Converted The result of applying this standard conversion sequence.
326/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
327/// value of the expression prior to the narrowing conversion.
328/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
329/// type of the expression prior to the narrowing conversion.
330/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
331/// from floating point types to integral types should be ignored.
333 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
334 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
335 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
336 "narrowing check outside C++");
337
338 // C++11 [dcl.init.list]p7:
339 // A narrowing conversion is an implicit conversion ...
340 QualType FromType = getToType(0);
341 QualType ToType = getToType(1);
342
343 // A conversion to an enumeration type is narrowing if the conversion to
344 // the underlying type is narrowing. This only arises for expressions of
345 // the form 'Enum{init}'.
346 if (auto *ET = ToType->getAs<EnumType>())
347 ToType = ET->getDecl()->getIntegerType();
348
349 switch (Second) {
350 // 'bool' is an integral type; dispatch to the right place to handle it.
352 if (FromType->isRealFloatingType())
353 goto FloatingIntegralConversion;
355 goto IntegralConversion;
356 // -- from a pointer type or pointer-to-member type to bool, or
357 return NK_Type_Narrowing;
358
359 // -- from a floating-point type to an integer type, or
360 //
361 // -- from an integer type or unscoped enumeration type to a floating-point
362 // type, except where the source is a constant expression and the actual
363 // value after conversion will fit into the target type and will produce
364 // the original value when converted back to the original type, or
366 FloatingIntegralConversion:
367 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
368 return NK_Type_Narrowing;
369 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
370 ToType->isRealFloatingType()) {
371 if (IgnoreFloatToIntegralConversion)
372 return NK_Not_Narrowing;
373 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
374 assert(Initializer && "Unknown conversion expression");
375
376 // If it's value-dependent, we can't tell whether it's narrowing.
377 if (Initializer->isValueDependent())
379
380 if (std::optional<llvm::APSInt> IntConstantValue =
381 Initializer->getIntegerConstantExpr(Ctx)) {
382 // Convert the integer to the floating type.
383 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
384 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
385 llvm::APFloat::rmNearestTiesToEven);
386 // And back.
387 llvm::APSInt ConvertedValue = *IntConstantValue;
388 bool ignored;
389 Result.convertToInteger(ConvertedValue,
390 llvm::APFloat::rmTowardZero, &ignored);
391 // If the resulting value is different, this was a narrowing conversion.
392 if (*IntConstantValue != ConvertedValue) {
393 ConstantValue = APValue(*IntConstantValue);
394 ConstantType = Initializer->getType();
396 }
397 } else {
398 // Variables are always narrowings.
400 }
401 }
402 return NK_Not_Narrowing;
403
404 // -- from long double to double or float, or from double to float, except
405 // where the source is a constant expression and the actual value after
406 // conversion is within the range of values that can be represented (even
407 // if it cannot be represented exactly), or
409 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
410 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
411 // FromType is larger than ToType.
412 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
413
414 // If it's value-dependent, we can't tell whether it's narrowing.
415 if (Initializer->isValueDependent())
417
419 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
420 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
421 // Constant!
422 if (Ctx.getLangOpts().C23)
423 ConstantValue = R.Val;
424 assert(ConstantValue.isFloat());
425 llvm::APFloat FloatVal = ConstantValue.getFloat();
426 // Convert the source value into the target type.
427 bool ignored;
428 llvm::APFloat Converted = FloatVal;
429 llvm::APFloat::opStatus ConvertStatus =
430 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
431 llvm::APFloat::rmNearestTiesToEven, &ignored);
432 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
433 llvm::APFloat::rmNearestTiesToEven, &ignored);
434 if (Ctx.getLangOpts().C23) {
435 if (FloatVal.isNaN() && Converted.isNaN() &&
436 !FloatVal.isSignaling() && !Converted.isSignaling()) {
437 // Quiet NaNs are considered the same value, regardless of
438 // payloads.
439 return NK_Not_Narrowing;
440 }
441 // For normal values, check exact equality.
442 if (!Converted.bitwiseIsEqual(FloatVal)) {
443 ConstantType = Initializer->getType();
445 }
446 } else {
447 // If there was no overflow, the source value is within the range of
448 // values that can be represented.
449 if (ConvertStatus & llvm::APFloat::opOverflow) {
450 ConstantType = Initializer->getType();
452 }
453 }
454 } else {
456 }
457 }
458 return NK_Not_Narrowing;
459
460 // -- from an integer type or unscoped enumeration type to an integer type
461 // that cannot represent all the values of the original type, except where
462 // the source is a constant expression and the actual value after
463 // conversion will fit into the target type and will produce the original
464 // value when converted back to the original type.
466 IntegralConversion: {
467 assert(FromType->isIntegralOrUnscopedEnumerationType());
468 assert(ToType->isIntegralOrUnscopedEnumerationType());
469 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
470 const unsigned FromWidth = Ctx.getIntWidth(FromType);
471 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
472 const unsigned ToWidth = Ctx.getIntWidth(ToType);
473
474 if (FromWidth > ToWidth ||
475 (FromWidth == ToWidth && FromSigned != ToSigned) ||
476 (FromSigned && !ToSigned)) {
477 // Not all values of FromType can be represented in ToType.
478 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
479
480 // If it's value-dependent, we can't tell whether it's narrowing.
481 if (Initializer->isValueDependent())
483
484 std::optional<llvm::APSInt> OptInitializerValue;
485 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
486 // Such conversions on variables are always narrowing.
488 }
489 llvm::APSInt &InitializerValue = *OptInitializerValue;
490 bool Narrowing = false;
491 if (FromWidth < ToWidth) {
492 // Negative -> unsigned is narrowing. Otherwise, more bits is never
493 // narrowing.
494 if (InitializerValue.isSigned() && InitializerValue.isNegative())
495 Narrowing = true;
496 } else {
497 // Add a bit to the InitializerValue so we don't have to worry about
498 // signed vs. unsigned comparisons.
499 InitializerValue = InitializerValue.extend(
500 InitializerValue.getBitWidth() + 1);
501 // Convert the initializer to and from the target width and signed-ness.
502 llvm::APSInt ConvertedValue = InitializerValue;
503 ConvertedValue = ConvertedValue.trunc(ToWidth);
504 ConvertedValue.setIsSigned(ToSigned);
505 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
506 ConvertedValue.setIsSigned(InitializerValue.isSigned());
507 // If the result is different, this was a narrowing conversion.
508 if (ConvertedValue != InitializerValue)
509 Narrowing = true;
510 }
511 if (Narrowing) {
512 ConstantType = Initializer->getType();
513 ConstantValue = APValue(InitializerValue);
515 }
516 }
517 return NK_Not_Narrowing;
518 }
519 case ICK_Complex_Real:
520 if (FromType->isComplexType() && !ToType->isComplexType())
521 return NK_Type_Narrowing;
522 return NK_Not_Narrowing;
523
525 if (Ctx.getLangOpts().C23) {
526 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
528 if (Initializer->EvaluateAsRValue(R, Ctx)) {
529 ConstantValue = R.Val;
530 assert(ConstantValue.isFloat());
531 llvm::APFloat FloatVal = ConstantValue.getFloat();
532 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
533 // value, the unqualified versions of the type of the initializer and
534 // the corresponding real type of the object declared shall be
535 // compatible.
536 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
537 ConstantType = Initializer->getType();
539 }
540 }
541 }
542 return NK_Not_Narrowing;
543 default:
544 // Other kinds of conversions are not narrowings.
545 return NK_Not_Narrowing;
546 }
547}
548
549/// dump - Print this standard conversion sequence to standard
550/// error. Useful for debugging overloading issues.
551LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
552 raw_ostream &OS = llvm::errs();
553 bool PrintedSomething = false;
554 if (First != ICK_Identity) {
556 PrintedSomething = true;
557 }
558
559 if (Second != ICK_Identity) {
560 if (PrintedSomething) {
561 OS << " -> ";
562 }
564
565 if (CopyConstructor) {
566 OS << " (by copy constructor)";
567 } else if (DirectBinding) {
568 OS << " (direct reference binding)";
569 } else if (ReferenceBinding) {
570 OS << " (reference binding)";
571 }
572 PrintedSomething = true;
573 }
574
575 if (Third != ICK_Identity) {
576 if (PrintedSomething) {
577 OS << " -> ";
578 }
580 PrintedSomething = true;
581 }
582
583 if (!PrintedSomething) {
584 OS << "No conversions required";
585 }
586}
587
588/// dump - Print this user-defined conversion sequence to standard
589/// error. Useful for debugging overloading issues.
591 raw_ostream &OS = llvm::errs();
592 if (Before.First || Before.Second || Before.Third) {
593 Before.dump();
594 OS << " -> ";
595 }
597 OS << '\'' << *ConversionFunction << '\'';
598 else
599 OS << "aggregate initialization";
600 if (After.First || After.Second || After.Third) {
601 OS << " -> ";
602 After.dump();
603 }
604}
605
606/// dump - Print this implicit conversion sequence to standard
607/// error. Useful for debugging overloading issues.
609 raw_ostream &OS = llvm::errs();
611 OS << "Worst list element conversion: ";
612 switch (ConversionKind) {
614 OS << "Standard conversion: ";
615 Standard.dump();
616 break;
618 OS << "User-defined conversion: ";
620 break;
622 OS << "Ellipsis conversion";
623 break;
625 OS << "Ambiguous conversion";
626 break;
627 case BadConversion:
628 OS << "Bad conversion";
629 break;
630 }
631
632 OS << "\n";
633}
634
636 new (&conversions()) ConversionSet();
637}
638
640 conversions().~ConversionSet();
641}
642
643void
648}
649
650namespace {
651 // Structure used by DeductionFailureInfo to store
652 // template argument information.
653 struct DFIArguments {
654 TemplateArgument FirstArg;
655 TemplateArgument SecondArg;
656 };
657 // Structure used by DeductionFailureInfo to store
658 // template parameter and template argument information.
659 struct DFIParamWithArguments : DFIArguments {
660 TemplateParameter Param;
661 };
662 // Structure used by DeductionFailureInfo to store template argument
663 // information and the index of the problematic call argument.
664 struct DFIDeducedMismatchArgs : DFIArguments {
665 TemplateArgumentList *TemplateArgs;
666 unsigned CallArgIndex;
667 };
668 // Structure used by DeductionFailureInfo to store information about
669 // unsatisfied constraints.
670 struct CNSInfo {
671 TemplateArgumentList *TemplateArgs;
672 ConstraintSatisfaction Satisfaction;
673 };
674}
675
676/// Convert from Sema's representation of template deduction information
677/// to the form used in overload-candidate information.
681 TemplateDeductionInfo &Info) {
683 Result.Result = static_cast<unsigned>(TDK);
684 Result.HasDiagnostic = false;
685 switch (TDK) {
692 Result.Data = nullptr;
693 break;
694
697 Result.Data = Info.Param.getOpaqueValue();
698 break;
699
702 // FIXME: Should allocate from normal heap so that we can free this later.
703 auto *Saved = new (Context) DFIDeducedMismatchArgs;
704 Saved->FirstArg = Info.FirstArg;
705 Saved->SecondArg = Info.SecondArg;
706 Saved->TemplateArgs = Info.takeSugared();
707 Saved->CallArgIndex = Info.CallArgIndex;
708 Result.Data = Saved;
709 break;
710 }
711
713 // FIXME: Should allocate from normal heap so that we can free this later.
714 DFIArguments *Saved = new (Context) DFIArguments;
715 Saved->FirstArg = Info.FirstArg;
716 Saved->SecondArg = Info.SecondArg;
717 Result.Data = Saved;
718 break;
719 }
720
722 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
725 // FIXME: Should allocate from normal heap so that we can free this later.
726 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
727 Saved->Param = Info.Param;
728 Saved->FirstArg = Info.FirstArg;
729 Saved->SecondArg = Info.SecondArg;
730 Result.Data = Saved;
731 break;
732 }
733
735 Result.Data = Info.takeSugared();
736 if (Info.hasSFINAEDiagnostic()) {
740 Result.HasDiagnostic = true;
741 }
742 break;
743
745 CNSInfo *Saved = new (Context) CNSInfo;
746 Saved->TemplateArgs = Info.takeSugared();
747 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
748 Result.Data = Saved;
749 break;
750 }
751
755 llvm_unreachable("not a deduction failure");
756 }
757
758 return Result;
759}
760
762 switch (static_cast<TemplateDeductionResult>(Result)) {
772 break;
773
780 // FIXME: Destroy the data?
781 Data = nullptr;
782 break;
783
785 // FIXME: Destroy the template argument list?
786 Data = nullptr;
788 Diag->~PartialDiagnosticAt();
789 HasDiagnostic = false;
790 }
791 break;
792
794 // FIXME: Destroy the template argument list?
795 Data = nullptr;
797 Diag->~PartialDiagnosticAt();
798 HasDiagnostic = false;
799 }
800 break;
801
802 // Unhandled
805 break;
806 }
807}
808
810 if (HasDiagnostic)
811 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
812 return nullptr;
813}
814
816 switch (static_cast<TemplateDeductionResult>(Result)) {
829 return TemplateParameter();
830
833 return TemplateParameter::getFromOpaqueValue(Data);
834
838 return static_cast<DFIParamWithArguments*>(Data)->Param;
839
840 // Unhandled
843 break;
844 }
845
846 return TemplateParameter();
847}
848
850 switch (static_cast<TemplateDeductionResult>(Result)) {
864 return nullptr;
865
868 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
869
871 return static_cast<TemplateArgumentList*>(Data);
872
874 return static_cast<CNSInfo*>(Data)->TemplateArgs;
875
876 // Unhandled
879 break;
880 }
881
882 return nullptr;
883}
884
886 switch (static_cast<TemplateDeductionResult>(Result)) {
898 return nullptr;
899
906 return &static_cast<DFIArguments*>(Data)->FirstArg;
907
908 // Unhandled
911 break;
912 }
913
914 return nullptr;
915}
916
918 switch (static_cast<TemplateDeductionResult>(Result)) {
931 return nullptr;
932
938 return &static_cast<DFIArguments*>(Data)->SecondArg;
939
940 // Unhandled
943 break;
944 }
945
946 return nullptr;
947}
948
949std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
950 switch (static_cast<TemplateDeductionResult>(Result)) {
953 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
954
955 default:
956 return std::nullopt;
957 }
958}
959
961 const FunctionDecl *Y) {
962 if (!X || !Y)
963 return false;
964 if (X->getNumParams() != Y->getNumParams())
965 return false;
966 // FIXME: when do rewritten comparison operators
967 // with explicit object parameters correspond?
968 // https://cplusplus.github.io/CWG/issues/2797.html
969 for (unsigned I = 0; I < X->getNumParams(); ++I)
970 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
971 Y->getParamDecl(I)->getType()))
972 return false;
973 if (auto *FTX = X->getDescribedFunctionTemplate()) {
974 auto *FTY = Y->getDescribedFunctionTemplate();
975 if (!FTY)
976 return false;
977 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
978 FTY->getTemplateParameters()))
979 return false;
980 }
981 return true;
982}
983
985 Expr *FirstOperand, FunctionDecl *EqFD) {
986 assert(EqFD->getOverloadedOperator() ==
987 OverloadedOperatorKind::OO_EqualEqual);
988 // C++2a [over.match.oper]p4:
989 // A non-template function or function template F named operator== is a
990 // rewrite target with first operand o unless a search for the name operator!=
991 // in the scope S from the instantiation context of the operator expression
992 // finds a function or function template that would correspond
993 // ([basic.scope.scope]) to F if its name were operator==, where S is the
994 // scope of the class type of o if F is a class member, and the namespace
995 // scope of which F is a member otherwise. A function template specialization
996 // named operator== is a rewrite target if its function template is a rewrite
997 // target.
999 OverloadedOperatorKind::OO_ExclaimEqual);
1000 if (isa<CXXMethodDecl>(EqFD)) {
1001 // If F is a class member, search scope is class type of first operand.
1002 QualType RHS = FirstOperand->getType();
1003 auto *RHSRec = RHS->getAs<RecordType>();
1004 if (!RHSRec)
1005 return true;
1006 LookupResult Members(S, NotEqOp, OpLoc,
1008 S.LookupQualifiedName(Members, RHSRec->getDecl());
1009 Members.suppressAccessDiagnostics();
1010 for (NamedDecl *Op : Members)
1011 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1012 return false;
1013 return true;
1014 }
1015 // Otherwise the search scope is the namespace scope of which F is a member.
1016 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1017 auto *NotEqFD = Op->getAsFunction();
1018 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1019 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1020 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1022 cast<Decl>(Op->getLexicalDeclContext())))
1023 return false;
1024 }
1025 return true;
1026}
1027
1031 return false;
1032 return Op == OO_EqualEqual || Op == OO_Spaceship;
1033}
1034
1036 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1037 auto Op = FD->getOverloadedOperator();
1038 if (!allowsReversed(Op))
1039 return false;
1040 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1041 assert(OriginalArgs.size() == 2);
1043 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1044 return false;
1045 }
1046 // Don't bother adding a reversed candidate that can never be a better
1047 // match than the non-reversed version.
1048 return FD->getNumNonObjectParams() != 2 ||
1050 FD->getParamDecl(1)->getType()) ||
1051 FD->hasAttr<EnableIfAttr>();
1052}
1053
1054void OverloadCandidateSet::destroyCandidates() {
1055 for (iterator i = begin(), e = end(); i != e; ++i) {
1056 for (auto &C : i->Conversions)
1057 C.~ImplicitConversionSequence();
1058 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1059 i->DeductionFailure.Destroy();
1060 }
1061}
1062
1064 destroyCandidates();
1065 SlabAllocator.Reset();
1066 NumInlineBytesUsed = 0;
1067 Candidates.clear();
1068 Functions.clear();
1069 Kind = CSK;
1070}
1071
1072namespace {
1073 class UnbridgedCastsSet {
1074 struct Entry {
1075 Expr **Addr;
1076 Expr *Saved;
1077 };
1078 SmallVector<Entry, 2> Entries;
1079
1080 public:
1081 void save(Sema &S, Expr *&E) {
1082 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1083 Entry entry = { &E, E };
1084 Entries.push_back(entry);
1085 E = S.stripARCUnbridgedCast(E);
1086 }
1087
1088 void restore() {
1090 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1091 *i->Addr = i->Saved;
1092 }
1093 };
1094}
1095
1096/// checkPlaceholderForOverload - Do any interesting placeholder-like
1097/// preprocessing on the given expression.
1098///
1099/// \param unbridgedCasts a collection to which to add unbridged casts;
1100/// without this, they will be immediately diagnosed as errors
1101///
1102/// Return true on unrecoverable error.
1103static bool
1105 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1106 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1107 // We can't handle overloaded expressions here because overload
1108 // resolution might reasonably tweak them.
1109 if (placeholder->getKind() == BuiltinType::Overload) return false;
1110
1111 // If the context potentially accepts unbridged ARC casts, strip
1112 // the unbridged cast and add it to the collection for later restoration.
1113 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1114 unbridgedCasts) {
1115 unbridgedCasts->save(S, E);
1116 return false;
1117 }
1118
1119 // Go ahead and check everything else.
1120 ExprResult result = S.CheckPlaceholderExpr(E);
1121 if (result.isInvalid())
1122 return true;
1123
1124 E = result.get();
1125 return false;
1126 }
1127
1128 // Nothing to do.
1129 return false;
1130}
1131
1132/// checkArgPlaceholdersForOverload - Check a set of call operands for
1133/// placeholders.
1135 UnbridgedCastsSet &unbridged) {
1136 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1137 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1138 return true;
1139
1140 return false;
1141}
1142
1143/// Determine whether the given New declaration is an overload of the
1144/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1145/// New and Old cannot be overloaded, e.g., if New has the same signature as
1146/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1147/// functions (or function templates) at all. When it does return Ovl_Match or
1148/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1149/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1150/// declaration.
1151///
1152/// Example: Given the following input:
1153///
1154/// void f(int, float); // #1
1155/// void f(int, int); // #2
1156/// int f(int, int); // #3
1157///
1158/// When we process #1, there is no previous declaration of "f", so IsOverload
1159/// will not be used.
1160///
1161/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1162/// the parameter types, we see that #1 and #2 are overloaded (since they have
1163/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1164/// unchanged.
1165///
1166/// When we process #3, Old is an overload set containing #1 and #2. We compare
1167/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1168/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1169/// functions are not part of the signature), IsOverload returns Ovl_Match and
1170/// MatchedDecl will be set to point to the FunctionDecl for #2.
1171///
1172/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1173/// by a using declaration. The rules for whether to hide shadow declarations
1174/// ignore some properties which otherwise figure into a function template's
1175/// signature.
1178 NamedDecl *&Match, bool NewIsUsingDecl) {
1179 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1180 I != E; ++I) {
1181 NamedDecl *OldD = *I;
1182
1183 bool OldIsUsingDecl = false;
1184 if (isa<UsingShadowDecl>(OldD)) {
1185 OldIsUsingDecl = true;
1186
1187 // We can always introduce two using declarations into the same
1188 // context, even if they have identical signatures.
1189 if (NewIsUsingDecl) continue;
1190
1191 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1192 }
1193
1194 // A using-declaration does not conflict with another declaration
1195 // if one of them is hidden.
1196 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1197 continue;
1198
1199 // If either declaration was introduced by a using declaration,
1200 // we'll need to use slightly different rules for matching.
1201 // Essentially, these rules are the normal rules, except that
1202 // function templates hide function templates with different
1203 // return types or template parameter lists.
1204 bool UseMemberUsingDeclRules =
1205 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1206 !New->getFriendObjectKind();
1207
1208 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1209 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1210 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1211 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1212 continue;
1213 }
1214
1215 if (!isa<FunctionTemplateDecl>(OldD) &&
1216 !shouldLinkPossiblyHiddenDecl(*I, New))
1217 continue;
1218
1219 Match = *I;
1220 return Ovl_Match;
1221 }
1222
1223 // Builtins that have custom typechecking or have a reference should
1224 // not be overloadable or redeclarable.
1225 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1226 Match = *I;
1227 return Ovl_NonFunction;
1228 }
1229 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1230 // We can overload with these, which can show up when doing
1231 // redeclaration checks for UsingDecls.
1232 assert(Old.getLookupKind() == LookupUsingDeclName);
1233 } else if (isa<TagDecl>(OldD)) {
1234 // We can always overload with tags by hiding them.
1235 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1236 // Optimistically assume that an unresolved using decl will
1237 // overload; if it doesn't, we'll have to diagnose during
1238 // template instantiation.
1239 //
1240 // Exception: if the scope is dependent and this is not a class
1241 // member, the using declaration can only introduce an enumerator.
1242 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1243 Match = *I;
1244 return Ovl_NonFunction;
1245 }
1246 } else {
1247 // (C++ 13p1):
1248 // Only function declarations can be overloaded; object and type
1249 // declarations cannot be overloaded.
1250 Match = *I;
1251 return Ovl_NonFunction;
1252 }
1253 }
1254
1255 // C++ [temp.friend]p1:
1256 // For a friend function declaration that is not a template declaration:
1257 // -- if the name of the friend is a qualified or unqualified template-id,
1258 // [...], otherwise
1259 // -- if the name of the friend is a qualified-id and a matching
1260 // non-template function is found in the specified class or namespace,
1261 // the friend declaration refers to that function, otherwise,
1262 // -- if the name of the friend is a qualified-id and a matching function
1263 // template is found in the specified class or namespace, the friend
1264 // declaration refers to the deduced specialization of that function
1265 // template, otherwise
1266 // -- the name shall be an unqualified-id [...]
1267 // If we get here for a qualified friend declaration, we've just reached the
1268 // third bullet. If the type of the friend is dependent, skip this lookup
1269 // until instantiation.
1270 if (New->getFriendObjectKind() && New->getQualifier() &&
1273 !New->getType()->isDependentType()) {
1274 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1275 TemplateSpecResult.addAllDecls(Old);
1276 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1277 /*QualifiedFriend*/true)) {
1278 New->setInvalidDecl();
1279 return Ovl_Overload;
1280 }
1281
1282 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1283 return Ovl_Match;
1284 }
1285
1286 return Ovl_Overload;
1287}
1288
1289static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1290 FunctionDecl *Old,
1291 bool UseMemberUsingDeclRules,
1292 bool ConsiderCudaAttrs,
1293 bool UseOverrideRules = false) {
1294 // C++ [basic.start.main]p2: This function shall not be overloaded.
1295 if (New->isMain())
1296 return false;
1297
1298 // MSVCRT user defined entry points cannot be overloaded.
1299 if (New->isMSVCRTEntryPoint())
1300 return false;
1301
1304
1305 // C++ [temp.fct]p2:
1306 // A function template can be overloaded with other function templates
1307 // and with normal (non-template) functions.
1308 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1309 return true;
1310
1311 // Is the function New an overload of the function Old?
1312 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1313 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1314
1315 // Compare the signatures (C++ 1.3.10) of the two functions to
1316 // determine whether they are overloads. If we find any mismatch
1317 // in the signature, they are overloads.
1318
1319 // If either of these functions is a K&R-style function (no
1320 // prototype), then we consider them to have matching signatures.
1321 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1322 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1323 return false;
1324
1325 const auto *OldType = cast<FunctionProtoType>(OldQType);
1326 const auto *NewType = cast<FunctionProtoType>(NewQType);
1327
1328 // The signature of a function includes the types of its
1329 // parameters (C++ 1.3.10), which includes the presence or absence
1330 // of the ellipsis; see C++ DR 357).
1331 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1332 return true;
1333
1334 // For member-like friends, the enclosing class is part of the signature.
1335 if ((New->isMemberLikeConstrainedFriend() ||
1338 return true;
1339
1340 // Compare the parameter lists.
1341 // This can only be done once we have establish that friend functions
1342 // inhabit the same context, otherwise we might tried to instantiate
1343 // references to non-instantiated entities during constraint substitution.
1344 // GH78101.
1345 if (NewTemplate) {
1346 // C++ [temp.over.link]p4:
1347 // The signature of a function template consists of its function
1348 // signature, its return type and its template parameter list. The names
1349 // of the template parameters are significant only for establishing the
1350 // relationship between the template parameters and the rest of the
1351 // signature.
1352 //
1353 // We check the return type and template parameter lists for function
1354 // templates first; the remaining checks follow.
1355 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1356 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1357 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1358 bool SameReturnType = SemaRef.Context.hasSameType(
1360 // FIXME(GH58571): Match template parameter list even for non-constrained
1361 // template heads. This currently ensures that the code prior to C++20 is
1362 // not newly broken.
1363 bool ConstraintsInTemplateHead =
1366 // C++ [namespace.udecl]p11:
1367 // The set of declarations named by a using-declarator that inhabits a
1368 // class C does not include member functions and member function
1369 // templates of a base class that "correspond" to (and thus would
1370 // conflict with) a declaration of a function or function template in
1371 // C.
1372 // Comparing return types is not required for the "correspond" check to
1373 // decide whether a member introduced by a shadow declaration is hidden.
1374 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1375 !SameTemplateParameterList)
1376 return true;
1377 if (!UseMemberUsingDeclRules &&
1378 (!SameTemplateParameterList || !SameReturnType))
1379 return true;
1380 }
1381
1382 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1383 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1384
1385 int OldParamsOffset = 0;
1386 int NewParamsOffset = 0;
1387
1388 // When determining if a method is an overload from a base class, act as if
1389 // the implicit object parameter are of the same type.
1390
1391 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1393 return Q;
1394
1395 // We do not allow overloading based off of '__restrict'.
1396 Q.removeRestrict();
1397
1398 // We may not have applied the implicit const for a constexpr member
1399 // function yet (because we haven't yet resolved whether this is a static
1400 // or non-static member function). Add it now, on the assumption that this
1401 // is a redeclaration of OldMethod.
1402 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1403 (M->isConstexpr() || M->isConsteval()) &&
1404 !isa<CXXConstructorDecl>(NewMethod))
1405 Q.addConst();
1406 return Q;
1407 };
1408
1409 auto CompareType = [&](QualType Base, QualType D) {
1410 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1411 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1412
1413 auto DS = D.getNonReferenceType().getCanonicalType().split();
1414 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1415
1416 if (BS.Quals != DS.Quals)
1417 return false;
1418
1419 if (OldMethod->isImplicitObjectMemberFunction() &&
1420 OldMethod->getParent() != NewMethod->getParent()) {
1421 QualType ParentType =
1422 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1424 if (ParentType.getTypePtr() != BS.Ty)
1425 return false;
1426 BS.Ty = DS.Ty;
1427 }
1428
1429 // FIXME: should we ignore some type attributes here?
1430 if (BS.Ty != DS.Ty)
1431 return false;
1432
1433 if (Base->isLValueReferenceType())
1434 return D->isLValueReferenceType();
1435 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1436 };
1437
1438 // If the function is a class member, its signature includes the
1439 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1440 auto DiagnoseInconsistentRefQualifiers = [&]() {
1441 if (SemaRef.LangOpts.CPlusPlus23)
1442 return false;
1443 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1444 return false;
1445 if (OldMethod->isExplicitObjectMemberFunction() ||
1446 NewMethod->isExplicitObjectMemberFunction())
1447 return false;
1448 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1449 NewMethod->getRefQualifier() == RQ_None)) {
1450 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1451 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1452 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1453 return true;
1454 }
1455 return false;
1456 };
1457
1458 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1459 OldParamsOffset++;
1460 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1461 NewParamsOffset++;
1462
1463 if (OldType->getNumParams() - OldParamsOffset !=
1464 NewType->getNumParams() - NewParamsOffset ||
1466 {OldType->param_type_begin() + OldParamsOffset,
1467 OldType->param_type_end()},
1468 {NewType->param_type_begin() + NewParamsOffset,
1469 NewType->param_type_end()},
1470 nullptr)) {
1471 return true;
1472 }
1473
1474 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1475 !OldMethod->isStatic()) {
1476 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1477 const CXXMethodDecl *New) {
1478 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1479 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1480
1481 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1482 return F->getRefQualifier() == RQ_None &&
1483 !F->isExplicitObjectMemberFunction();
1484 };
1485
1486 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1487 CompareType(OldObjectType.getNonReferenceType(),
1488 NewObjectType.getNonReferenceType()))
1489 return true;
1490 return CompareType(OldObjectType, NewObjectType);
1491 }(OldMethod, NewMethod);
1492
1493 if (!HaveCorrespondingObjectParameters) {
1494 if (DiagnoseInconsistentRefQualifiers())
1495 return true;
1496 // CWG2554
1497 // and, if at least one is an explicit object member function, ignoring
1498 // object parameters
1499 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1500 !OldMethod->isExplicitObjectMemberFunction()))
1501 return true;
1502 }
1503 }
1504
1505 if (!UseOverrideRules) {
1506 Expr *NewRC = New->getTrailingRequiresClause(),
1507 *OldRC = Old->getTrailingRequiresClause();
1508 if ((NewRC != nullptr) != (OldRC != nullptr))
1509 return true;
1510
1511 if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1512 return true;
1513 }
1514
1515 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1516 NewMethod->isImplicitObjectMemberFunction()) {
1517 if (DiagnoseInconsistentRefQualifiers())
1518 return true;
1519 }
1520
1521 // Though pass_object_size is placed on parameters and takes an argument, we
1522 // consider it to be a function-level modifier for the sake of function
1523 // identity. Either the function has one or more parameters with
1524 // pass_object_size or it doesn't.
1527 return true;
1528
1529 // enable_if attributes are an order-sensitive part of the signature.
1531 NewI = New->specific_attr_begin<EnableIfAttr>(),
1532 NewE = New->specific_attr_end<EnableIfAttr>(),
1533 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1534 OldE = Old->specific_attr_end<EnableIfAttr>();
1535 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1536 if (NewI == NewE || OldI == OldE)
1537 return true;
1538 llvm::FoldingSetNodeID NewID, OldID;
1539 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1540 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1541 if (NewID != OldID)
1542 return true;
1543 }
1544
1545 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1546 // Don't allow overloading of destructors. (In theory we could, but it
1547 // would be a giant change to clang.)
1548 if (!isa<CXXDestructorDecl>(New)) {
1549 Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(New),
1550 OldTarget = SemaRef.IdentifyCUDATarget(Old);
1551 if (NewTarget != Sema::CFT_InvalidTarget) {
1552 assert((OldTarget != Sema::CFT_InvalidTarget) &&
1553 "Unexpected invalid target.");
1554
1555 // Allow overloading of functions with same signature and different CUDA
1556 // target attributes.
1557 if (NewTarget != OldTarget)
1558 return true;
1559 }
1560 }
1561 }
1562
1563 // The signatures match; this is not an overload.
1564 return false;
1565}
1566
1568 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1569 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1570 ConsiderCudaAttrs);
1571}
1572
1574 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1575 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1576 /*UseMemberUsingDeclRules=*/false,
1577 /*ConsiderCudaAttrs=*/true,
1578 /*UseOverrideRules=*/true);
1579}
1580
1581/// Tries a user-defined conversion from From to ToType.
1582///
1583/// Produces an implicit conversion sequence for when a standard conversion
1584/// is not an option. See TryImplicitConversion for more information.
1587 bool SuppressUserConversions,
1588 AllowedExplicit AllowExplicit,
1589 bool InOverloadResolution,
1590 bool CStyle,
1591 bool AllowObjCWritebackConversion,
1592 bool AllowObjCConversionOnExplicit) {
1594
1595 if (SuppressUserConversions) {
1596 // We're not in the case above, so there is no conversion that
1597 // we can perform.
1599 return ICS;
1600 }
1601
1602 // Attempt user-defined conversion.
1603 OverloadCandidateSet Conversions(From->getExprLoc(),
1605 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1606 Conversions, AllowExplicit,
1607 AllowObjCConversionOnExplicit)) {
1608 case OR_Success:
1609 case OR_Deleted:
1610 ICS.setUserDefined();
1611 // C++ [over.ics.user]p4:
1612 // A conversion of an expression of class type to the same class
1613 // type is given Exact Match rank, and a conversion of an
1614 // expression of class type to a base class of that type is
1615 // given Conversion rank, in spite of the fact that a copy
1616 // constructor (i.e., a user-defined conversion function) is
1617 // called for those cases.
1618 if (CXXConstructorDecl *Constructor
1619 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1620 QualType FromCanon
1622 QualType ToCanon
1624 if (Constructor->isCopyConstructor() &&
1625 (FromCanon == ToCanon ||
1626 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1627 // Turn this into a "standard" conversion sequence, so that it
1628 // gets ranked with standard conversion sequences.
1630 ICS.setStandard();
1632 ICS.Standard.setFromType(From->getType());
1633 ICS.Standard.setAllToTypes(ToType);
1634 ICS.Standard.CopyConstructor = Constructor;
1635 ICS.Standard.FoundCopyConstructor = Found;
1636 if (ToCanon != FromCanon)
1638 }
1639 }
1640 break;
1641
1642 case OR_Ambiguous:
1643 ICS.setAmbiguous();
1644 ICS.Ambiguous.setFromType(From->getType());
1645 ICS.Ambiguous.setToType(ToType);
1646 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1647 Cand != Conversions.end(); ++Cand)
1648 if (Cand->Best)
1649 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1650 break;
1651
1652 // Fall through.
1655 break;
1656 }
1657
1658 return ICS;
1659}
1660
1661/// TryImplicitConversion - Attempt to perform an implicit conversion
1662/// from the given expression (Expr) to the given type (ToType). This
1663/// function returns an implicit conversion sequence that can be used
1664/// to perform the initialization. Given
1665///
1666/// void f(float f);
1667/// void g(int i) { f(i); }
1668///
1669/// this routine would produce an implicit conversion sequence to
1670/// describe the initialization of f from i, which will be a standard
1671/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1672/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1673//
1674/// Note that this routine only determines how the conversion can be
1675/// performed; it does not actually perform the conversion. As such,
1676/// it will not produce any diagnostics if no conversion is available,
1677/// but will instead return an implicit conversion sequence of kind
1678/// "BadConversion".
1679///
1680/// If @p SuppressUserConversions, then user-defined conversions are
1681/// not permitted.
1682/// If @p AllowExplicit, then explicit user-defined conversions are
1683/// permitted.
1684///
1685/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1686/// writeback conversion, which allows __autoreleasing id* parameters to
1687/// be initialized with __strong id* or __weak id* arguments.
1690 bool SuppressUserConversions,
1691 AllowedExplicit AllowExplicit,
1692 bool InOverloadResolution,
1693 bool CStyle,
1694 bool AllowObjCWritebackConversion,
1695 bool AllowObjCConversionOnExplicit) {
1697 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1698 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1699 ICS.setStandard();
1700 return ICS;
1701 }
1702
1703 if (!S.getLangOpts().CPlusPlus) {
1705 return ICS;
1706 }
1707
1708 // C++ [over.ics.user]p4:
1709 // A conversion of an expression of class type to the same class
1710 // type is given Exact Match rank, and a conversion of an
1711 // expression of class type to a base class of that type is
1712 // given Conversion rank, in spite of the fact that a copy/move
1713 // constructor (i.e., a user-defined conversion function) is
1714 // called for those cases.
1715 QualType FromType = From->getType();
1716 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1717 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1718 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1719 ICS.setStandard();
1721 ICS.Standard.setFromType(FromType);
1722 ICS.Standard.setAllToTypes(ToType);
1723
1724 // We don't actually check at this point whether there is a valid
1725 // copy/move constructor, since overloading just assumes that it
1726 // exists. When we actually perform initialization, we'll find the
1727 // appropriate constructor to copy the returned object, if needed.
1728 ICS.Standard.CopyConstructor = nullptr;
1729
1730 // Determine whether this is considered a derived-to-base conversion.
1731 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1733
1734 return ICS;
1735 }
1736
1737 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1738 AllowExplicit, InOverloadResolution, CStyle,
1739 AllowObjCWritebackConversion,
1740 AllowObjCConversionOnExplicit);
1741}
1742
1745 bool SuppressUserConversions,
1746 AllowedExplicit AllowExplicit,
1747 bool InOverloadResolution,
1748 bool CStyle,
1749 bool AllowObjCWritebackConversion) {
1750 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1751 AllowExplicit, InOverloadResolution, CStyle,
1752 AllowObjCWritebackConversion,
1753 /*AllowObjCConversionOnExplicit=*/false);
1754}
1755
1756/// PerformImplicitConversion - Perform an implicit conversion of the
1757/// expression From to the type ToType. Returns the
1758/// converted expression. Flavor is the kind of conversion we're
1759/// performing, used in the error message. If @p AllowExplicit,
1760/// explicit user-defined conversions are permitted.
1762 AssignmentAction Action,
1763 bool AllowExplicit) {
1764 if (checkPlaceholderForOverload(*this, From))
1765 return ExprError();
1766
1767 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1768 bool AllowObjCWritebackConversion
1769 = getLangOpts().ObjCAutoRefCount &&
1770 (Action == AA_Passing || Action == AA_Sending);
1771 if (getLangOpts().ObjC)
1772 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1773 From->getType(), From);
1775 *this, From, ToType,
1776 /*SuppressUserConversions=*/false,
1777 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1778 /*InOverloadResolution=*/false,
1779 /*CStyle=*/false, AllowObjCWritebackConversion,
1780 /*AllowObjCConversionOnExplicit=*/false);
1781 return PerformImplicitConversion(From, ToType, ICS, Action);
1782}
1783
1784/// Determine whether the conversion from FromType to ToType is a valid
1785/// conversion that strips "noexcept" or "noreturn" off the nested function
1786/// type.
1788 QualType &ResultTy) {
1789 if (Context.hasSameUnqualifiedType(FromType, ToType))
1790 return false;
1791
1792 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1793 // or F(t noexcept) -> F(t)
1794 // where F adds one of the following at most once:
1795 // - a pointer
1796 // - a member pointer
1797 // - a block pointer
1798 // Changes here need matching changes in FindCompositePointerType.
1799 CanQualType CanTo = Context.getCanonicalType(ToType);
1800 CanQualType CanFrom = Context.getCanonicalType(FromType);
1801 Type::TypeClass TyClass = CanTo->getTypeClass();
1802 if (TyClass != CanFrom->getTypeClass()) return false;
1803 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1804 if (TyClass == Type::Pointer) {
1805 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1806 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1807 } else if (TyClass == Type::BlockPointer) {
1808 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1809 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1810 } else if (TyClass == Type::MemberPointer) {
1811 auto ToMPT = CanTo.castAs<MemberPointerType>();
1812 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1813 // A function pointer conversion cannot change the class of the function.
1814 if (ToMPT->getClass() != FromMPT->getClass())
1815 return false;
1816 CanTo = ToMPT->getPointeeType();
1817 CanFrom = FromMPT->getPointeeType();
1818 } else {
1819 return false;
1820 }
1821
1822 TyClass = CanTo->getTypeClass();
1823 if (TyClass != CanFrom->getTypeClass()) return false;
1824 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1825 return false;
1826 }
1827
1828 const auto *FromFn = cast<FunctionType>(CanFrom);
1829 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1830
1831 const auto *ToFn = cast<FunctionType>(CanTo);
1832 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1833
1834 bool Changed = false;
1835
1836 // Drop 'noreturn' if not present in target type.
1837 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1838 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1839 Changed = true;
1840 }
1841
1842 // Drop 'noexcept' if not present in target type.
1843 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1844 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1845 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1846 FromFn = cast<FunctionType>(
1847 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1848 EST_None)
1849 .getTypePtr());
1850 Changed = true;
1851 }
1852
1853 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1854 // only if the ExtParameterInfo lists of the two function prototypes can be
1855 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1857 bool CanUseToFPT, CanUseFromFPT;
1858 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1859 CanUseFromFPT, NewParamInfos) &&
1860 CanUseToFPT && !CanUseFromFPT) {
1861 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1862 ExtInfo.ExtParameterInfos =
1863 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1864 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1865 FromFPT->getParamTypes(), ExtInfo);
1866 FromFn = QT->getAs<FunctionType>();
1867 Changed = true;
1868 }
1869 }
1870
1871 if (!Changed)
1872 return false;
1873
1874 assert(QualType(FromFn, 0).isCanonical());
1875 if (QualType(FromFn, 0) != CanTo) return false;
1876
1877 ResultTy = ToType;
1878 return true;
1879}
1880
1881/// Determine whether the conversion from FromType to ToType is a valid
1882/// floating point conversion.
1883///
1884static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1885 QualType ToType) {
1886 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1887 return false;
1888 // FIXME: disable conversions between long double, __ibm128 and __float128
1889 // if their representation is different until there is back end support
1890 // We of course allow this conversion if long double is really double.
1891
1892 // Conversions between bfloat16 and float16 are currently not supported.
1893 if ((FromType->isBFloat16Type() &&
1894 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1895 (ToType->isBFloat16Type() &&
1896 (FromType->isFloat16Type() || FromType->isHalfType())))
1897 return false;
1898
1899 // Conversions between IEEE-quad and IBM-extended semantics are not
1900 // permitted.
1901 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1902 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1903 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1904 &ToSem == &llvm::APFloat::IEEEquad()) ||
1905 (&FromSem == &llvm::APFloat::IEEEquad() &&
1906 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1907 return false;
1908 return true;
1909}
1910
1911static bool IsVectorElementConversion(Sema &S, QualType FromType,
1912 QualType ToType,
1913 ImplicitConversionKind &ICK, Expr *From) {
1914 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1915 return true;
1916
1917 if (S.IsFloatingPointPromotion(FromType, ToType)) {
1919 return true;
1920 }
1921
1922 if (IsFloatingPointConversion(S, FromType, ToType)) {
1924 return true;
1925 }
1926
1927 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1929 return true;
1930 }
1931
1932 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1934 ToType->isRealFloatingType())) {
1936 return true;
1937 }
1938
1939 if (S.IsIntegralPromotion(From, FromType, ToType)) {
1941 return true;
1942 }
1943
1944 if (FromType->isIntegralOrUnscopedEnumerationType() &&
1945 ToType->isIntegralType(S.Context)) {
1947 return true;
1948 }
1949
1950 return false;
1951}
1952
1953/// Determine whether the conversion from FromType to ToType is a valid
1954/// vector conversion.
1955///
1956/// \param ICK Will be set to the vector conversion kind, if this is a vector
1957/// conversion.
1958static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1960 ImplicitConversionKind &ElConv, Expr *From,
1961 bool InOverloadResolution, bool CStyle) {
1962 // We need at least one of these types to be a vector type to have a vector
1963 // conversion.
1964 if (!ToType->isVectorType() && !FromType->isVectorType())
1965 return false;
1966
1967 // Identical types require no conversions.
1968 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1969 return false;
1970
1971 // There are no conversions between extended vector types, only identity.
1972 if (ToType->isExtVectorType()) {
1973 if (FromType->isExtVectorType()) {
1974 // HLSL allows implicit truncation of vector types.
1975 if (S.getLangOpts().HLSL) {
1976 unsigned FromElts = FromType->getAs<VectorType>()->getNumElements();
1977 unsigned ToElts = ToType->getAs<VectorType>()->getNumElements();
1978 if (FromElts < ToElts)
1979 return false;
1980 if (FromElts == ToElts)
1981 ICK = ICK_Identity;
1982 else
1984
1985 QualType FromElTy = FromType->getAs<VectorType>()->getElementType();
1986 QualType ToElTy = ToType->getAs<VectorType>()->getElementType();
1987 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
1988 return true;
1989 return IsVectorElementConversion(S, FromElTy, ToElTy, ElConv, From);
1990 }
1991 // There are no conversions between extended vector types other than the
1992 // identity conversion.
1993 return false;
1994 }
1995
1996 // Vector splat from any arithmetic type to a vector.
1997 if (FromType->isArithmeticType()) {
1998 ICK = ICK_Vector_Splat;
1999 return true;
2000 }
2001 }
2002
2003 if (ToType->isSVESizelessBuiltinType() ||
2004 FromType->isSVESizelessBuiltinType())
2005 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2006 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2008 return true;
2009 }
2010
2011 if (ToType->isRVVSizelessBuiltinType() ||
2012 FromType->isRVVSizelessBuiltinType())
2013 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2014 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2016 return true;
2017 }
2018
2019 // We can perform the conversion between vector types in the following cases:
2020 // 1)vector types are equivalent AltiVec and GCC vector types
2021 // 2)lax vector conversions are permitted and the vector types are of the
2022 // same size
2023 // 3)the destination type does not have the ARM MVE strict-polymorphism
2024 // attribute, which inhibits lax vector conversion for overload resolution
2025 // only
2026 if (ToType->isVectorType() && FromType->isVectorType()) {
2027 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2028 (S.isLaxVectorConversion(FromType, ToType) &&
2029 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2030 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2031 S.isLaxVectorConversion(FromType, ToType) &&
2032 S.anyAltivecTypes(FromType, ToType) &&
2033 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2034 !InOverloadResolution && !CStyle) {
2035 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2036 << FromType << ToType;
2037 }
2039 return true;
2040 }
2041 }
2042
2043 return false;
2044}
2045
2046static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2047 bool InOverloadResolution,
2049 bool CStyle);
2050
2051/// IsStandardConversion - Determines whether there is a standard
2052/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2053/// expression From to the type ToType. Standard conversion sequences
2054/// only consider non-class types; for conversions that involve class
2055/// types, use TryImplicitConversion. If a conversion exists, SCS will
2056/// contain the standard conversion sequence required to perform this
2057/// conversion and this routine will return true. Otherwise, this
2058/// routine will return false and the value of SCS is unspecified.
2059static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2060 bool InOverloadResolution,
2062 bool CStyle,
2063 bool AllowObjCWritebackConversion) {
2064 QualType FromType = From->getType();
2065
2066 // Standard conversions (C++ [conv])
2068 SCS.IncompatibleObjC = false;
2069 SCS.setFromType(FromType);
2070 SCS.CopyConstructor = nullptr;
2071
2072 // There are no standard conversions for class types in C++, so
2073 // abort early. When overloading in C, however, we do permit them.
2074 if (S.getLangOpts().CPlusPlus &&
2075 (FromType->isRecordType() || ToType->isRecordType()))
2076 return false;
2077
2078 // The first conversion can be an lvalue-to-rvalue conversion,
2079 // array-to-pointer conversion, or function-to-pointer conversion
2080 // (C++ 4p1).
2081
2082 if (FromType == S.Context.OverloadTy) {
2083 DeclAccessPair AccessPair;
2084 if (FunctionDecl *Fn
2085 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2086 AccessPair)) {
2087 // We were able to resolve the address of the overloaded function,
2088 // so we can convert to the type of that function.
2089 FromType = Fn->getType();
2090 SCS.setFromType(FromType);
2091
2092 // we can sometimes resolve &foo<int> regardless of ToType, so check
2093 // if the type matches (identity) or we are converting to bool
2095 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2096 QualType resultTy;
2097 // if the function type matches except for [[noreturn]], it's ok
2098 if (!S.IsFunctionConversion(FromType,
2099 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2100 // otherwise, only a boolean conversion is standard
2101 if (!ToType->isBooleanType())
2102 return false;
2103 }
2104
2105 // Check if the "from" expression is taking the address of an overloaded
2106 // function and recompute the FromType accordingly. Take advantage of the
2107 // fact that non-static member functions *must* have such an address-of
2108 // expression.
2109 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2110 if (Method && !Method->isStatic() &&
2111 !Method->isExplicitObjectMemberFunction()) {
2112 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2113 "Non-unary operator on non-static member address");
2114 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2115 == UO_AddrOf &&
2116 "Non-address-of operator on non-static member address");
2117 const Type *ClassType
2119 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2120 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2121 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2122 UO_AddrOf &&
2123 "Non-address-of operator for overloaded function expression");
2124 FromType = S.Context.getPointerType(FromType);
2125 }
2126 } else {
2127 return false;
2128 }
2129 }
2130 // Lvalue-to-rvalue conversion (C++11 4.1):
2131 // A glvalue (3.10) of a non-function, non-array type T can
2132 // be converted to a prvalue.
2133 bool argIsLValue = From->isGLValue();
2134 if (argIsLValue &&
2135 !FromType->isFunctionType() && !FromType->isArrayType() &&
2136 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2138
2139 // C11 6.3.2.1p2:
2140 // ... if the lvalue has atomic type, the value has the non-atomic version
2141 // of the type of the lvalue ...
2142 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2143 FromType = Atomic->getValueType();
2144
2145 // If T is a non-class type, the type of the rvalue is the
2146 // cv-unqualified version of T. Otherwise, the type of the rvalue
2147 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2148 // just strip the qualifiers because they don't matter.
2149 FromType = FromType.getUnqualifiedType();
2150 } else if (FromType->isArrayType()) {
2151 // Array-to-pointer conversion (C++ 4.2)
2153
2154 // An lvalue or rvalue of type "array of N T" or "array of unknown
2155 // bound of T" can be converted to an rvalue of type "pointer to
2156 // T" (C++ 4.2p1).
2157 FromType = S.Context.getArrayDecayedType(FromType);
2158
2159 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2160 // This conversion is deprecated in C++03 (D.4)
2162
2163 // For the purpose of ranking in overload resolution
2164 // (13.3.3.1.1), this conversion is considered an
2165 // array-to-pointer conversion followed by a qualification
2166 // conversion (4.4). (C++ 4.2p2)
2167 SCS.Second = ICK_Identity;
2170 SCS.setAllToTypes(FromType);
2171 return true;
2172 }
2173 } else if (FromType->isFunctionType() && argIsLValue) {
2174 // Function-to-pointer conversion (C++ 4.3).
2176
2177 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2178 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2180 return false;
2181
2182 // An lvalue of function type T can be converted to an rvalue of
2183 // type "pointer to T." The result is a pointer to the
2184 // function. (C++ 4.3p1).
2185 FromType = S.Context.getPointerType(FromType);
2186 } else {
2187 // We don't require any conversions for the first step.
2188 SCS.First = ICK_Identity;
2189 }
2190 SCS.setToType(0, FromType);
2191
2192 // The second conversion can be an integral promotion, floating
2193 // point promotion, integral conversion, floating point conversion,
2194 // floating-integral conversion, pointer conversion,
2195 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2196 // For overloading in C, this can also be a "compatible-type"
2197 // conversion.
2198 bool IncompatibleObjC = false;
2201 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2202 // The unqualified versions of the types are the same: there's no
2203 // conversion to do.
2204 SCS.Second = ICK_Identity;
2205 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2206 // Integral promotion (C++ 4.5).
2208 FromType = ToType.getUnqualifiedType();
2209 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2210 // Floating point promotion (C++ 4.6).
2212 FromType = ToType.getUnqualifiedType();
2213 } else if (S.IsComplexPromotion(FromType, ToType)) {
2214 // Complex promotion (Clang extension)
2216 FromType = ToType.getUnqualifiedType();
2217 } else if (ToType->isBooleanType() &&
2218 (FromType->isArithmeticType() ||
2219 FromType->isAnyPointerType() ||
2220 FromType->isBlockPointerType() ||
2221 FromType->isMemberPointerType())) {
2222 // Boolean conversions (C++ 4.12).
2224 FromType = S.Context.BoolTy;
2225 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2226 ToType->isIntegralType(S.Context)) {
2227 // Integral conversions (C++ 4.7).
2229 FromType = ToType.getUnqualifiedType();
2230 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2231 // Complex conversions (C99 6.3.1.6)
2233 FromType = ToType.getUnqualifiedType();
2234 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2235 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2236 // Complex-real conversions (C99 6.3.1.7)
2238 FromType = ToType.getUnqualifiedType();
2239 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2240 // Floating point conversions (C++ 4.8).
2242 FromType = ToType.getUnqualifiedType();
2243 } else if ((FromType->isRealFloatingType() &&
2244 ToType->isIntegralType(S.Context)) ||
2246 ToType->isRealFloatingType())) {
2247
2248 // Floating-integral conversions (C++ 4.9).
2250 FromType = ToType.getUnqualifiedType();
2251 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2253 } else if (AllowObjCWritebackConversion &&
2254 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2256 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2257 FromType, IncompatibleObjC)) {
2258 // Pointer conversions (C++ 4.10).
2260 SCS.IncompatibleObjC = IncompatibleObjC;
2261 FromType = FromType.getUnqualifiedType();
2262 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2263 InOverloadResolution, FromType)) {
2264 // Pointer to member conversions (4.11).
2266 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, ElementICK,
2267 From, InOverloadResolution, CStyle)) {
2268 SCS.Second = SecondICK;
2269 SCS.Element = ElementICK;
2270 FromType = ToType.getUnqualifiedType();
2271 } else if (!S.getLangOpts().CPlusPlus &&
2272 S.Context.typesAreCompatible(ToType, FromType)) {
2273 // Compatible conversions (Clang extension for C function overloading)
2275 FromType = ToType.getUnqualifiedType();
2277 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2279 FromType = ToType;
2280 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2281 CStyle)) {
2282 // tryAtomicConversion has updated the standard conversion sequence
2283 // appropriately.
2284 return true;
2285 } else if (ToType->isEventT() &&
2287 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2289 FromType = ToType;
2290 } else if (ToType->isQueueT() &&
2292 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2294 FromType = ToType;
2295 } else if (ToType->isSamplerT() &&
2298 FromType = ToType;
2299 } else if ((ToType->isFixedPointType() &&
2300 FromType->isConvertibleToFixedPointType()) ||
2301 (FromType->isFixedPointType() &&
2302 ToType->isConvertibleToFixedPointType())) {
2304 FromType = ToType;
2305 } else {
2306 // No second conversion required.
2307 SCS.Second = ICK_Identity;
2308 }
2309 SCS.setToType(1, FromType);
2310
2311 // The third conversion can be a function pointer conversion or a
2312 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2313 bool ObjCLifetimeConversion;
2314 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2315 // Function pointer conversions (removing 'noexcept') including removal of
2316 // 'noreturn' (Clang extension).
2318 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2319 ObjCLifetimeConversion)) {
2321 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2322 FromType = ToType;
2323 } else {
2324 // No conversion required
2325 SCS.Third = ICK_Identity;
2326 }
2327
2328 // C++ [over.best.ics]p6:
2329 // [...] Any difference in top-level cv-qualification is
2330 // subsumed by the initialization itself and does not constitute
2331 // a conversion. [...]
2332 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2333 QualType CanonTo = S.Context.getCanonicalType(ToType);
2334 if (CanonFrom.getLocalUnqualifiedType()
2335 == CanonTo.getLocalUnqualifiedType() &&
2336 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2337 FromType = ToType;
2338 CanonFrom = CanonTo;
2339 }
2340
2341 SCS.setToType(2, FromType);
2342
2343 if (CanonFrom == CanonTo)
2344 return true;
2345
2346 // If we have not converted the argument type to the parameter type,
2347 // this is a bad conversion sequence, unless we're resolving an overload in C.
2348 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2349 return false;
2350
2351 ExprResult ER = ExprResult{From};
2354 /*Diagnose=*/false,
2355 /*DiagnoseCFAudited=*/false,
2356 /*ConvertRHS=*/false);
2357 ImplicitConversionKind SecondConv;
2358 switch (Conv) {
2359 case Sema::Compatible:
2360 SecondConv = ICK_C_Only_Conversion;
2361 break;
2362 // For our purposes, discarding qualifiers is just as bad as using an
2363 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2364 // qualifiers, as well.
2369 break;
2370 default:
2371 return false;
2372 }
2373
2374 // First can only be an lvalue conversion, so we pretend that this was the
2375 // second conversion. First should already be valid from earlier in the
2376 // function.
2377 SCS.Second = SecondConv;
2378 SCS.setToType(1, ToType);
2379
2380 // Third is Identity, because Second should rank us worse than any other
2381 // conversion. This could also be ICK_Qualification, but it's simpler to just
2382 // lump everything in with the second conversion, and we don't gain anything
2383 // from making this ICK_Qualification.
2384 SCS.Third = ICK_Identity;
2385 SCS.setToType(2, ToType);
2386 return true;
2387}
2388
2389static bool
2391 QualType &ToType,
2392 bool InOverloadResolution,
2394 bool CStyle) {
2395
2396 const RecordType *UT = ToType->getAsUnionType();
2397 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2398 return false;
2399 // The field to initialize within the transparent union.
2400 RecordDecl *UD = UT->getDecl();
2401 // It's compatible if the expression matches any of the fields.
2402 for (const auto *it : UD->fields()) {
2403 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2404 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2405 ToType = it->getType();
2406 return true;
2407 }
2408 }
2409 return false;
2410}
2411
2412/// IsIntegralPromotion - Determines whether the conversion from the
2413/// expression From (whose potentially-adjusted type is FromType) to
2414/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2415/// sets PromotedType to the promoted type.
2416bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2417 const BuiltinType *To = ToType->getAs<BuiltinType>();
2418 // All integers are built-in.
2419 if (!To) {
2420 return false;
2421 }
2422
2423 // An rvalue of type char, signed char, unsigned char, short int, or
2424 // unsigned short int can be converted to an rvalue of type int if
2425 // int can represent all the values of the source type; otherwise,
2426 // the source rvalue can be converted to an rvalue of type unsigned
2427 // int (C++ 4.5p1).
2428 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2429 !FromType->isEnumeralType()) {
2430 if ( // We can promote any signed, promotable integer type to an int
2431 (FromType->isSignedIntegerType() ||
2432 // We can promote any unsigned integer type whose size is
2433 // less than int to an int.
2434 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2435 return To->getKind() == BuiltinType::Int;
2436 }
2437
2438 return To->getKind() == BuiltinType::UInt;
2439 }
2440
2441 // C++11 [conv.prom]p3:
2442 // A prvalue of an unscoped enumeration type whose underlying type is not
2443 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2444 // following types that can represent all the values of the enumeration
2445 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2446 // unsigned int, long int, unsigned long int, long long int, or unsigned
2447 // long long int. If none of the types in that list can represent all the
2448 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2449 // type can be converted to an rvalue a prvalue of the extended integer type
2450 // with lowest integer conversion rank (4.13) greater than the rank of long
2451 // long in which all the values of the enumeration can be represented. If
2452 // there are two such extended types, the signed one is chosen.
2453 // C++11 [conv.prom]p4:
2454 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2455 // can be converted to a prvalue of its underlying type. Moreover, if
2456 // integral promotion can be applied to its underlying type, a prvalue of an
2457 // unscoped enumeration type whose underlying type is fixed can also be
2458 // converted to a prvalue of the promoted underlying type.
2459 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2460 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2461 // provided for a scoped enumeration.
2462 if (FromEnumType->getDecl()->isScoped())
2463 return false;
2464
2465 // We can perform an integral promotion to the underlying type of the enum,
2466 // even if that's not the promoted type. Note that the check for promoting
2467 // the underlying type is based on the type alone, and does not consider
2468 // the bitfield-ness of the actual source expression.
2469 if (FromEnumType->getDecl()->isFixed()) {
2470 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2471 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2472 IsIntegralPromotion(nullptr, Underlying, ToType);
2473 }
2474
2475 // We have already pre-calculated the promotion type, so this is trivial.
2476 if (ToType->isIntegerType() &&
2477 isCompleteType(From->getBeginLoc(), FromType))
2478 return Context.hasSameUnqualifiedType(
2479 ToType, FromEnumType->getDecl()->getPromotionType());
2480
2481 // C++ [conv.prom]p5:
2482 // If the bit-field has an enumerated type, it is treated as any other
2483 // value of that type for promotion purposes.
2484 //
2485 // ... so do not fall through into the bit-field checks below in C++.
2486 if (getLangOpts().CPlusPlus)
2487 return false;
2488 }
2489
2490 // C++0x [conv.prom]p2:
2491 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2492 // to an rvalue a prvalue of the first of the following types that can
2493 // represent all the values of its underlying type: int, unsigned int,
2494 // long int, unsigned long int, long long int, or unsigned long long int.
2495 // If none of the types in that list can represent all the values of its
2496 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2497 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2498 // type.
2499 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2500 ToType->isIntegerType()) {
2501 // Determine whether the type we're converting from is signed or
2502 // unsigned.
2503 bool FromIsSigned = FromType->isSignedIntegerType();
2504 uint64_t FromSize = Context.getTypeSize(FromType);
2505
2506 // The types we'll try to promote to, in the appropriate
2507 // order. Try each of these types.
2508 QualType PromoteTypes[6] = {
2509 Context.IntTy, Context.UnsignedIntTy,
2510 Context.LongTy, Context.UnsignedLongTy ,
2511 Context.LongLongTy, Context.UnsignedLongLongTy
2512 };
2513 for (int Idx = 0; Idx < 6; ++Idx) {
2514 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2515 if (FromSize < ToSize ||
2516 (FromSize == ToSize &&
2517 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2518 // We found the type that we can promote to. If this is the
2519 // type we wanted, we have a promotion. Otherwise, no
2520 // promotion.
2521 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2522 }
2523 }
2524 }
2525
2526 // An rvalue for an integral bit-field (9.6) can be converted to an
2527 // rvalue of type int if int can represent all the values of the
2528 // bit-field; otherwise, it can be converted to unsigned int if
2529 // unsigned int can represent all the values of the bit-field. If
2530 // the bit-field is larger yet, no integral promotion applies to
2531 // it. If the bit-field has an enumerated type, it is treated as any
2532 // other value of that type for promotion purposes (C++ 4.5p3).
2533 // FIXME: We should delay checking of bit-fields until we actually perform the
2534 // conversion.
2535 //
2536 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2537 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2538 // bit-fields and those whose underlying type is larger than int) for GCC
2539 // compatibility.
2540 if (From) {
2541 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2542 std::optional<llvm::APSInt> BitWidth;
2543 if (FromType->isIntegralType(Context) &&
2544 (BitWidth =
2545 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2546 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2547 ToSize = Context.getTypeSize(ToType);
2548
2549 // Are we promoting to an int from a bitfield that fits in an int?
2550 if (*BitWidth < ToSize ||
2551 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2552 return To->getKind() == BuiltinType::Int;
2553 }
2554
2555 // Are we promoting to an unsigned int from an unsigned bitfield
2556 // that fits into an unsigned int?
2557 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2558 return To->getKind() == BuiltinType::UInt;
2559 }
2560
2561 return false;
2562 }
2563 }
2564 }
2565
2566 // An rvalue of type bool can be converted to an rvalue of type int,
2567 // with false becoming zero and true becoming one (C++ 4.5p4).
2568 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2569 return true;
2570 }
2571
2572 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2573 // integral type.
2574 if (Context.getLangOpts().HLSL)
2575 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2576
2577 return false;
2578}
2579
2580/// IsFloatingPointPromotion - Determines whether the conversion from
2581/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2582/// returns true and sets PromotedType to the promoted type.
2584 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2585 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2586 /// An rvalue of type float can be converted to an rvalue of type
2587 /// double. (C++ 4.6p1).
2588 if (FromBuiltin->getKind() == BuiltinType::Float &&
2589 ToBuiltin->getKind() == BuiltinType::Double)
2590 return true;
2591
2592 // C99 6.3.1.5p1:
2593 // When a float is promoted to double or long double, or a
2594 // double is promoted to long double [...].
2595 if (!getLangOpts().CPlusPlus &&
2596 (FromBuiltin->getKind() == BuiltinType::Float ||
2597 FromBuiltin->getKind() == BuiltinType::Double) &&
2598 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2599 ToBuiltin->getKind() == BuiltinType::Float128 ||
2600 ToBuiltin->getKind() == BuiltinType::Ibm128))
2601 return true;
2602
2603 // Half can be promoted to float.
2604 if (!getLangOpts().NativeHalfType &&
2605 FromBuiltin->getKind() == BuiltinType::Half &&
2606 ToBuiltin->getKind() == BuiltinType::Float)
2607 return true;
2608 }
2609
2610 return false;
2611}
2612
2613/// Determine if a conversion is a complex promotion.
2614///
2615/// A complex promotion is defined as a complex -> complex conversion
2616/// where the conversion between the underlying real types is a
2617/// floating-point or integral promotion.
2619 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2620 if (!FromComplex)
2621 return false;
2622
2623 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2624 if (!ToComplex)
2625 return false;
2626
2627 return IsFloatingPointPromotion(FromComplex->getElementType(),
2628 ToComplex->getElementType()) ||
2629 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2630 ToComplex->getElementType());
2631}
2632
2633/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2634/// the pointer type FromPtr to a pointer to type ToPointee, with the
2635/// same type qualifiers as FromPtr has on its pointee type. ToType,
2636/// if non-empty, will be a pointer to ToType that may or may not have
2637/// the right set of qualifiers on its pointee.
2638///
2639static QualType
2641 QualType ToPointee, QualType ToType,
2642 ASTContext &Context,
2643 bool StripObjCLifetime = false) {
2644 assert((FromPtr->getTypeClass() == Type::Pointer ||
2645 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2646 "Invalid similarly-qualified pointer type");
2647
2648 /// Conversions to 'id' subsume cv-qualifier conversions.
2649 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2650 return ToType.getUnqualifiedType();
2651
2652 QualType CanonFromPointee
2653 = Context.getCanonicalType(FromPtr->getPointeeType());
2654 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2655 Qualifiers Quals = CanonFromPointee.getQualifiers();
2656
2657 if (StripObjCLifetime)
2658 Quals.removeObjCLifetime();
2659
2660 // Exact qualifier match -> return the pointer type we're converting to.
2661 if (CanonToPointee.getLocalQualifiers() == Quals) {
2662 // ToType is exactly what we need. Return it.
2663 if (!ToType.isNull())
2664 return ToType.getUnqualifiedType();
2665
2666 // Build a pointer to ToPointee. It has the right qualifiers
2667 // already.
2668 if (isa<ObjCObjectPointerType>(ToType))
2669 return Context.getObjCObjectPointerType(ToPointee);
2670 return Context.getPointerType(ToPointee);
2671 }
2672
2673 // Just build a canonical type that has the right qualifiers.
2674 QualType QualifiedCanonToPointee
2675 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2676
2677 if (isa<ObjCObjectPointerType>(ToType))
2678 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2679 return Context.getPointerType(QualifiedCanonToPointee);
2680}
2681
2683 bool InOverloadResolution,
2684 ASTContext &Context) {
2685 // Handle value-dependent integral null pointer constants correctly.
2686 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2687 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2689 return !InOverloadResolution;
2690
2691 return Expr->isNullPointerConstant(Context,
2692 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2694}
2695
2696/// IsPointerConversion - Determines whether the conversion of the
2697/// expression From, which has the (possibly adjusted) type FromType,
2698/// can be converted to the type ToType via a pointer conversion (C++
2699/// 4.10). If so, returns true and places the converted type (that
2700/// might differ from ToType in its cv-qualifiers at some level) into
2701/// ConvertedType.
2702///
2703/// This routine also supports conversions to and from block pointers
2704/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2705/// pointers to interfaces. FIXME: Once we've determined the
2706/// appropriate overloading rules for Objective-C, we may want to
2707/// split the Objective-C checks into a different routine; however,
2708/// GCC seems to consider all of these conversions to be pointer
2709/// conversions, so for now they live here. IncompatibleObjC will be
2710/// set if the conversion is an allowed Objective-C conversion that
2711/// should result in a warning.
2713 bool InOverloadResolution,
2714 QualType& ConvertedType,
2715 bool &IncompatibleObjC) {
2716 IncompatibleObjC = false;
2717 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2718 IncompatibleObjC))
2719 return true;
2720
2721 // Conversion from a null pointer constant to any Objective-C pointer type.
2722 if (ToType->isObjCObjectPointerType() &&
2723 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2724 ConvertedType = ToType;
2725 return true;
2726 }
2727
2728 // Blocks: Block pointers can be converted to void*.
2729 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2730 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2731 ConvertedType = ToType;
2732 return true;
2733 }
2734 // Blocks: A null pointer constant can be converted to a block
2735 // pointer type.
2736 if (ToType->isBlockPointerType() &&
2737 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2738 ConvertedType = ToType;
2739 return true;
2740 }
2741
2742 // If the left-hand-side is nullptr_t, the right side can be a null
2743 // pointer constant.
2744 if (ToType->isNullPtrType() &&
2745 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2746 ConvertedType = ToType;
2747 return true;
2748 }
2749
2750 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2751 if (!ToTypePtr)
2752 return false;
2753
2754 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2755 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2756 ConvertedType = ToType;
2757 return true;
2758 }
2759
2760 // Beyond this point, both types need to be pointers
2761 // , including objective-c pointers.
2762 QualType ToPointeeType = ToTypePtr->getPointeeType();
2763 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2764 !getLangOpts().ObjCAutoRefCount) {
2765 ConvertedType = BuildSimilarlyQualifiedPointerType(
2766 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2767 Context);
2768 return true;
2769 }
2770 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2771 if (!FromTypePtr)
2772 return false;
2773
2774 QualType FromPointeeType = FromTypePtr->getPointeeType();
2775
2776 // If the unqualified pointee types are the same, this can't be a
2777 // pointer conversion, so don't do all of the work below.
2778 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2779 return false;
2780
2781 // An rvalue of type "pointer to cv T," where T is an object type,
2782 // can be converted to an rvalue of type "pointer to cv void" (C++
2783 // 4.10p2).
2784 if (FromPointeeType->isIncompleteOrObjectType() &&
2785 ToPointeeType->isVoidType()) {
2786 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2787 ToPointeeType,
2788 ToType, Context,
2789 /*StripObjCLifetime=*/true);
2790 return true;
2791 }
2792
2793 // MSVC allows implicit function to void* type conversion.
2794 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2795 ToPointeeType->isVoidType()) {
2796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2797 ToPointeeType,
2798 ToType, Context);
2799 return true;
2800 }
2801
2802 // When we're overloading in C, we allow a special kind of pointer
2803 // conversion for compatible-but-not-identical pointee types.
2804 if (!getLangOpts().CPlusPlus &&
2805 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2806 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2807 ToPointeeType,
2808 ToType, Context);
2809 return true;
2810 }
2811
2812 // C++ [conv.ptr]p3:
2813 //
2814 // An rvalue of type "pointer to cv D," where D is a class type,
2815 // can be converted to an rvalue of type "pointer to cv B," where
2816 // B is a base class (clause 10) of D. If B is an inaccessible
2817 // (clause 11) or ambiguous (10.2) base class of D, a program that
2818 // necessitates this conversion is ill-formed. The result of the
2819 // conversion is a pointer to the base class sub-object of the
2820 // derived class object. The null pointer value is converted to
2821 // the null pointer value of the destination type.
2822 //
2823 // Note that we do not check for ambiguity or inaccessibility
2824 // here. That is handled by CheckPointerConversion.
2825 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2826 ToPointeeType->isRecordType() &&
2827 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2828 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2829 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2830 ToPointeeType,
2831 ToType, Context);
2832 return true;
2833 }
2834
2835 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2836 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2837 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2838 ToPointeeType,
2839 ToType, Context);
2840 return true;
2841 }
2842
2843 return false;
2844}
2845
2846/// Adopt the given qualifiers for the given type.
2848 Qualifiers TQs = T.getQualifiers();
2849
2850 // Check whether qualifiers already match.
2851 if (TQs == Qs)
2852 return T;
2853
2854 if (Qs.compatiblyIncludes(TQs))
2855 return Context.getQualifiedType(T, Qs);
2856
2857 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2858}
2859
2860/// isObjCPointerConversion - Determines whether this is an
2861/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2862/// with the same arguments and return values.
2864 QualType& ConvertedType,
2865 bool &IncompatibleObjC) {
2866 if (!getLangOpts().ObjC)
2867 return false;
2868
2869 // The set of qualifiers on the type we're converting from.
2870 Qualifiers FromQualifiers = FromType.getQualifiers();
2871
2872 // First, we handle all conversions on ObjC object pointer types.
2873 const ObjCObjectPointerType* ToObjCPtr =
2874 ToType->getAs<ObjCObjectPointerType>();
2875 const ObjCObjectPointerType *FromObjCPtr =
2876 FromType->getAs<ObjCObjectPointerType>();
2877
2878 if (ToObjCPtr && FromObjCPtr) {
2879 // If the pointee types are the same (ignoring qualifications),
2880 // then this is not a pointer conversion.
2881 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2882 FromObjCPtr->getPointeeType()))
2883 return false;
2884
2885 // Conversion between Objective-C pointers.
2886 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2887 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2888 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2889 if (getLangOpts().CPlusPlus && LHS && RHS &&
2891 FromObjCPtr->getPointeeType()))
2892 return false;
2893 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2894 ToObjCPtr->getPointeeType(),
2895 ToType, Context);
2896 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2897 return true;
2898 }
2899
2900 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2901 // Okay: this is some kind of implicit downcast of Objective-C
2902 // interfaces, which is permitted. However, we're going to
2903 // complain about it.
2904 IncompatibleObjC = true;
2905 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2906 ToObjCPtr->getPointeeType(),
2907 ToType, Context);
2908 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2909 return true;
2910 }
2911 }
2912 // Beyond this point, both types need to be C pointers or block pointers.
2913 QualType ToPointeeType;
2914 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2915 ToPointeeType = ToCPtr->getPointeeType();
2916 else if (const BlockPointerType *ToBlockPtr =
2917 ToType->getAs<BlockPointerType>()) {
2918 // Objective C++: We're able to convert from a pointer to any object
2919 // to a block pointer type.
2920 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2921 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2922 return true;
2923 }
2924 ToPointeeType = ToBlockPtr->getPointeeType();
2925 }
2926 else if (FromType->getAs<BlockPointerType>() &&
2927 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2928 // Objective C++: We're able to convert from a block pointer type to a
2929 // pointer to any object.
2930 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2931 return true;
2932 }
2933 else
2934 return false;
2935
2936 QualType FromPointeeType;
2937 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2938 FromPointeeType = FromCPtr->getPointeeType();
2939 else if (const BlockPointerType *FromBlockPtr =
2940 FromType->getAs<BlockPointerType>())
2941 FromPointeeType = FromBlockPtr->getPointeeType();
2942 else
2943 return false;
2944
2945 // If we have pointers to pointers, recursively check whether this
2946 // is an Objective-C conversion.
2947 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2948 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2949 IncompatibleObjC)) {
2950 // We always complain about this conversion.
2951 IncompatibleObjC = true;
2952 ConvertedType = Context.getPointerType(ConvertedType);
2953 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2954 return true;
2955 }
2956 // Allow conversion of pointee being objective-c pointer to another one;
2957 // as in I* to id.
2958 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2959 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2960 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2961 IncompatibleObjC)) {
2962
2963 ConvertedType = Context.getPointerType(ConvertedType);
2964 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2965 return true;
2966 }
2967
2968 // If we have pointers to functions or blocks, check whether the only
2969 // differences in the argument and result types are in Objective-C
2970 // pointer conversions. If so, we permit the conversion (but
2971 // complain about it).
2972 const FunctionProtoType *FromFunctionType
2973 = FromPointeeType->getAs<FunctionProtoType>();
2974 const FunctionProtoType *ToFunctionType
2975 = ToPointeeType->getAs<FunctionProtoType>();
2976 if (FromFunctionType && ToFunctionType) {
2977 // If the function types are exactly the same, this isn't an
2978 // Objective-C pointer conversion.
2979 if (Context.getCanonicalType(FromPointeeType)
2980 == Context.getCanonicalType(ToPointeeType))
2981 return false;
2982
2983 // Perform the quick checks that will tell us whether these
2984 // function types are obviously different.
2985 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2986 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2987 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2988 return false;
2989
2990 bool HasObjCConversion = false;
2991 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2992 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2993 // Okay, the types match exactly. Nothing to do.
2994 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2995 ToFunctionType->getReturnType(),
2996 ConvertedType, IncompatibleObjC)) {
2997 // Okay, we have an Objective-C pointer conversion.
2998 HasObjCConversion = true;
2999 } else {
3000 // Function types are too different. Abort.
3001 return false;
3002 }
3003
3004 // Check argument types.
3005 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3006 ArgIdx != NumArgs; ++ArgIdx) {
3007 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3008 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3009 if (Context.getCanonicalType(FromArgType)
3010 == Context.getCanonicalType(ToArgType)) {
3011 // Okay, the types match exactly. Nothing to do.
3012 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3013 ConvertedType, IncompatibleObjC)) {
3014 // Okay, we have an Objective-C pointer conversion.
3015 HasObjCConversion = true;
3016 } else {
3017 // Argument types are too different. Abort.
3018 return false;
3019 }
3020 }
3021
3022 if (HasObjCConversion) {
3023 // We had an Objective-C conversion. Allow this pointer
3024 // conversion, but complain about it.
3025 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3026 IncompatibleObjC = true;
3027 return true;
3028 }
3029 }
3030
3031 return false;
3032}
3033
3034/// Determine whether this is an Objective-C writeback conversion,
3035/// used for parameter passing when performing automatic reference counting.
3036///
3037/// \param FromType The type we're converting form.
3038///
3039/// \param ToType The type we're converting to.
3040///
3041/// \param ConvertedType The type that will be produced after applying
3042/// this conversion.
3044 QualType &ConvertedType) {
3045 if (!getLangOpts().ObjCAutoRefCount ||
3046 Context.hasSameUnqualifiedType(FromType, ToType))
3047 return false;
3048
3049 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
3050 QualType ToPointee;
3051 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
3052 ToPointee = ToPointer->getPointeeType();
3053 else
3054 return false;
3055
3056 Qualifiers ToQuals = ToPointee.getQualifiers();
3057 if (!ToPointee->isObjCLifetimeType() ||
3059 !ToQuals.withoutObjCLifetime().empty())
3060 return false;
3061
3062 // Argument must be a pointer to __strong to __weak.
3063 QualType FromPointee;
3064 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
3065 FromPointee = FromPointer->getPointeeType();
3066 else
3067 return false;
3068
3069 Qualifiers FromQuals = FromPointee.getQualifiers();
3070 if (!FromPointee->isObjCLifetimeType() ||
3071 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
3072 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
3073 return false;
3074
3075 // Make sure that we have compatible qualifiers.
3077 if (!ToQuals.compatiblyIncludes(FromQuals))
3078 return false;
3079
3080 // Remove qualifiers from the pointee type we're converting from; they
3081 // aren't used in the compatibility check belong, and we'll be adding back
3082 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
3083 FromPointee = FromPointee.getUnqualifiedType();
3084
3085 // The unqualified form of the pointee types must be compatible.
3086 ToPointee = ToPointee.getUnqualifiedType();
3087 bool IncompatibleObjC;
3088 if (Context.typesAreCompatible(FromPointee, ToPointee))
3089 FromPointee = ToPointee;
3090 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
3091 IncompatibleObjC))
3092 return false;
3093
3094 /// Construct the type we're converting to, which is a pointer to
3095 /// __autoreleasing pointee.
3096 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
3097 ConvertedType = Context.getPointerType(FromPointee);
3098 return true;
3099}
3100
3102 QualType& ConvertedType) {
3103 QualType ToPointeeType;
3104 if (const BlockPointerType *ToBlockPtr =
3105 ToType->getAs<BlockPointerType>())
3106 ToPointeeType = ToBlockPtr->getPointeeType();
3107 else
3108 return false;
3109
3110 QualType FromPointeeType;
3111 if (const BlockPointerType *FromBlockPtr =
3112 FromType->getAs<BlockPointerType>())
3113 FromPointeeType = FromBlockPtr->getPointeeType();
3114 else
3115 return false;
3116 // We have pointer to blocks, check whether the only
3117 // differences in the argument and result types are in Objective-C
3118 // pointer conversions. If so, we permit the conversion.
3119
3120 const FunctionProtoType *FromFunctionType
3121 = FromPointeeType->getAs<FunctionProtoType>();
3122 const FunctionProtoType *ToFunctionType
3123 = ToPointeeType->getAs<FunctionProtoType>();
3124
3125 if (!FromFunctionType || !ToFunctionType)
3126 return false;
3127
3128 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3129 return true;
3130
3131 // Perform the quick checks that will tell us whether these
3132 // function types are obviously different.
3133 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3134 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3135 return false;
3136
3137 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3138 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3139 if (FromEInfo != ToEInfo)
3140 return false;
3141
3142 bool IncompatibleObjC = false;
3143 if (Context.hasSameType(FromFunctionType->getReturnType(),
3144 ToFunctionType->getReturnType())) {
3145 // Okay, the types match exactly. Nothing to do.
3146 } else {
3147 QualType RHS = FromFunctionType->getReturnType();
3148 QualType LHS = ToFunctionType->getReturnType();
3149 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3150 !RHS.hasQualifiers() && LHS.hasQualifiers())
3151 LHS = LHS.getUnqualifiedType();
3152
3153 if (Context.hasSameType(RHS,LHS)) {
3154 // OK exact match.
3155 } else if (isObjCPointerConversion(RHS, LHS,
3156 ConvertedType, IncompatibleObjC)) {
3157 if (IncompatibleObjC)
3158 return false;
3159 // Okay, we have an Objective-C pointer conversion.
3160 }
3161 else
3162 return false;
3163 }
3164
3165 // Check argument types.
3166 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3167 ArgIdx != NumArgs; ++ArgIdx) {
3168 IncompatibleObjC = false;
3169 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3170 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3171 if (Context.hasSameType(FromArgType, ToArgType)) {
3172 // Okay, the types match exactly. Nothing to do.
3173 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3174 ConvertedType, IncompatibleObjC)) {
3175 if (IncompatibleObjC)
3176 return false;
3177 // Okay, we have an Objective-C pointer conversion.
3178 } else
3179 // Argument types are too different. Abort.
3180 return false;
3181 }
3182
3184 bool CanUseToFPT, CanUseFromFPT;
3185 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3186 CanUseToFPT, CanUseFromFPT,
3187 NewParamInfos))
3188 return false;
3189
3190 ConvertedType = ToType;
3191 return true;
3192}
3193
3194enum {
3203
3204/// Attempts to get the FunctionProtoType from a Type. Handles
3205/// MemberFunctionPointers properly.
3207 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3208 return FPT;
3209
3210 if (auto *MPT = FromType->getAs<MemberPointerType>())
3211 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3212
3213 return nullptr;
3214}
3215
3216/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3217/// function types. Catches different number of parameter, mismatch in
3218/// parameter types, and different return types.
3220 QualType FromType, QualType ToType) {
3221 // If either type is not valid, include no extra info.
3222 if (FromType.isNull() || ToType.isNull()) {
3223 PDiag << ft_default;
3224 return;
3225 }
3226
3227 // Get the function type from the pointers.
3228 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3229 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3230 *ToMember = ToType->castAs<MemberPointerType>();
3231 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3232 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3233 << QualType(FromMember->getClass(), 0);
3234 return;
3235 }
3236 FromType = FromMember->getPointeeType();
3237 ToType = ToMember->getPointeeType();
3238 }
3239
3240 if (FromType->isPointerType())
3241 FromType = FromType->getPointeeType();
3242 if (ToType->isPointerType())
3243 ToType = ToType->getPointeeType();
3244
3245 // Remove references.
3246 FromType = FromType.getNonReferenceType();
3247 ToType = ToType.getNonReferenceType();
3248
3249 // Don't print extra info for non-specialized template functions.
3250 if (FromType->isInstantiationDependentType() &&
3251 !FromType->getAs<TemplateSpecializationType>()) {
3252 PDiag << ft_default;
3253 return;
3254 }
3255
3256 // No extra info for same types.
3257 if (Context.hasSameType(FromType, ToType)) {
3258 PDiag << ft_default;
3259 return;
3260 }
3261
3262 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3263 *ToFunction = tryGetFunctionProtoType(ToType);
3264
3265 // Both types need to be function types.
3266 if (!FromFunction || !ToFunction) {
3267 PDiag << ft_default;
3268 return;
3269 }
3270
3271 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3272 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3273 << FromFunction->getNumParams();
3274 return;
3275 }
3276
3277 // Handle different parameter types.
3278 unsigned ArgPos;
3279 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3280 PDiag << ft_parameter_mismatch << ArgPos + 1
3281 << ToFunction->getParamType(ArgPos)
3282 << FromFunction->getParamType(ArgPos);
3283 return;
3284 }
3285
3286 // Handle different return type.
3287 if (!Context.hasSameType(FromFunction->getReturnType(),
3288 ToFunction->getReturnType())) {
3289 PDiag << ft_return_type << ToFunction->getReturnType()
3290 << FromFunction->getReturnType();
3291 return;
3292 }
3293
3294 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3295 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3296 << FromFunction->getMethodQuals();
3297 return;
3298 }
3299
3300 // Handle exception specification differences on canonical type (in C++17
3301 // onwards).
3302 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3303 ->isNothrow() !=
3304 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3305 ->isNothrow()) {
3306 PDiag << ft_noexcept;
3307 return;
3308 }
3309
3310 // Unable to find a difference, so add no extra info.
3311 PDiag << ft_default;
3312}
3313
3314/// FunctionParamTypesAreEqual - This routine checks two function proto types
3315/// for equality of their parameter types. Caller has already checked that
3316/// they have same number of parameters. If the parameters are different,
3317/// ArgPos will have the parameter index of the first different parameter.
3318/// If `Reversed` is true, the parameters of `NewType` will be compared in
3319/// reverse order. That's useful if one of the functions is being used as a C++20
3320/// synthesized operator overload with a reversed parameter order.
3322 ArrayRef<QualType> New, unsigned *ArgPos,
3323 bool Reversed) {
3324 assert(llvm::size(Old) == llvm::size(New) &&
3325 "Can't compare parameters of functions with different number of "
3326 "parameters!");
3327
3328 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3329 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3330 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3331
3332 // Ignore address spaces in pointee type. This is to disallow overloading
3333 // on __ptr32/__ptr64 address spaces.
3334 QualType OldType =
3335 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3336 QualType NewType =
3337 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3338
3339 if (!Context.hasSameType(OldType, NewType)) {
3340 if (ArgPos)
3341 *ArgPos = Idx;
3342 return false;
3343 }
3344 }
3345 return true;
3346}
3347
3349 const FunctionProtoType *NewType,
3350 unsigned *ArgPos, bool Reversed) {
3351 return FunctionParamTypesAreEqual(OldType->param_types(),
3352 NewType->param_types(), ArgPos, Reversed);
3353}
3354
3356 const FunctionDecl *NewFunction,
3357 unsigned *ArgPos,
3358 bool Reversed) {
3359
3360 if (OldFunction->getNumNonObjectParams() !=
3361 NewFunction->getNumNonObjectParams())
3362 return false;
3363
3364 unsigned OldIgnore =
3366 unsigned NewIgnore =
3368
3369 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3370 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3371
3372 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3373 NewPT->param_types().slice(NewIgnore),
3374 ArgPos, Reversed);
3375}
3376
3377/// CheckPointerConversion - Check the pointer conversion from the
3378/// expression From to the type ToType. This routine checks for
3379/// ambiguous or inaccessible derived-to-base pointer
3380/// conversions for which IsPointerConversion has already returned
3381/// true. It returns true and produces a diagnostic if there was an
3382/// error, or returns false otherwise.
3384 CastKind &Kind,
3385 CXXCastPath& BasePath,
3386 bool IgnoreBaseAccess,
3387 bool Diagnose) {
3388 QualType FromType = From->getType();
3389 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3390
3391 Kind = CK_BitCast;
3392
3393 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3396 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3397 DiagRuntimeBehavior(From->getExprLoc(), From,
3398 PDiag(diag::warn_impcast_bool_to_null_pointer)
3399 << ToType << From->getSourceRange());
3400 else if (!isUnevaluatedContext())
3401 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3402 << ToType << From->getSourceRange();
3403 }
3404 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3405 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3406 QualType FromPointeeType = FromPtrType->getPointeeType(),
3407 ToPointeeType = ToPtrType->getPointeeType();
3408
3409 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3410 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3411 // We must have a derived-to-base conversion. Check an
3412 // ambiguous or inaccessible conversion.
3413 unsigned InaccessibleID = 0;
3414 unsigned AmbiguousID = 0;
3415 if (Diagnose) {
3416 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3417 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3418 }
3419 if (CheckDerivedToBaseConversion(
3420 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3421 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3422 &BasePath, IgnoreBaseAccess))
3423 return true;
3424
3425 // The conversion was successful.
3426 Kind = CK_DerivedToBase;
3427 }
3428
3429 if (Diagnose && !IsCStyleOrFunctionalCast &&
3430 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3431 assert(getLangOpts().MSVCCompat &&
3432 "this should only be possible with MSVCCompat!");
3433 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3434 << From->getSourceRange();
3435 }
3436 }
3437 } else if (const ObjCObjectPointerType *ToPtrType =
3438 ToType->getAs<ObjCObjectPointerType>()) {
3439 if (const ObjCObjectPointerType *FromPtrType =
3440 FromType->getAs<ObjCObjectPointerType>()) {
3441 // Objective-C++ conversions are always okay.
3442 // FIXME: We should have a different class of conversions for the
3443 // Objective-C++ implicit conversions.
3444 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3445 return false;
3446 } else if (FromType->isBlockPointerType()) {
3447 Kind = CK_BlockPointerToObjCPointerCast;
3448 } else {
3449 Kind = CK_CPointerToObjCPointerCast;
3450 }
3451 } else if (ToType->isBlockPointerType()) {
3452 if (!FromType->isBlockPointerType())
3453 Kind = CK_AnyPointerToBlockPointerCast;
3454 }
3455
3456 // We shouldn't fall into this case unless it's valid for other
3457 // reasons.
3459 Kind = CK_NullToPointer;
3460
3461 return false;
3462}
3463
3464/// IsMemberPointerConversion - Determines whether the conversion of the
3465/// expression From, which has the (possibly adjusted) type FromType, can be
3466/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3467/// If so, returns true and places the converted type (that might differ from
3468/// ToType in its cv-qualifiers at some level) into ConvertedType.
3470 QualType ToType,
3471 bool InOverloadResolution,
3472 QualType &ConvertedType) {
3473 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3474 if (!ToTypePtr)
3475 return false;
3476
3477 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3478 if (From->isNullPointerConstant(Context,
3479 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3481 ConvertedType = ToType;
3482 return true;
3483 }
3484
3485 // Otherwise, both types have to be member pointers.
3486 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3487 if (!FromTypePtr)
3488 return false;
3489
3490 // A pointer to member of B can be converted to a pointer to member of D,
3491 // where D is derived from B (C++ 4.11p2).
3492 QualType FromClass(FromTypePtr->getClass(), 0);
3493 QualType ToClass(ToTypePtr->getClass(), 0);
3494
3495 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3496 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3497 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3498 ToClass.getTypePtr());
3499 return true;
3500 }
3501
3502 return false;
3503}
3504
3505/// CheckMemberPointerConversion - Check the member pointer conversion from the
3506/// expression From to the type ToType. This routine checks for ambiguous or
3507/// virtual or inaccessible base-to-derived member pointer conversions
3508/// for which IsMemberPointerConversion has already returned true. It returns
3509/// true and produces a diagnostic if there was an error, or returns false
3510/// otherwise.
3512 CastKind &Kind,
3513 CXXCastPath &BasePath,
3514 bool IgnoreBaseAccess) {
3515 QualType FromType = From->getType();
3516 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3517 if (!FromPtrType) {
3518 // This must be a null pointer to member pointer conversion
3519 assert(From->isNullPointerConstant(Context,
3521 "Expr must be null pointer constant!");
3522 Kind = CK_NullToMemberPointer;
3523 return false;
3524 }
3525
3526 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3527 assert(ToPtrType && "No member pointer cast has a target type "
3528 "that is not a member pointer.");
3529
3530 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3531 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3532
3533 // FIXME: What about dependent types?
3534 assert(FromClass->isRecordType() && "Pointer into non-class.");
3535 assert(ToClass->isRecordType() && "Pointer into non-class.");
3536
3537 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3538 /*DetectVirtual=*/true);
3539 bool DerivationOkay =
3540 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3541 assert(DerivationOkay &&
3542 "Should not have been called if derivation isn't OK.");
3543 (void)DerivationOkay;
3544
3545 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3546 getUnqualifiedType())) {
3547 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3548 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3549 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3550 return true;
3551 }
3552
3553 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3554 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3555 << FromClass << ToClass << QualType(VBase, 0)
3556 << From->getSourceRange();
3557 return true;
3558 }
3559
3560 if (!IgnoreBaseAccess)
3561 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3562 Paths.front(),
3563 diag::err_downcast_from_inaccessible_base);
3564
3565 // Must be a base to derived member conversion.
3566 BuildBasePathArray(Paths, BasePath);
3567 Kind = CK_BaseToDerivedMemberPointer;
3568 return false;
3569}
3570
3571/// Determine whether the lifetime conversion between the two given
3572/// qualifiers sets is nontrivial.
3574 Qualifiers ToQuals) {
3575 // Converting anything to const __unsafe_unretained is trivial.
3576 if (ToQuals.hasConst() &&
3578 return false;
3579
3580 return true;
3581}
3582
3583/// Perform a single iteration of the loop for checking if a qualification
3584/// conversion is valid.
3585///
3586/// Specifically, check whether any change between the qualifiers of \p
3587/// FromType and \p ToType is permissible, given knowledge about whether every
3588/// outer layer is const-qualified.
3590 bool CStyle, bool IsTopLevel,
3591 bool &PreviousToQualsIncludeConst,
3592 bool &ObjCLifetimeConversion) {
3593 Qualifiers FromQuals = FromType.getQualifiers();
3594 Qualifiers ToQuals = ToType.getQualifiers();
3595
3596 // Ignore __unaligned qualifier.
3597 FromQuals.removeUnaligned();
3598
3599 // Objective-C ARC:
3600 // Check Objective-C lifetime conversions.
3601 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3602 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3603 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3604 ObjCLifetimeConversion = true;
3605 FromQuals.removeObjCLifetime();
3606 ToQuals.removeObjCLifetime();
3607 } else {
3608 // Qualification conversions cannot cast between different
3609 // Objective-C lifetime qualifiers.
3610 return false;
3611 }
3612 }
3613
3614 // Allow addition/removal of GC attributes but not changing GC attributes.
3615 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3616 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3617 FromQuals.removeObjCGCAttr();
3618 ToQuals.removeObjCGCAttr();
3619 }
3620
3621 // -- for every j > 0, if const is in cv 1,j then const is in cv
3622 // 2,j, and similarly for volatile.
3623 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3624 return false;
3625
3626 // If address spaces mismatch:
3627 // - in top level it is only valid to convert to addr space that is a
3628 // superset in all cases apart from C-style casts where we allow
3629 // conversions between overlapping address spaces.
3630 // - in non-top levels it is not a valid conversion.
3631 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3632 (!IsTopLevel ||
3633 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3634 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3635 return false;
3636
3637 // -- if the cv 1,j and cv 2,j are different, then const is in
3638 // every cv for 0 < k < j.
3639 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3640 !PreviousToQualsIncludeConst)
3641 return false;
3642
3643 // The following wording is from C++20, where the result of the conversion
3644 // is T3, not T2.
3645 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3646 // "array of unknown bound of"
3647 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3648 return false;
3649
3650 // -- if the resulting P3,i is different from P1,i [...], then const is
3651 // added to every cv 3_k for 0 < k < i.
3652 if (!CStyle && FromType->isConstantArrayType() &&
3653 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3654 return false;
3655
3656 // Keep track of whether all prior cv-qualifiers in the "to" type
3657 // include const.
3658 PreviousToQualsIncludeConst =
3659 PreviousToQualsIncludeConst && ToQuals.hasConst();
3660 return true;
3661}
3662
3663/// IsQualificationConversion - Determines whether the conversion from
3664/// an rvalue of type FromType to ToType is a qualification conversion
3665/// (C++ 4.4).
3666///
3667/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3668/// when the qualification conversion involves a change in the Objective-C
3669/// object lifetime.
3670bool
3672 bool CStyle, bool &ObjCLifetimeConversion) {
3673 FromType = Context.getCanonicalType(FromType);
3674 ToType = Context.getCanonicalType(ToType);
3675 ObjCLifetimeConversion = false;
3676
3677 // If FromType and ToType are the same type, this is not a
3678 // qualification conversion.
3679 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3680 return false;
3681
3682 // (C++ 4.4p4):
3683 // A conversion can add cv-qualifiers at levels other than the first
3684 // in multi-level pointers, subject to the following rules: [...]
3685 bool PreviousToQualsIncludeConst = true;
3686 bool UnwrappedAnyPointer = false;
3687 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3689 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3690 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3691 return false;
3692 UnwrappedAnyPointer = true;
3693 }
3694
3695 // We are left with FromType and ToType being the pointee types
3696 // after unwrapping the original FromType and ToType the same number
3697 // of times. If we unwrapped any pointers, and if FromType and
3698 // ToType have the same unqualified type (since we checked
3699 // qualifiers above), then this is a qualification conversion.
3700 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3701}
3702
3703/// - Determine whether this is a conversion from a scalar type to an
3704/// atomic type.
3705///
3706/// If successful, updates \c SCS's second and third steps in the conversion
3707/// sequence to finish the conversion.
3708static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3709 bool InOverloadResolution,
3711 bool CStyle) {
3712 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3713 if (!ToAtomic)
3714 return false;
3715
3717 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3718 InOverloadResolution, InnerSCS,
3719 CStyle, /*AllowObjCWritebackConversion=*/false))
3720 return false;
3721
3722 SCS.Second = InnerSCS.Second;
3723 SCS.setToType(1, InnerSCS.getToType(1));
3724 SCS.Third = InnerSCS.Third;
3727 SCS.setToType(2, InnerSCS.getToType(2));
3728 return true;
3729}
3730
3732 CXXConstructorDecl *Constructor,
3733 QualType Type) {
3734 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3735 if (CtorType->getNumParams() > 0) {
3736 QualType FirstArg = CtorType->getParamType(0);
3737 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3738 return true;
3739 }
3740 return false;
3741}
3742
3743static OverloadingResult
3745 CXXRecordDecl *To,
3747 OverloadCandidateSet &CandidateSet,
3748 bool AllowExplicit) {
3750 for (auto *D : S.LookupConstructors(To)) {
3751 auto Info = getConstructorInfo(D);
3752 if (!Info)
3753 continue;
3754
3755 bool Usable = !Info.Constructor->isInvalidDecl() &&
3756 S.isInitListConstructor(Info.Constructor);
3757 if (Usable) {
3758 bool SuppressUserConversions = false;
3759 if (Info.ConstructorTmpl)
3760 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3761 /*ExplicitArgs*/ nullptr, From,
3762 CandidateSet, SuppressUserConversions,
3763 /*PartialOverloading*/ false,
3764 AllowExplicit);
3765 else
3766 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3767 CandidateSet, SuppressUserConversions,
3768 /*PartialOverloading*/ false, AllowExplicit);
3769 }
3770 }
3771
3772 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3773
3775 switch (auto Result =
3776 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3777 case OR_Deleted:
3778 case OR_Success: {
3779 // Record the standard conversion we used and the conversion function.
3780 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3781 QualType ThisType = Constructor->getFunctionObjectParameterType();
3782 // Initializer lists don't have conversions as such.
3784 User.HadMultipleCandidates = HadMultipleCandidates;
3785 User.ConversionFunction = Constructor;
3786 User.FoundConversionFunction = Best->FoundDecl;
3788 User.After.setFromType(ThisType);
3789 User.After.setAllToTypes(ToType);
3790 return Result;
3791 }
3792
3794 return OR_No_Viable_Function;
3795 case OR_Ambiguous:
3796 return OR_Ambiguous;
3797 }
3798
3799 llvm_unreachable("Invalid OverloadResult!");
3800}
3801
3802/// Determines whether there is a user-defined conversion sequence
3803/// (C++ [over.ics.user]) that converts expression From to the type
3804/// ToType. If such a conversion exists, User will contain the
3805/// user-defined conversion sequence that performs such a conversion
3806/// and this routine will return true. Otherwise, this routine returns
3807/// false and User is unspecified.
3808///
3809/// \param AllowExplicit true if the conversion should consider C++0x
3810/// "explicit" conversion functions as well as non-explicit conversion
3811/// functions (C++0x [class.conv.fct]p2).
3812///
3813/// \param AllowObjCConversionOnExplicit true if the conversion should
3814/// allow an extra Objective-C pointer conversion on uses of explicit
3815/// constructors. Requires \c AllowExplicit to also be set.
3816static OverloadingResult
3819 OverloadCandidateSet &CandidateSet,
3820 AllowedExplicit AllowExplicit,
3821 bool AllowObjCConversionOnExplicit) {
3822 assert(AllowExplicit != AllowedExplicit::None ||
3823 !AllowObjCConversionOnExplicit);
3825
3826 // Whether we will only visit constructors.
3827 bool ConstructorsOnly = false;
3828
3829 // If the type we are conversion to is a class type, enumerate its
3830 // constructors.
3831 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3832 // C++ [over.match.ctor]p1:
3833 // When objects of class type are direct-initialized (8.5), or
3834 // copy-initialized from an expression of the same or a
3835 // derived class type (8.5), overload resolution selects the
3836 // constructor. [...] For copy-initialization, the candidate
3837 // functions are all the converting constructors (12.3.1) of
3838 // that class. The argument list is the expression-list within
3839 // the parentheses of the initializer.
3840 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3841 (From->getType()->getAs<RecordType>() &&
3842 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3843 ConstructorsOnly = true;
3844
3845 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3846 // We're not going to find any constructors.
3847 } else if (CXXRecordDecl *ToRecordDecl
3848 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3849
3850 Expr **Args = &From;
3851 unsigned NumArgs = 1;
3852 bool ListInitializing = false;
3853 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3854 // But first, see if there is an init-list-constructor that will work.
3856 S, From, ToType, ToRecordDecl, User, CandidateSet,
3857 AllowExplicit == AllowedExplicit::All);
3859 return Result;
3860 // Never mind.
3861 CandidateSet.clear(
3863
3864 // If we're list-initializing, we pass the individual elements as
3865 // arguments, not the entire list.
3866 Args = InitList->getInits();
3867 NumArgs = InitList->getNumInits();
3868 ListInitializing = true;
3869 }
3870
3871 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3872 auto Info = getConstructorInfo(D);
3873 if (!Info)
3874 continue;
3875
3876 bool Usable = !Info.Constructor->isInvalidDecl();
3877 if (!ListInitializing)
3878 Usable = Usable && Info.Constructor->isConvertingConstructor(
3879 /*AllowExplicit*/ true);
3880 if (Usable) {
3881 bool SuppressUserConversions = !ConstructorsOnly;
3882 // C++20 [over.best.ics.general]/4.5:
3883 // if the target is the first parameter of a constructor [of class
3884 // X] and the constructor [...] is a candidate by [...] the second
3885 // phase of [over.match.list] when the initializer list has exactly
3886 // one element that is itself an initializer list, [...] and the
3887 // conversion is to X or reference to cv X, user-defined conversion
3888 // sequences are not cnosidered.
3889 if (SuppressUserConversions && ListInitializing) {
3890 SuppressUserConversions =
3891 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3892 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3893 ToType);
3894 }
3895 if (Info.ConstructorTmpl)
3897 Info.ConstructorTmpl, Info.FoundDecl,
3898 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3899 CandidateSet, SuppressUserConversions,
3900 /*PartialOverloading*/ false,
3901 AllowExplicit == AllowedExplicit::All);
3902 else
3903 // Allow one user-defined conversion when user specifies a
3904 // From->ToType conversion via an static cast (c-style, etc).
3905 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3906 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3907 SuppressUserConversions,
3908 /*PartialOverloading*/ false,
3909 AllowExplicit == AllowedExplicit::All);
3910 }
3911 }
3912 }
3913 }
3914
3915 // Enumerate conversion functions, if we're allowed to.
3916 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3917 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3918 // No conversion functions from incomplete types.
3919 } else if (const RecordType *FromRecordType =
3920 From->getType()->getAs<RecordType>()) {
3921 if (CXXRecordDecl *FromRecordDecl
3922 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3923 // Add all of the conversion functions as candidates.
3924 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3925 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3926 DeclAccessPair FoundDecl = I.getPair();
3927 NamedDecl *D = FoundDecl.getDecl();
3928 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3929 if (isa<UsingShadowDecl>(D))
3930 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3931
3932 CXXConversionDecl *Conv;
3933 FunctionTemplateDecl *ConvTemplate;
3934 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3935 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3936 else
3937 Conv = cast<CXXConversionDecl>(D);
3938
3939 if (ConvTemplate)
3941 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3942 CandidateSet, AllowObjCConversionOnExplicit,
3943 AllowExplicit != AllowedExplicit::None);
3944 else
3945 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3946 CandidateSet, AllowObjCConversionOnExplicit,
3947 AllowExplicit != AllowedExplicit::None);
3948 }
3949 }
3950 }
3951
3952 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3953
3955 switch (auto Result =
3956 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3957 case OR_Success:
3958 case OR_Deleted:
3959 // Record the standard conversion we used and the conversion function.
3960 if (CXXConstructorDecl *Constructor
3961 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3962 // C++ [over.ics.user]p1:
3963 // If the user-defined conversion is specified by a
3964 // constructor (12.3.1), the initial standard conversion
3965 // sequence converts the source type to the type required by
3966 // the argument of the constructor.
3967 //
3968 if (isa<InitListExpr>(From)) {
3969 // Initializer lists don't have conversions as such.
3971 } else {
3972 if (Best->Conversions[0].isEllipsis())
3973 User.EllipsisConversion = true;
3974 else {
3975 User.Before = Best->Conversions[0].Standard;
3976 User.EllipsisConversion = false;
3977 }
3978 }
3979 User.HadMultipleCandidates = HadMultipleCandidates;
3980 User.ConversionFunction = Constructor;
3981 User.FoundConversionFunction = Best->FoundDecl;
3983 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3984 User.After.setAllToTypes(ToType);
3985 return Result;
3986 }
3987 if (CXXConversionDecl *Conversion
3988 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3989 // C++ [over.ics.user]p1:
3990 //
3991 // [...] If the user-defined conversion is specified by a
3992 // conversion function (12.3.2), the initial standard
3993 // conversion sequence converts the source type to the
3994 // implicit object parameter of the conversion function.
3995 User.Before = Best->Conversions[0].Standard;
3996 User.HadMultipleCandidates = HadMultipleCandidates;
3997 User.ConversionFunction = Conversion;
3998 User.FoundConversionFunction = Best->FoundDecl;
3999 User.EllipsisConversion = false;
4000
4001 // C++ [over.ics.user]p2:
4002 // The second standard conversion sequence converts the
4003 // result of the user-defined conversion to the target type
4004 // for the sequence. Since an implicit conversion sequence
4005 // is an initialization, the special rules for
4006 // initialization by user-defined conversion apply when
4007 // selecting the best user-defined conversion for a
4008 // user-defined conversion sequence (see 13.3.3 and
4009 // 13.3.3.1).
4010 User.After = Best->FinalConversion;
4011 return Result;
4012 }
4013 llvm_unreachable("Not a constructor or conversion function?");
4014
4016 return OR_No_Viable_Function;
4017
4018 case OR_Ambiguous:
4019 return OR_Ambiguous;
4020 }
4021
4022 llvm_unreachable("Invalid OverloadResult!");
4023}
4024
4025bool
4028 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4030 OverloadingResult OvResult =
4031 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4032 CandidateSet, AllowedExplicit::None, false);
4033
4034 if (!(OvResult == OR_Ambiguous ||
4035 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4036 return false;
4037
4038 auto Cands = CandidateSet.CompleteCandidates(
4039 *this,
4041 From);
4042 if (OvResult == OR_Ambiguous)
4043 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4044 << From->getType() << ToType << From->getSourceRange();
4045 else { // OR_No_Viable_Function && !CandidateSet.empty()
4046 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4047 diag::err_typecheck_nonviable_condition_incomplete,
4048 From->getType(), From->getSourceRange()))
4049 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4050 << false << From->getType() << From->getSourceRange() << ToType;
4051 }
4052
4053 CandidateSet.NoteCandidates(
4054 *this, From, Cands);
4055 return true;
4056}
4057
4058// Helper for compareConversionFunctions that gets the FunctionType that the
4059// conversion-operator return value 'points' to, or nullptr.
4060static const FunctionType *
4062 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4063 const PointerType *RetPtrTy =
4064 ConvFuncTy->getReturnType()->getAs<PointerType>();
4065
4066 if (!RetPtrTy)
4067 return nullptr;
4068
4069 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4070}
4071
4072/// Compare the user-defined conversion functions or constructors
4073/// of two user-defined conversion sequences to determine whether any ordering
4074/// is possible.
4077 FunctionDecl *Function2) {
4078 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4079 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4080 if (!Conv1 || !Conv2)
4082
4083 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4085
4086 // Objective-C++:
4087 // If both conversion functions are implicitly-declared conversions from
4088 // a lambda closure type to a function pointer and a block pointer,
4089 // respectively, always prefer the conversion to a function pointer,
4090 // because the function pointer is more lightweight and is more likely
4091 // to keep code working.
4092 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4093 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4094 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4095 if (Block1 != Block2)
4096 return Block1 ? ImplicitConversionSequence::Worse
4098 }
4099
4100 // In order to support multiple calling conventions for the lambda conversion
4101 // operator (such as when the free and member function calling convention is
4102 // different), prefer the 'free' mechanism, followed by the calling-convention
4103 // of operator(). The latter is in place to support the MSVC-like solution of
4104 // defining ALL of the possible conversions in regards to calling-convention.
4105 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4106 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4107
4108 if (Conv1FuncRet && Conv2FuncRet &&
4109 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4110 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4111 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4112
4113 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4114 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4115
4116 CallingConv CallOpCC =
4117 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4119 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4121 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4122
4123 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4124 for (CallingConv CC : PrefOrder) {
4125 if (Conv1CC == CC)
4127 if (Conv2CC == CC)
4129 }
4130 }
4131
4133}
4134
4136 const ImplicitConversionSequence &ICS) {
4138 (ICS.isUserDefined() &&
4140}
4141
4142/// CompareImplicitConversionSequences - Compare two implicit
4143/// conversion sequences to determine whether one is better than the
4144/// other or if they are indistinguishable (C++ 13.3.3.2).
4147 const ImplicitConversionSequence& ICS1,
4148 const ImplicitConversionSequence& ICS2)
4149{
4150 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4151 // conversion sequences (as defined in 13.3.3.1)
4152 // -- a standard conversion sequence (13.3.3.1.1) is a better
4153 // conversion sequence than a user-defined conversion sequence or
4154 // an ellipsis conversion sequence, and
4155 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4156 // conversion sequence than an ellipsis conversion sequence
4157 // (13.3.3.1.3).
4158 //
4159 // C++0x [over.best.ics]p10:
4160 // For the purpose of ranking implicit conversion sequences as
4161 // described in 13.3.3.2, the ambiguous conversion sequence is
4162 // treated as a user-defined sequence that is indistinguishable
4163 // from any other user-defined conversion sequence.
4164
4165 // String literal to 'char *' conversion has been deprecated in C++03. It has
4166 // been removed from C++11. We still accept this conversion, if it happens at
4167 // the best viable function. Otherwise, this conversion is considered worse
4168 // than ellipsis conversion. Consider this as an extension; this is not in the
4169 // standard. For example:
4170 //
4171 // int &f(...); // #1
4172 // void f(char*); // #2
4173 // void g() { int &r = f("foo"); }
4174 //
4175 // In C++03, we pick #2 as the best viable function.
4176 // In C++11, we pick #1 as the best viable function, because ellipsis
4177 // conversion is better than string-literal to char* conversion (since there
4178 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4179 // convert arguments, #2 would be the best viable function in C++11.
4180 // If the best viable function has this conversion, a warning will be issued
4181 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4182
4183 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4186 // Ill-formedness must not differ
4187 ICS1.isBad() == ICS2.isBad())
4191
4192 if (ICS1.getKindRank() < ICS2.getKindRank())
4194 if (ICS2.getKindRank() < ICS1.getKindRank())
4196
4197 // The following checks require both conversion sequences to be of
4198 // the same kind.
4199 if (ICS1.getKind() != ICS2.getKind())
4201
4204
4205 // Two implicit conversion sequences of the same form are
4206 // indistinguishable conversion sequences unless one of the
4207 // following rules apply: (C++ 13.3.3.2p3):
4208
4209 // List-initialization sequence L1 is a better conversion sequence than
4210 // list-initialization sequence L2 if:
4211 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4212 // if not that,
4213 // — L1 and L2 convert to arrays of the same element type, and either the
4214 // number of elements n_1 initialized by L1 is less than the number of
4215 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4216 // an array of unknown bound and L1 does not,
4217 // even if one of the other rules in this paragraph would otherwise apply.
4218 if (!ICS1.isBad()) {
4219 bool StdInit1 = false, StdInit2 = false;
4222 nullptr);
4225 nullptr);
4226 if (StdInit1 != StdInit2)
4227 return StdInit1 ? ImplicitConversionSequence::Better
4229
4232 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4234 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4236 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4237 CAT2->getElementType())) {
4238 // Both to arrays of the same element type
4239 if (CAT1->getSize() != CAT2->getSize())
4240 // Different sized, the smaller wins
4241 return CAT1->getSize().ult(CAT2->getSize())
4246 // One is incomplete, it loses
4250 }
4251 }
4252 }
4253
4254 if (ICS1.isStandard())
4255 // Standard conversion sequence S1 is a better conversion sequence than
4256 // standard conversion sequence S2 if [...]
4258 ICS1.Standard, ICS2.Standard);
4259 else if (ICS1.isUserDefined()) {
4260 // User-defined conversion sequence U1 is a better conversion
4261 // sequence than another user-defined conversion sequence U2 if
4262 // they contain the same user-defined conversion function or
4263 // constructor and if the second standard conversion sequence of
4264 // U1 is better than the second standard conversion sequence of
4265 // U2 (C++ 13.3.3.2p3).
4269 ICS1.UserDefined.After,
4270 ICS2.UserDefined.After);
4271 else
4275 }
4276
4277 return Result;
4278}
4279
4280// Per 13.3.3.2p3, compare the given standard conversion sequences to
4281// determine if one is a proper subset of the other.
4284 const StandardConversionSequence& SCS1,
4285 const StandardConversionSequence& SCS2) {
4288
4289 // the identity conversion sequence is considered to be a subsequence of
4290 // any non-identity conversion sequence
4291 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4293 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4295
4296 if (SCS1.Second != SCS2.Second) {
4297 if (SCS1.Second == ICK_Identity)
4299 else if (SCS2.Second == ICK_Identity)
4301 else
4303 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4305
4306 if (SCS1.Third == SCS2.Third) {
4307 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4309 }
4310
4311 if (SCS1.Third == ICK_Identity)
4315
4316 if (SCS2.Third == ICK_Identity)
4320
4322}
4323
4324/// Determine whether one of the given reference bindings is better
4325/// than the other based on what kind of bindings they are.
4326static bool
4328 const StandardConversionSequence &SCS2) {
4329 // C++0x [over.ics.rank]p3b4:
4330 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4331 // implicit object parameter of a non-static member function declared
4332 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4333 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4334 // lvalue reference to a function lvalue and S2 binds an rvalue
4335 // reference*.
4336 //
4337 // FIXME: Rvalue references. We're going rogue with the above edits,
4338 // because the semantics in the current C++0x working paper (N3225 at the
4339 // time of this writing) break the standard definition of std::forward
4340 // and std::reference_wrapper when dealing with references to functions.
4341 // Proposed wording changes submitted to CWG for consideration.
4344 return false;
4345
4346 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4347 SCS2.IsLvalueReference) ||
4350}
4351
4353 None,
4356};
4357
4358/// Returns kind of fixed enum promotion the \a SCS uses.
4359static FixedEnumPromotion
4361
4362 if (SCS.Second != ICK_Integral_Promotion)
4363 return FixedEnumPromotion::None;
4364
4365 QualType FromType = SCS.getFromType();
4366 if (!FromType->isEnumeralType())
4367 return FixedEnumPromotion::None;
4368
4369 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4370 if (!Enum->isFixed())
4371 return FixedEnumPromotion::None;
4372
4373 QualType UnderlyingType = Enum->getIntegerType();
4374 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4375 return FixedEnumPromotion::ToUnderlyingType;
4376
4377 return FixedEnumPromotion::ToPromotedUnderlyingType;
4378}
4379
4380/// CompareStandardConversionSequences - Compare two standard
4381/// conversion sequences to determine whether one is better than the
4382/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4385 const StandardConversionSequence& SCS1,
4386 const StandardConversionSequence& SCS2)
4387{
4388 // Standard conversion sequence S1 is a better conversion sequence
4389 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4390
4391 // -- S1 is a proper subsequence of S2 (comparing the conversion
4392 // sequences in the canonical form defined by 13.3.3.1.1,
4393 // excluding any Lvalue Transformation; the identity conversion
4394 // sequence is considered to be a subsequence of any
4395 // non-identity conversion sequence) or, if not that,
4398 return CK;
4399
4400 // -- the rank of S1 is better than the rank of S2 (by the rules
4401 // defined below), or, if not that,
4402 ImplicitConversionRank Rank1 = SCS1.getRank();
4403 ImplicitConversionRank Rank2 = SCS2.getRank();
4404 if (Rank1 < Rank2)
4406 else if (Rank2 < Rank1)
4408
4409 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4410 // are indistinguishable unless one of the following rules
4411 // applies:
4412
4413 // A conversion that is not a conversion of a pointer, or
4414 // pointer to member, to bool is better than another conversion
4415 // that is such a conversion.
4417 return SCS2.isPointerConversionToBool()
4420
4421 // C++14 [over.ics.rank]p4b2:
4422 // This is retroactively applied to C++11 by CWG 1601.
4423 //
4424 // A conversion that promotes an enumeration whose underlying type is fixed
4425 // to its underlying type is better than one that promotes to the promoted
4426 // underlying type, if the two are different.
4429 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4430 FEP1 != FEP2)
4431 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4434
4435 // C++ [over.ics.rank]p4b2:
4436 //
4437 // If class B is derived directly or indirectly from class A,
4438 // conversion of B* to A* is better than conversion of B* to
4439 // void*, and conversion of A* to void* is better than conversion
4440 // of B* to void*.
4441 bool SCS1ConvertsToVoid
4443 bool SCS2ConvertsToVoid
4445 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4446 // Exactly one of the conversion sequences is a conversion to
4447 // a void pointer; it's the worse conversion.
4448 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4450 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4451 // Neither conversion sequence converts to a void pointer; compare
4452 // their derived-to-base conversions.
4454 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4455 return DerivedCK;
4456 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4457 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4458 // Both conversion sequences are conversions to void
4459 // pointers. Compare the source types to determine if there's an
4460 // inheritance relationship in their sources.
4461 QualType FromType1 = SCS1.getFromType();
4462 QualType FromType2 = SCS2.getFromType();
4463
4464 // Adjust the types we're converting from via the array-to-pointer
4465 // conversion, if we need to.
4466 if (SCS1.First == ICK_Array_To_Pointer)
4467 FromType1 = S.Context.getArrayDecayedType(FromType1);
4468 if (SCS2.First == ICK_Array_To_Pointer)
4469 FromType2 = S.Context.getArrayDecayedType(FromType2);
4470
4471 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4472 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4473
4474 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4476 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4478
4479 // Objective-C++: If one interface is more specific than the
4480 // other, it is the better one.
4481 const ObjCObjectPointerType* FromObjCPtr1
4482 = FromType1->getAs<ObjCObjectPointerType>();
4483 const ObjCObjectPointerType* FromObjCPtr2
4484 = FromType2->getAs<ObjCObjectPointerType>();
4485 if (FromObjCPtr1 && FromObjCPtr2) {
4486 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4487 FromObjCPtr2);
4488 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4489 FromObjCPtr1);
4490 if (AssignLeft != AssignRight) {
4491 return AssignLeft? ImplicitConversionSequence::Better
4493 }
4494 }
4495 }
4496
4497 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4498 // Check for a better reference binding based on the kind of bindings.
4499 if (isBetterReferenceBindingKind(SCS1, SCS2))
4501 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4503 }
4504
4505 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4506 // bullet 3).
4508 = CompareQualificationConversions(S, SCS1, SCS2))
4509 return QualCK;
4510
4511 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4512 // C++ [over.ics.rank]p3b4:
4513 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4514 // which the references refer are the same type except for
4515 // top-level cv-qualifiers, and the type to which the reference
4516 // initialized by S2 refers is more cv-qualified than the type
4517 // to which the reference initialized by S1 refers.
4518 QualType T1 = SCS1.getToType(2);
4519 QualType T2 = SCS2.getToType(2);
4520 T1 = S.Context.getCanonicalType(T1);
4521 T2 = S.Context.getCanonicalType(T2);
4522 Qualifiers T1Quals, T2Quals;
4523 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4524 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4525 if (UnqualT1 == UnqualT2) {
4526 // Objective-C++ ARC: If the references refer to objects with different
4527 // lifetimes, prefer bindings that don't change lifetime.
4533 }
4534
4535 // If the type is an array type, promote the element qualifiers to the
4536 // type for comparison.
4537 if (isa<ArrayType>(T1) && T1Quals)
4538 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4539 if (isa<ArrayType>(T2) && T2Quals)
4540 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4541 if (T2.isMoreQualifiedThan(T1))
4543 if (T1.isMoreQualifiedThan(T2))
4545 }
4546 }
4547
4548 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4549 // floating-to-integral conversion if the integral conversion
4550 // is between types of the same size.
4551 // For example:
4552 // void f(float);
4553 // void f(int);
4554 // int main {
4555 // long a;
4556 // f(a);
4557 // }
4558 // Here, MSVC will call f(int) instead of generating a compile error
4559 // as clang will do in standard mode.
4560 if (S.getLangOpts().MSVCCompat &&
4563 SCS2.Second == ICK_Floating_Integral &&
4564 S.Context.getTypeSize(SCS1.getFromType()) ==
4565 S.Context.getTypeSize(SCS1.getToType(2)))
4567
4568 // Prefer a compatible vector conversion over a lax vector conversion
4569 // For example:
4570 //
4571 // typedef float __v4sf __attribute__((__vector_size__(16)));
4572 // void f(vector float);
4573 // void f(vector signed int);
4574 // int main() {
4575 // __v4sf a;
4576 // f(a);
4577 // }
4578 // Here, we'd like to choose f(vector float) and not
4579 // report an ambiguous call error
4580 if (SCS1.Second == ICK_Vector_Conversion &&
4581 SCS2.Second == ICK_Vector_Conversion) {
4582 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4583 SCS1.getFromType(), SCS1.getToType(2));
4584 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4585 SCS2.getFromType(), SCS2.getToType(2));
4586
4587 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4588 return SCS1IsCompatibleVectorConversion
4591 }
4592
4593 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4595 bool SCS1IsCompatibleSVEVectorConversion =
4597 bool SCS2IsCompatibleSVEVectorConversion =
4599
4600 if (SCS1IsCompatibleSVEVectorConversion !=
4601 SCS2IsCompatibleSVEVectorConversion)
4602 return SCS1IsCompatibleSVEVectorConversion
4605 }
4606
4607 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4609 bool SCS1IsCompatibleRVVVectorConversion =
4611 bool SCS2IsCompatibleRVVVectorConversion =
4613
4614 if (SCS1IsCompatibleRVVVectorConversion !=
4615 SCS2IsCompatibleRVVVectorConversion)
4616 return SCS1IsCompatibleRVVVectorConversion
4619 }
4620
4622}
4623
4624/// CompareQualificationConversions - Compares two standard conversion
4625/// sequences to determine whether they can be ranked based on their
4626/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4629 const StandardConversionSequence& SCS1,
4630 const StandardConversionSequence& SCS2) {
4631 // C++ [over.ics.rank]p3:
4632 // -- S1 and S2 differ only in their qualification conversion and
4633 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4634 // [C++98]
4635 // [...] and the cv-qualification signature of type T1 is a proper subset
4636 // of the cv-qualification signature of type T2, and S1 is not the
4637 // deprecated string literal array-to-pointer conversion (4.2).
4638 // [C++2a]
4639 // [...] where T1 can be converted to T2 by a qualification conversion.
4640 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4641 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4643
4644 // FIXME: the example in the standard doesn't use a qualification
4645 // conversion (!)
4646 QualType T1 = SCS1.getToType(2);
4647 QualType T2 = SCS2.getToType(2);
4648 T1 = S.Context.getCanonicalType(T1);
4649 T2 = S.Context.getCanonicalType(T2);
4650 assert(!T1->isReferenceType() && !T2->isReferenceType());
4651 Qualifiers T1Quals, T2Quals;
4652 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4653 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4654
4655 // If the types are the same, we won't learn anything by unwrapping
4656 // them.
4657 if (UnqualT1 == UnqualT2)
4659
4660 // Don't ever prefer a standard conversion sequence that uses the deprecated
4661 // string literal array to pointer conversion.
4662 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4663 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4664
4665 // Objective-C++ ARC:
4666 // Prefer qualification conversions not involving a change in lifetime
4667 // to qualification conversions that do change lifetime.
4670 CanPick1 = false;
4673 CanPick2 = false;
4674
4675 bool ObjCLifetimeConversion;
4676 if (CanPick1 &&
4677 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4678 CanPick1 = false;
4679 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4680 // directions, so we can't short-cut this second check in general.
4681 if (CanPick2 &&
4682 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4683 CanPick2 = false;
4684
4685 if (CanPick1 != CanPick2)
4686 return CanPick1 ? ImplicitConversionSequence::Better
4689}
4690
4691/// CompareDerivedToBaseConversions - Compares two standard conversion
4692/// sequences to determine whether they can be ranked based on their
4693/// various kinds of derived-to-base conversions (C++
4694/// [over.ics.rank]p4b3). As part of these checks, we also look at
4695/// conversions between Objective-C interface types.
4698 const StandardConversionSequence& SCS1,
4699 const StandardConversionSequence& SCS2) {
4700 QualType FromType1 = SCS1.getFromType();
4701 QualType ToType1 = SCS1.getToType(1);
4702 QualType FromType2 = SCS2.getFromType();
4703 QualType ToType2 = SCS2.getToType(1);
4704
4705 // Adjust the types we're converting from via the array-to-pointer
4706 // conversion, if we need to.
4707 if (SCS1.First == ICK_Array_To_Pointer)
4708 FromType1 = S.Context.getArrayDecayedType(FromType1);
4709 if (SCS2.First == ICK_Array_To_Pointer)
4710 FromType2 = S.Context.getArrayDecayedType(FromType2);
4711
4712 // Canonicalize all of the types.
4713 FromType1 = S.Context.getCanonicalType(FromType1);
4714 ToType1 = S.Context.getCanonicalType(ToType1);
4715 FromType2 = S.Context.getCanonicalType(FromType2);
4716 ToType2 = S.Context.getCanonicalType(ToType2);
4717
4718 // C++ [over.ics.rank]p4b3:
4719 //
4720 // If class B is derived directly or indirectly from class A and
4721 // class C is derived directly or indirectly from B,
4722 //
4723 // Compare based on pointer conversions.
4724 if (SCS1.Second == ICK_Pointer_Conversion &&
4726 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4727 FromType1->isPointerType() && FromType2->isPointerType() &&
4728 ToType1->isPointerType() && ToType2->isPointerType()) {
4729 QualType FromPointee1 =
4730 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4731 QualType ToPointee1 =
4732 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4733 QualType FromPointee2 =
4734 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4735 QualType ToPointee2 =
4736 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4737
4738 // -- conversion of C* to B* is better than conversion of C* to A*,
4739 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4740 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4742 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4744 }
4745
4746 // -- conversion of B* to A* is better than conversion of C* to A*,
4747 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4748 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4750 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4752 }
4753 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4755 const ObjCObjectPointerType *FromPtr1
4756 = FromType1->getAs<ObjCObjectPointerType>();
4757 const ObjCObjectPointerType *FromPtr2
4758 = FromType2->getAs<ObjCObjectPointerType>();
4759 const ObjCObjectPointerType *ToPtr1
4760 = ToType1->getAs<ObjCObjectPointerType>();
4761 const ObjCObjectPointerType *ToPtr2
4762 = ToType2->getAs<ObjCObjectPointerType>();
4763
4764 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4765 // Apply the same conversion ranking rules for Objective-C pointer types
4766 // that we do for C++ pointers to class types. However, we employ the
4767 // Objective-C pseudo-subtyping relationship used for assignment of
4768 // Objective-C pointer types.
4769 bool FromAssignLeft
4770 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4771 bool FromAssignRight
4772 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4773 bool ToAssignLeft
4774 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4775 bool ToAssignRight
4776 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4777
4778 // A conversion to an a non-id object pointer type or qualified 'id'
4779 // type is better than a conversion to 'id'.
4780 if (ToPtr1->isObjCIdType() &&
4781 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4783 if (ToPtr2->isObjCIdType() &&
4784 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4786
4787 // A conversion to a non-id object pointer type is better than a
4788 // conversion to a qualified 'id' type
4789 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4791 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4793
4794 // A conversion to an a non-Class object pointer type or qualified 'Class'
4795 // type is better than a conversion to 'Class'.
4796 if (ToPtr1->isObjCClassType() &&
4797 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4799 if (ToPtr2->isObjCClassType() &&
4800 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4802
4803 // A conversion to a non-Class object pointer type is better than a
4804 // conversion to a qualified 'Class' type.
4805 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4807 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4809
4810 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4811 if (S.Context.hasSameType(FromType1, FromType2) &&
4812 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4813 (ToAssignLeft != ToAssignRight)) {
4814 if (FromPtr1->isSpecialized()) {
4815 // "conversion of B<A> * to B * is better than conversion of B * to
4816 // C *.
4817 bool IsFirstSame =
4818 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4819 bool IsSecondSame =
4820 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4821 if (IsFirstSame) {
4822 if (!IsSecondSame)
4824 } else if (IsSecondSame)
4826 }
4827 return ToAssignLeft? ImplicitConversionSequence::Worse
4829 }
4830
4831 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4832 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4833 (FromAssignLeft != FromAssignRight))
4834 return FromAssignLeft? ImplicitConversionSequence::Better
4836 }
4837 }
4838
4839 // Ranking of member-pointer types.
4840 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4841 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4842 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4843 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4844 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4845 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4846 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4847 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4848 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4849 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4850 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4851 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4852 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4853 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4854 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4855 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4856 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4857 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4859 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4861 }
4862 // conversion of B::* to C::* is better than conversion of A::* to C::*
4863 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4864 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4866 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4868 }
4869 }
4870
4871 if (SCS1.Second == ICK_Derived_To_Base) {
4872 // -- conversion of C to B is better than conversion of C to A,
4873 // -- binding of an expression of type C to a reference of type
4874 // B& is better than binding an expression of type C to a
4875 // reference of type A&,
4876 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4877 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4878 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4880 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4882 }
4883
4884 // -- conversion of B to A is better than conversion of C to A.
4885 // -- binding of an expression of type B to a reference of type
4886 // A& is better than binding an expression of type C to a
4887 // reference of type A&,
4888 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4889 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4890 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4892 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4894 }
4895 }
4896
4898}
4899
4901 if (!T.getQualifiers().hasUnaligned())
4902 return T;
4903
4904 Qualifiers Q;
4905 T = Ctx.getUnqualifiedArrayType(T, Q);
4906 Q.removeUnaligned();
4907 return Ctx.getQualifiedType(T, Q);
4908}
4909
4910/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4911/// determine whether they are reference-compatible,
4912/// reference-related, or incompatible, for use in C++ initialization by
4913/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4914/// type, and the first type (T1) is the pointee type of the reference
4915/// type being initialized.
4918 QualType OrigT1, QualType OrigT2,
4919 ReferenceConversions *ConvOut) {
4920 assert(!OrigT1->isReferenceType() &&
4921 "T1 must be the pointee type of the reference type");
4922 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4923
4924 QualType T1 = Context.getCanonicalType(OrigT1);
4925 QualType T2 = Context.getCanonicalType(OrigT2);
4926 Qualifiers T1Quals, T2Quals;
4927 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4928 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4929
4930 ReferenceConversions ConvTmp;
4931 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4932 Conv = ReferenceConversions();
4933
4934 // C++2a [dcl.init.ref]p4:
4935 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4936 // reference-related to "cv2 T2" if T1 is similar to T2, or
4937 // T1 is a base class of T2.
4938 // "cv1 T1" is reference-compatible with "cv2 T2" if
4939 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4940 // "pointer to cv1 T1" via a standard conversion sequence.
4941
4942 // Check for standard conversions we can apply to pointers: derived-to-base
4943 // conversions, ObjC pointer conversions, and function pointer conversions.
4944 // (Qualification conversions are checked last.)
4945 QualType ConvertedT2;
4946 if (UnqualT1 == UnqualT2) {
4947 // Nothing to do.
4948 } else if (isCompleteType(Loc, OrigT2) &&
4949 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4950 Conv |= ReferenceConversions::DerivedToBase;
4951 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4952 UnqualT2->isObjCObjectOrInterfaceType() &&
4953 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4954 Conv |= ReferenceConversions::ObjC;
4955 else if (UnqualT2->isFunctionType() &&
4956 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4957 Conv |= ReferenceConversions::Function;
4958 // No need to check qualifiers; function types don't have them.
4959 return Ref_Compatible;
4960 }
4961 bool ConvertedReferent = Conv != 0;
4962
4963 // We can have a qualification conversion. Compute whether the types are
4964 // similar at the same time.
4965 bool PreviousToQualsIncludeConst = true;
4966 bool TopLevel = true;
4967 do {
4968 if (T1 == T2)
4969 break;
4970
4971 // We will need a qualification conversion.
4972 Conv |= ReferenceConversions::Qualification;
4973
4974 // Track whether we performed a qualification conversion anywhere other
4975 // than the top level. This matters for ranking reference bindings in
4976 // overload resolution.
4977 if (!TopLevel)
4978 Conv |= ReferenceConversions::NestedQualification;
4979
4980 // MS compiler ignores __unaligned qualifier for references; do the same.
4981 T1 = withoutUnaligned(Context, T1);
4982 T2 = withoutUnaligned(Context, T2);
4983
4984 // If we find a qualifier mismatch, the types are not reference-compatible,
4985 // but are still be reference-related if they're similar.
4986 bool ObjCLifetimeConversion = false;
4987 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4988 PreviousToQualsIncludeConst,
4989 ObjCLifetimeConversion))
4990 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4991 ? Ref_Related
4992 : Ref_Incompatible;
4993
4994 // FIXME: Should we track this for any level other than the first?
4995 if (ObjCLifetimeConversion)
4996 Conv |= ReferenceConversions::ObjCLifetime;
4997
4998 TopLevel = false;
4999 } while (Context.UnwrapSimilarTypes(T1, T2));
5000
5001 // At this point, if the types are reference-related, we must either have the
5002 // same inner type (ignoring qualifiers), or must have already worked out how
5003 // to convert the referent.
5004 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5005 ? Ref_Compatible
5006 : Ref_Incompatible;
5007}
5008
5009/// Look for a user-defined conversion to a value reference-compatible
5010/// with DeclType. Return true if something definite is found.
5011static bool
5013 QualType DeclType, SourceLocation DeclLoc,
5014 Expr *Init, QualType T2, bool AllowRvalues,
5015 bool AllowExplicit) {
5016 assert(T2->isRecordType() && "Can only find conversions of record types.");
5017 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5018
5019 OverloadCandidateSet CandidateSet(
5021 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5022 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5023 NamedDecl *D = *I;
5024 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5025 if (isa<UsingShadowDecl>(D))
5026 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5027
5028 FunctionTemplateDecl *ConvTemplate
5029 = dyn_cast<FunctionTemplateDecl>(D);
5030 CXXConversionDecl *Conv;
5031 if (ConvTemplate)
5032 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5033 else
5034 Conv = cast<CXXConversionDecl>(D);
5035
5036 if (AllowRvalues) {
5037 // If we are initializing an rvalue reference, don't permit conversion
5038 // functions that return lvalues.
5039 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5040 const ReferenceType *RefType
5042 if (RefType && !RefType->getPointeeType()->isFunctionType())
5043 continue;
5044 }
5045
5046 if (!ConvTemplate &&
5048 DeclLoc,
5049 Conv->getConversionType()
5054 continue;
5055 } else {
5056 // If the conversion function doesn't return a reference type,
5057 // it can't be considered for this conversion. An rvalue reference
5058 // is only acceptable if its referencee is a function type.
5059
5060 const ReferenceType *RefType =
5062 if (!RefType ||
5063 (!RefType->isLValueReferenceType() &&
5064 !RefType->getPointeeType()->isFunctionType()))
5065 continue;
5066 }
5067
5068 if (ConvTemplate)
5070 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5071 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5072 else
5074 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5075 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5076 }
5077
5078 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5079
5081 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5082 case OR_Success:
5083 // C++ [over.ics.ref]p1:
5084 //
5085 // [...] If the parameter binds directly to the result of
5086 // applying a conversion function to the argument
5087 // expression, the implicit conversion sequence is a
5088 // user-defined conversion sequence (13.3.3.1.2), with the
5089 // second standard conversion sequence either an identity
5090 // conversion or, if the conversion function returns an
5091 // entity of a type that is a derived class of the parameter
5092 // type, a derived-to-base Conversion.
5093 if (!Best->FinalConversion.DirectBinding)
5094 return false;
5095
5096 ICS.setUserDefined();
5097 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5098 ICS.UserDefined.After = Best->FinalConversion;
5099 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5100 ICS.UserDefined.ConversionFunction = Best->Function;
5101 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5102 ICS.UserDefined.EllipsisConversion = false;
5103 assert(ICS.UserDefined.After.ReferenceBinding &&
5105 "Expected a direct reference binding!");
5106 return true;
5107
5108 case OR_Ambiguous:
5109 ICS.setAmbiguous();
5110 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5111 Cand != CandidateSet.end(); ++Cand)
5112 if (Cand->Best)
5113 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5114 return true;
5115
5117 case OR_Deleted:
5118 // There was no suitable conversion, or we found a deleted
5119 // conversion; continue with other checks.
5120 return false;
5121 }
5122
5123 llvm_unreachable("Invalid OverloadResult!");
5124}
5125
5126/// Compute an implicit conversion sequence for reference
5127/// initialization.
5130 SourceLocation DeclLoc,
5131 bool SuppressUserConversions,
5132 bool AllowExplicit) {
5133 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5134
5135 // Most paths end in a failed conversion.
5138
5139 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5140 QualType T2 = Init->getType();
5141
5142 // If the initializer is the address of an overloaded function, try
5143 // to resolve the overloaded function. If all goes well, T2 is the
5144 // type of the resulting function.
5145 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5146 DeclAccessPair Found;
5148 false, Found))
5149 T2 = Fn->getType();
5150 }
5151
5152 // Compute some basic properties of the types and the initializer.
5153 bool isRValRef = DeclType->isRValueReferenceType();
5154 Expr::Classification InitCategory = Init->Classify(S.Context);
5155
5157 Sema::ReferenceCompareResult RefRelationship =
5158 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5159
5160 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5161 ICS.setStandard();
5163 // FIXME: A reference binding can be a function conversion too. We should
5164 // consider that when ordering reference-to-function bindings.
5165 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5167 : (RefConv & Sema::ReferenceConversions::ObjC)
5169 : ICK_Identity;
5171 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5172 // a reference binding that performs a non-top-level qualification
5173 // conversion as a qualification conversion, not as an identity conversion.
5174 ICS.Standard.Third = (RefConv &
5175 Sema::ReferenceConversions::NestedQualification)
5177 : ICK_Identity;
5178 ICS.Standard.setFromType(T2);
5179 ICS.Standard.setToType(0, T2);
5180 ICS.Standard.setToType(1, T1);
5181 ICS.Standard.setToType(2, T1);
5182 ICS.Standard.ReferenceBinding = true;
5183 ICS.Standard.DirectBinding = BindsDirectly;
5184 ICS.Standard.IsLvalueReference = !isRValRef;
5186 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5189 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5190 ICS.Standard.CopyConstructor = nullptr;
5192 };
5193
5194 // C++0x [dcl.init.ref]p5:
5195 // A reference to type "cv1 T1" is initialized by an expression
5196 // of type "cv2 T2" as follows:
5197
5198 // -- If reference is an lvalue reference and the initializer expression
5199 if (!isRValRef) {
5200 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5201 // reference-compatible with "cv2 T2," or
5202 //
5203 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5204 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5205 // C++ [over.ics.ref]p1:
5206 // When a parameter of reference type binds directly (8.5.3)
5207 // to an argument expression, the implicit conversion sequence
5208 // is the identity conversion, unless the argument expression
5209 // has a type that is a derived class of the parameter type,
5210 // in which case the implicit conversion sequence is a
5211 // derived-to-base Conversion (13.3.3.1).
5212 SetAsReferenceBinding(/*BindsDirectly=*/true);
5213
5214 // Nothing more to do: the inaccessibility/ambiguity check for
5215 // derived-to-base conversions is suppressed when we're
5216 // computing the implicit conversion sequence (C++
5217 // [over.best.ics]p2).
5218 return ICS;
5219 }
5220
5221 // -- has a class type (i.e., T2 is a class type), where T1 is
5222 // not reference-related to T2, and can be implicitly
5223 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5224 // is reference-compatible with "cv3 T3" 92) (this
5225 // conversion is selected by enumerating the applicable
5226 // conversion functions (13.3.1.6) and choosing the best
5227 // one through overload resolution (13.3)),
5228 if (!SuppressUserConversions && T2->isRecordType() &&
5229 S.isCompleteType(DeclLoc, T2) &&
5230 RefRelationship == Sema::Ref_Incompatible) {
5231 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5232 Init, T2, /*AllowRvalues=*/false,
5233 AllowExplicit))
5234 return ICS;
5235 }
5236 }
5237
5238 // -- Otherwise, the reference shall be an lvalue reference to a
5239 // non-volatile const type (i.e., cv1 shall be const), or the reference
5240 // shall be an rvalue reference.
5241 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5242 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5244 return ICS;
5245 }
5246
5247 // -- If the initializer expression
5248 //
5249 // -- is an xvalue, class prvalue, array prvalue or function
5250 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5251 if (RefRelationship == Sema::Ref_Compatible &&
5252 (InitCategory.isXValue() ||
5253 (InitCategory.isPRValue() &&
5254 (T2->isRecordType() || T2->isArrayType())) ||
5255 (InitCategory.isLValue() && T2->isFunctionType()))) {
5256 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5257 // binding unless we're binding to a class prvalue.
5258 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5259 // allow the use of rvalue references in C++98/03 for the benefit of
5260 // standard library implementors; therefore, we need the xvalue check here.
5261 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5262 !(InitCategory.isPRValue() || T2->isRecordType()));
5263 return ICS;
5264 }
5265
5266 // -- has a class type (i.e., T2 is a class type), where T1 is not
5267 // reference-related to T2, and can be implicitly converted to
5268 // an xvalue, class prvalue, or function lvalue of type
5269 // "cv3 T3", where "cv1 T1" is reference-compatible with
5270 // "cv3 T3",
5271 //
5272 // then the reference is bound to the value of the initializer
5273 // expression in the first case and to the result of the conversion
5274 // in the second case (or, in either case, to an appropriate base
5275 // class subobject).
5276 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5277 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5278 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5279 Init, T2, /*AllowRvalues=*/true,
5280 AllowExplicit)) {
5281 // In the second case, if the reference is an rvalue reference
5282 // and the second standard conversion sequence of the
5283 // user-defined conversion sequence includes an lvalue-to-rvalue
5284 // conversion, the program is ill-formed.
5285 if (ICS.isUserDefined() && isRValRef &&
5288
5289 return ICS;
5290 }
5291
5292 // A temporary of function type cannot be created; don't even try.
5293 if (T1->isFunctionType())
5294 return ICS;
5295
5296 // -- Otherwise, a temporary of type "cv1 T1" is created and
5297 // initialized from the initializer expression using the
5298 // rules for a non-reference copy initialization (8.5). The
5299 // reference is then bound to the temporary. If T1 is
5300 // reference-related to T2, cv1 must be the same
5301 // cv-qualification as, or greater cv-qualification than,
5302 // cv2; otherwise, the program is ill-formed.
5303 if (RefRelationship == Sema::Ref_Related) {
5304 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5305 // we would be reference-compatible or reference-compatible with
5306 // added qualification. But that wasn't the case, so the reference
5307 // initialization fails.
5308 //
5309 // Note that we only want to check address spaces and cvr-qualifiers here.
5310 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5311 Qualifiers T1Quals = T1.getQualifiers();
5312 Qualifiers T2Quals = T2.getQualifiers();
5313 T1Quals.removeObjCGCAttr();
5314 T1Quals.removeObjCLifetime();
5315 T2Quals.removeObjCGCAttr();
5316 T2Quals.removeObjCLifetime();
5317 // MS compiler ignores __unaligned qualifier for references; do the same.
5318 T1Quals.removeUnaligned();
5319 T2Quals.removeUnaligned();
5320 if (!T1Quals.compatiblyIncludes(T2Quals))
5321 return ICS;
5322 }
5323
5324 // If at least one of the types is a class type, the types are not
5325 // related, and we aren't allowed any user conversions, the
5326 // reference binding fails. This case is important for breaking
5327 // recursion, since TryImplicitConversion below will attempt to
5328 // create a temporary through the use of a copy constructor.
5329 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5330 (T1->isRecordType() || T2->isRecordType()))
5331 return ICS;
5332
5333 // If T1 is reference-related to T2 and the reference is an rvalue
5334 // reference, the initializer expression shall not be an lvalue.
5335 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5336 Init->Classify(S.Context).isLValue()) {
5338 return ICS;
5339 }
5340
5341 // C++ [over.ics.ref]p2:
5342 // When a parameter of reference type is not bound directly to
5343 // an argument expression, the conversion sequence is the one
5344 // required to convert the argument expression to the
5345 // underlying type of the reference according to
5346 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5347 // to copy-initializing a temporary of the underlying type with
5348 // the argument expression. Any difference in top-level
5349 // cv-qualification is subsumed by the initialization itself
5350 // and does not constitute a conversion.
5351 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5352 AllowedExplicit::None,
5353 /*InOverloadResolution=*/false,
5354 /*CStyle=*/false,
5355 /*AllowObjCWritebackConversion=*/false,
5356 /*AllowObjCConversionOnExplicit=*/false);
5357
5358 // Of course, that's still a reference binding.
5359 if (ICS.isStandard()) {
5360 ICS.Standard.ReferenceBinding = true;
5361 ICS.Standard.IsLvalueReference = !isRValRef;
5362 ICS.Standard.BindsToFunctionLvalue = false;
5363 ICS.Standard.BindsToRvalue = true;
5366 } else if (ICS.isUserDefined()) {
5367 const ReferenceType *LValRefType =
5370
5371 // C++ [over.ics.ref]p3:
5372 // Except for an implicit object parameter, for which see 13.3.1, a
5373 // standard conversion sequence cannot be formed if it requires [...]
5374 // binding an rvalue reference to an lvalue other than a function
5375 // lvalue.
5376 // Note that the function case is not possible here.
5377 if (isRValRef && LValRefType) {
5379 return ICS;
5380 }
5381
5383 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5385 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5388 }
5389
5390 return ICS;
5391}
5392
5394TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5395 bool SuppressUserConversions,
5396 bool InOverloadResolution,
5397 bool AllowObjCWritebackConversion,
5398 bool AllowExplicit = false);
5399
5400/// TryListConversion - Try to copy-initialize a value of type ToType from the
5401/// initializer list From.
5404 bool SuppressUserConversions,
5405 bool InOverloadResolution,
5406 bool AllowObjCWritebackConversion) {
5407 // C++11 [over.ics.list]p1:
5408 // When an argument is an initializer list, it is not an expression and
5409 // special rules apply for converting it to a parameter type.
5410
5412 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5413
5414 // We need a complete type for what follows. With one C++20 exception,
5415 // incomplete types can never be initialized from init lists.
5416 QualType InitTy = ToType;
5417 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5418 if (AT && S.getLangOpts().CPlusPlus20)
5419 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5420 // C++20 allows list initialization of an incomplete array type.
5421 InitTy = IAT->getElementType();
5422 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5423 return Result;
5424
5425 // C++20 [over.ics.list]/2:
5426 // If the initializer list is a designated-initializer-list, a conversion
5427 // is only possible if the parameter has an aggregate type
5428 //
5429 // FIXME: The exception for reference initialization here is not part of the
5430 // language rules, but follow other compilers in adding it as a tentative DR
5431 // resolution.
5432 bool IsDesignatedInit = From->hasDesignatedInit();
5433 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5434 IsDesignatedInit)
5435 return Result;
5436
5437 // Per DR1467:
5438 // If the parameter type is a class X and the initializer list has a single
5439 // element of type cv U, where U is X or a class derived from X, the
5440 // implicit conversion sequence is the one required to convert the element
5441 // to the parameter type.
5442 //
5443 // Otherwise, if the parameter type is a character array [... ]
5444 // and the initializer list has a single element that is an
5445 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5446 // implicit conversion sequence is the identity conversion.
5447 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5448 if (ToType->isRecordType()) {
5449 QualType InitType = From->getInit(0)->getType();
5450 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5451 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5452 return TryCopyInitialization(S, From->getInit(0), ToType,
5453 SuppressUserConversions,
5454 InOverloadResolution,
5455 AllowObjCWritebackConversion);
5456 }
5457
5458 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5459 InitializedEntity Entity =
5461 /*Consumed=*/false);
5462 if (S.CanPerformCopyInitialization(Entity, From)) {
5463 Result.setStandard();
5464 Result.Standard.setAsIdentityConversion();
5465 Result.Standard.setFromType(ToType);
5466 Result.Standard.setAllToTypes(ToType);
5467 return Result;
5468 }
5469 }
5470 }
5471
5472 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5473 // C++11 [over.ics.list]p2:
5474 // If the parameter type is std::initializer_list<X> or "array of X" and
5475 // all the elements can be implicitly converted to X, the implicit
5476 // conversion sequence is the worst conversion necessary to convert an
5477 // element of the list to X.
5478 //
5479 // C++14 [over.ics.list]p3:
5480 // Otherwise, if the parameter type is "array of N X", if the initializer
5481 // list has exactly N elements or if it has fewer than N elements and X is
5482 // default-constructible, and if all the elements of the initializer list
5483 // can be implicitly converted to X, the implicit conversion sequence is
5484 // the worst conversion necessary to convert an element of the list to X.
5485 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5486 unsigned e = From->getNumInits();
5489 QualType());
5490 QualType ContTy = ToType;
5491 bool IsUnbounded = false;
5492 if (AT) {
5493 InitTy = AT->getElementType();
5494 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5495 if (CT->getSize().ult(e)) {
5496 // Too many inits, fatally bad
5498 ToType);
5499 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5500 return Result;
5501 }
5502 if (CT->getSize().ugt(e)) {
5503 // Need an init from empty {}, is there one?
5504 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5505 From->getEndLoc());
5506 EmptyList.setType(S.Context.VoidTy);
5507 DfltElt = TryListConversion(
5508 S, &EmptyList, InitTy, SuppressUserConversions,
5509 InOverloadResolution, AllowObjCWritebackConversion);
5510 if (DfltElt.isBad()) {
5511 // No {} init, fatally bad
5513 ToType);
5514 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5515 return Result;
5516 }
5517 }
5518 } else {
5519 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5520 IsUnbounded = true;
5521 if (!e) {
5522 // Cannot convert to zero-sized.
5524 ToType);
5525 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5526 return Result;
5527 }
5528 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5529 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5531 }
5532 }
5533
5534 Result.setStandard();
5535 Result.Standard.setAsIdentityConversion();
5536 Result.Standard.setFromType(InitTy);
5537 Result.Standard.setAllToTypes(InitTy);
5538 for (unsigned i = 0; i < e; ++i) {
5539 Expr *Init = From->getInit(i);
5541 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5542 AllowObjCWritebackConversion);
5543
5544 // Keep the worse conversion seen so far.
5545 // FIXME: Sequences are not totally ordered, so 'worse' can be
5546 // ambiguous. CWG has been informed.
5548 Result) ==
5550 Result = ICS;
5551 // Bail as soon as we find something unconvertible.
5552 if (Result.isBad()) {
5553 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5554 return Result;
5555 }
5556 }
5557 }
5558
5559 // If we needed any implicit {} initialization, compare that now.
5560 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5561 // has been informed that this might not be the best thing.
5562 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5563 S, From->getEndLoc(), DfltElt, Result) ==
5565 Result = DfltElt;
5566 // Record the type being initialized so that we may compare sequences
5567 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5568 return Result;
5569 }
5570
5571 // C++14 [over.ics.list]p4:
5572 // C++11 [over.ics.list]p3:
5573 // Otherwise, if the parameter is a non-aggregate class X and overload
5574 // resolution chooses a single best constructor [...] the implicit
5575 // conversion sequence is a user-defined conversion sequence. If multiple
5576 // constructors are viable but none is better than the others, the
5577 // implicit conversion sequence is a user-defined conversion sequence.
5578 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5579 // This function can deal with initializer lists.
5580 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5581 AllowedExplicit::None,
5582 InOverloadResolution, /*CStyle=*/false,
5583 AllowObjCWritebackConversion,
5584 /*AllowObjCConversionOnExplicit=*/false);
5585 }
5586
5587 // C++14 [over.ics.list]p5:
5588 // C++11 [over.ics.list]p4:
5589 // Otherwise, if the parameter has an aggregate type which can be
5590 // initialized from the initializer list [...] the implicit conversion
5591 // sequence is a user-defined conversion sequence.
5592 if (ToType->isAggregateType()) {
5593 // Type is an aggregate, argument is an init list. At this point it comes
5594 // down to checking whether the initialization works.
5595 // FIXME: Find out whether this parameter is consumed or not.
5596 InitializedEntity Entity =
5598 /*Consumed=*/false);
5600 From)) {
5601 Result.setUserDefined();
5602 Result.UserDefined.Before.setAsIdentityConversion();
5603 // Initializer lists don't have a type.
5604 Result.UserDefined.Before.setFromType(QualType());
5605 Result.UserDefined.Before.setAllToTypes(QualType());
5606
5607 Result.UserDefined.After.setAsIdentityConversion();
5608 Result.UserDefined.After.setFromType(ToType);
5609 Result.UserDefined.After.setAllToTypes(ToType);
5610 Result.UserDefined.ConversionFunction = nullptr;
5611 }
5612 return Result;
5613 }
5614
5615 // C++14 [over.ics.list]p6:
5616 // C++11 [over.ics.list]p5:
5617 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5618 if (ToType->isReferenceType()) {
5619 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5620 // mention initializer lists in any way. So we go by what list-
5621 // initialization would do and try to extrapolate from that.
5622
5623 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5624
5625 // If the initializer list has a single element that is reference-related
5626 // to the parameter type, we initialize the reference from that.
5627 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5628 Expr *Init = From->getInit(0);
5629
5630 QualType T2 = Init->getType();
5631
5632 // If the initializer is the address of an overloaded function, try
5633 // to resolve the overloaded function. If all goes well, T2 is the
5634 // type of the resulting function.
5635 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5636 DeclAccessPair Found;
5638 Init, ToType, false, Found))
5639 T2 = Fn->getType();
5640 }
5641
5642 // Compute some basic properties of the types and the initializer.
5643 Sema::ReferenceCompareResult RefRelationship =
5644 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5645
5646 if (RefRelationship >= Sema::Ref_Related) {
5647 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5648 SuppressUserConversions,
5649 /*AllowExplicit=*/false);
5650 }
5651 }
5652
5653 // Otherwise, we bind the reference to a temporary created from the
5654 // initializer list.
5655 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5656 InOverloadResolution,
5657 AllowObjCWritebackConversion);
5658 if (Result.isFailure())
5659 return Result;
5660 assert(!Result.isEllipsis() &&
5661 "Sub-initialization cannot result in ellipsis conversion.");
5662
5663 // Can we even bind to a temporary?
5664 if (ToType->isRValueReferenceType() ||
5665 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5666 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5667 Result.UserDefined.After;
5668 SCS.ReferenceBinding = true;
5670 SCS.BindsToRvalue = true;
5671 SCS.BindsToFunctionLvalue = false;
5674 } else
5676 From, ToType);
5677 return Result;
5678 }
5679
5680 // C++14 [over.ics.list]p7:
5681 // C++11 [over.ics.list]p6:
5682 // Otherwise, if the parameter type is not a class:
5683 if (!ToType->isRecordType()) {
5684 // - if the initializer list has one element that is not itself an
5685 // initializer list, the implicit conversion sequence is the one
5686 // required to convert the element to the parameter type.
5687 unsigned NumInits = From->getNumInits();
5688 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5689 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5690 SuppressUserConversions,
5691 InOverloadResolution,
5692 AllowObjCWritebackConversion);
5693 // - if the initializer list has no elements, the implicit conversion
5694 // sequence is the identity conversion.
5695 else if (NumInits == 0) {
5696 Result.setStandard();
5697 Result.Standard.setAsIdentityConversion();
5698 Result.Standard.setFromType(ToType);
5699 Result.Standard.setAllToTypes(ToType);
5700 }
5701 return Result;
5702 }
5703
5704 // C++14 [over.ics.list]p8:
5705 // C++11 [over.ics.list]p7:
5706 // In all cases other than those enumerated above, no conversion is possible
5707 return Result;
5708}
5709
5710/// TryCopyInitialization - Try to copy-initialize a value of type
5711/// ToType from the expression From. Return the implicit conversion
5712/// sequence required to pass this argument, which may be a bad
5713/// conversion sequence (meaning that the argument cannot be passed to
5714/// a parameter of this type). If @p SuppressUserConversions, then we
5715/// do not permit any user-defined conversion sequences.
5718 bool SuppressUserConversions,
5719 bool InOverloadResolution,
5720 bool AllowObjCWritebackConversion,
5721 bool AllowExplicit) {
5722 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5723 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5724 InOverloadResolution,AllowObjCWritebackConversion);
5725
5726 if (ToType->isReferenceType())
5727 return TryReferenceInit(S, From, ToType,
5728 /*FIXME:*/ From->getBeginLoc(),
5729 SuppressUserConversions, AllowExplicit);
5730
5731 return TryImplicitConversion(S, From, ToType,
5732 SuppressUserConversions,
5733 AllowedExplicit::None,
5734 InOverloadResolution,
5735 /*CStyle=*/false,
5736 AllowObjCWritebackConversion,
5737 /*AllowObjCConversionOnExplicit=*/false);
5738}
5739
5740static bool TryCopyInitialization(const CanQualType FromQTy,
5741 const CanQualType ToQTy,
5742 Sema &S,
5743 SourceLocation Loc,
5744 ExprValueKind FromVK) {
5745 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5747 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5748
5749 return !ICS.isBad();
5750}
5751
5752/// TryObjectArgumentInitialization - Try to initialize the object
5753/// parameter of the given member function (@c Method) from the
5754/// expression @p From.
5756 Sema &S, SourceLocation Loc, QualType FromType,
5757 Expr::Classification FromClassification, CXXMethodDecl *Method,
5758 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5759 QualType ExplicitParameterType = QualType(),
5760 bool SuppressUserConversion = false) {
5761
5762 // We need to have an object of class type.
5763 if (const auto *PT = FromType->getAs<PointerType>()) {
5764 FromType = PT->getPointeeType();
5765
5766 // When we had a pointer, it's implicitly dereferenced, so we
5767 // better have an lvalue.
5768 assert(FromClassification.isLValue());
5769 }
5770
5771 auto ValueKindFromClassification = [](Expr::Classification C) {
5772 if (C.isPRValue())
5773 return clang::VK_PRValue;
5774 if (C.isXValue())
5775 return VK_XValue;
5776 return clang::VK_LValue;
5777 };
5778
5779 if (Method->isExplicitObjectMemberFunction()) {
5780 if (ExplicitParameterType.isNull())
5781 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5782 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5783 ValueKindFromClassification(FromClassification));
5785 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5786 /*InOverloadResolution=*/true, false);
5787 if (ICS.isBad())
5788 ICS.Bad.FromExpr = nullptr;
5789 return ICS;
5790 }
5791
5792 assert(FromType->isRecordType());
5793
5794 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5795 // C++98 [class.dtor]p2:
5796 // A destructor can be invoked for a const, volatile or const volatile
5797 // object.
5798 // C++98 [over.match.funcs]p4:
5799 // For static member functions, the implicit object parameter is considered
5800 // to match any object (since if the function is selected, the object is
5801 // discarded).
5802 Qualifiers Quals = Method->getMethodQualifiers();
5803 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5804 Quals.addConst();
5805 Quals.addVolatile();
5806 }
5807
5808 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5809
5810 // Set up the conversion sequence as a "bad" conversion, to allow us
5811 // to exit early.
5813
5814 // C++0x [over.match.funcs]p4:
5815 // For non-static member functions, the type of the implicit object
5816 // parameter is
5817 //
5818 // - "lvalue reference to cv X" for functions declared without a
5819 // ref-qualifier or with the & ref-qualifier
5820 // - "rvalue reference to cv X" for functions declared with the &&
5821 // ref-qualifier
5822 //
5823 // where X is the class of which the function is a member and cv is the
5824 // cv-qualification on the member function declaration.
5825 //
5826 // However, when finding an implicit conversion sequence for the argument, we
5827 // are not allowed to perform user-defined conversions
5828 // (C++ [over.match.funcs]p5). We perform a simplified version of
5829 // reference binding here, that allows class rvalues to bind to
5830 // non-constant references.
5831
5832 // First check the qualifiers.
5833 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5834 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5835 if (ImplicitParamType.getCVRQualifiers() !=
5836 FromTypeCanon.getLocalCVRQualifiers() &&
5837 !ImplicitParamType.isAtLeastAsQualifiedAs(
5838 withoutUnaligned(S.Context, FromTypeCanon))) {
5840 FromType, ImplicitParamType);
5841 return ICS;
5842 }
5843
5844 if (FromTypeCanon.hasAddressSpace()) {
5845 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5846 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5847 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5849 FromType, ImplicitParamType);
5850 return ICS;
5851 }
5852 }
5853
5854 // Check that we have either the same type or a derived type. It
5855 // affects the conversion rank.
5856 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5857 ImplicitConversionKind SecondKind;
5858 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5859 SecondKind = ICK_Identity;
5860 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5861 SecondKind = ICK_Derived_To_Base;
5862 } else if (!Method->isExplicitObjectMemberFunction()) {
5864 FromType, ImplicitParamType);
5865 return ICS;
5866 }
5867
5868 // Check the ref-qualifier.
5869 switch (Method->getRefQualifier()) {
5870 case RQ_None:
5871 // Do nothing; we don't care about lvalueness or rvalueness.
5872 break;
5873
5874 case RQ_LValue:
5875 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5876 // non-const lvalue reference cannot bind to an rvalue
5878 ImplicitParamType);
5879 return ICS;
5880 }
5881 break;
5882
5883 case RQ_RValue:
5884 if (!FromClassification.isRValue()) {
5885 // rvalue reference cannot bind to an lvalue
5887 ImplicitParamType);
5888 return ICS;
5889 }
5890 break;
5891 }
5892
5893 // Success. Mark this as a reference binding.
5894 ICS.setStandard();
5896 ICS.Standard.Second = SecondKind;
5897 ICS.Standard.setFromType(FromType);
5898 ICS.Standard.setAllToTypes(ImplicitParamType);
5899 ICS.Standard.ReferenceBinding = true;
5900 ICS.Standard.DirectBinding = true;
5902 ICS.Standard.BindsToFunctionLvalue = false;
5903 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5905 = (Method->getRefQualifier() == RQ_None);
5906 return ICS;
5907}
5908
5909/// PerformObjectArgumentInitialization - Perform initialization of
5910/// the implicit object parameter for the given Method with the given
5911/// expression.
5913 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5914 CXXMethodDecl *Method) {
5915 QualType FromRecordType, DestType;
5916 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5917
5918 Expr::Classification FromClassification;
5919 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5920 FromRecordType = PT->getPointeeType();
5921 DestType = Method->getThisType();
5922 FromClassification = Expr::Classification::makeSimpleLValue();
5923 } else {
5924 FromRecordType = From->getType();
5925 DestType = ImplicitParamRecordType;
5926 FromClassification = From->Classify(Context);
5927
5928 // When performing member access on a prvalue, materialize a temporary.
5929 if (From->isPRValue()) {
5930 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5931 Method->getRefQualifier() !=
5933 }
5934 }
5935
5936 // Note that we always use the true parent context when performing
5937 // the actual argument initialization.
5939 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5940 Method->getParent());
5941 if (ICS.isBad()) {
5942 switch (ICS.Bad.Kind) {
5944 Qualifiers FromQs = FromRecordType.getQualifiers();
5945 Qualifiers ToQs = DestType.getQualifiers();
5946 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5947 if (CVR) {
5948 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5949 << Method->getDeclName() << FromRecordType << (CVR - 1)
5950 << From->getSourceRange();
5951 Diag(Method->getLocation(), diag::note_previous_decl)
5952 << Method->getDeclName();
5953 return ExprError();
5954 }
5955 break;
5956 }
5957
5960 bool IsRValueQualified =
5962 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5963 << Method->getDeclName() << FromClassification.isRValue()
5964 << IsRValueQualified;
5965 Diag(Method->getLocation(), diag::note_previous_decl)
5966 << Method->getDeclName();
5967 return ExprError();
5968 }
5969
5972 break;
5973
5976 llvm_unreachable("Lists are not objects");
5977 }
5978
5979 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5980 << ImplicitParamRecordType << FromRecordType
5981 << From->getSourceRange();
5982 }
5983
5984 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5985 ExprResult FromRes =
5986 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5987 if (FromRes.isInvalid())
5988 return ExprError();
5989 From = FromRes.get();
5990 }
5991
5992 if (!Context.hasSameType(From->getType(), DestType)) {
5993 CastKind CK;
5994 QualType PteeTy = DestType->getPointeeType();
5995 LangAS DestAS =
5996 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5997 if (FromRecordType.getAddressSpace() != DestAS)
5998 CK = CK_AddressSpaceConversion;
5999 else
6000 CK = CK_NoOp;
6001 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6002 }
6003 return From;
6004}
6005
6006/// TryContextuallyConvertToBool - Attempt to contextually convert the
6007/// expression From to bool (C++0x [conv]p3).
6010 // C++ [dcl.init]/17.8:
6011 // - Otherwise, if the initialization is direct-initialization, the source
6012 // type is std::nullptr_t, and the destination type is bool, the initial
6013 // value of the object being initialized is false.
6014 if (From->getType()->isNullPtrType())
6016 S.Context.BoolTy,
6017 From->isGLValue());
6018
6019 // All other direct-initialization of bool is equivalent to an implicit
6020 // conversion to bool in which explicit conversions are permitted.
6021 return TryImplicitConversion(S, From, S.Context.BoolTy,
6022 /*SuppressUserConversions=*/false,
6023 AllowedExplicit::Conversions,
6024 /*InOverloadResolution=*/false,
6025 /*CStyle=*/false,
6026 /*AllowObjCWritebackConversion=*/false,
6027 /*AllowObjCConversionOnExplicit=*/false);
6028}
6029
6030/// PerformContextuallyConvertToBool - Perform a contextual conversion
6031/// of the expression From to bool (C++0x [conv]p3).
6033 if (checkPlaceholderForOverload(*this, From))
6034 return ExprError();
6035
6037 if (!ICS.isBad())
6038 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
6039
6040 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6041 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6042 << From->getType() << From->getSourceRange();
6043 return ExprError();
6044}
6045
6046/// Check that the specified conversion is permitted in a converted constant
6047/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6048/// is acceptable.
6051 // Since we know that the target type is an integral or unscoped enumeration
6052 // type, most conversion kinds are impossible. All possible First and Third
6053 // conversions are fine.
6054 switch (SCS.Second) {
6055 case ICK_Identity:
6057 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6059 return true;
6060
6062 // Conversion from an integral or unscoped enumeration type to bool is
6063 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6064 // conversion, so we allow it in a converted constant expression.
6065 //
6066 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6067 // a lot of popular code. We should at least add a warning for this
6068 // (non-conforming) extension.
6070 SCS.getToType(2)->isBooleanType();
6071
6073 case ICK_Pointer_Member:
6074 // C++1z: null pointer conversions and null member pointer conversions are
6075 // only permitted if the source type is std::nullptr_t.
6076 return SCS.getFromType()->isNullPtrType();
6077
6088 case ICK_Vector_Splat:
6089 case ICK_Complex_Real:
6098 return false;
6099
6103 llvm_unreachable("found a first conversion kind in Second");
6104
6106 case ICK_Qualification:
6107 llvm_unreachable("found a third conversion kind in Second");
6108
6110 break;
6111 }
6112
6113 llvm_unreachable("unknown conversion kind");
6114}
6115
6116/// BuildConvertedConstantExpression - Check that the expression From is a
6117/// converted constant expression of type T, perform the conversion but
6118/// does not evaluate the expression
6120 QualType T,
6121 Sema::CCEKind CCE,
6122 NamedDecl *Dest,
6123 APValue &PreNarrowingValue) {
6124 assert(S.getLangOpts().CPlusPlus11 &&
6125 "converted constant expression outside C++11");
6126
6127 if (checkPlaceholderForOverload(S, From))
6128 return ExprError();
6129
6130 // C++1z [expr.const]p3:
6131 // A converted constant expression of type T is an expression,
6132 // implicitly converted to type T, where the converted
6133 // expression is a constant expression and the implicit conversion
6134 // sequence contains only [... list of conversions ...].
6138 : TryCopyInitialization(S, From, T,
6139 /*SuppressUserConversions=*/false,
6140 /*InOverloadResolution=*/false,
6141 /*AllowObjCWritebackConversion=*/false,
6142 /*AllowExplicit=*/false);
6143 StandardConversionSequence *SCS = nullptr;
6144 switch (ICS.getKind()) {
6146 SCS = &ICS.Standard;
6147 break;
6149 if (T->isRecordType())
6150 SCS = &ICS.UserDefined.Before;
6151 else
6152 SCS = &ICS.UserDefined.After;
6153 break;
6157 return S.Diag(From->getBeginLoc(),
6158 diag::err_typecheck_converted_constant_expression)
6159 << From->getType() << From->getSourceRange() << T;
6160 return ExprError();
6161
6164 llvm_unreachable("bad conversion in converted constant expression");
6165 }
6166
6167 // Check that we would only use permitted conversions.
6168 if (!CheckConvertedConstantConversions(S, *SCS)) {
6169 return S.Diag(From->getBeginLoc(),
6170 diag::err_typecheck_converted_constant_expression_disallowed)
6171 << From->getType() << From->getSourceRange() << T;
6172 }
6173 // [...] and where the reference binding (if any) binds directly.
6174 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6175 return S.Diag(From->getBeginLoc(),
6176 diag::err_typecheck_converted_constant_expression_indirect)
6177 << From->getType() << From->getSourceRange() << T;
6178 }
6179 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6180 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6181 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6182 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6183 // case explicitly.
6184 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6185 return S.Diag(From->getBeginLoc(),
6186 diag::err_reference_bind_to_bitfield_in_cce)
6187 << From->getSourceRange();
6188 }
6189
6190 // Usually we can simply apply the ImplicitConversionSequence we formed
6191 // earlier, but that's not guaranteed to work when initializing an object of
6192 // class type.
6194 if (T->isRecordType()) {
6195 assert(CCE == Sema::CCEK_TemplateArg &&
6196 "unexpected class type converted constant expr");
6199 T, cast<NonTypeTemplateParmDecl>(Dest)),
6200 SourceLocation(), From);
6201 } else {
6203 }
6204 if (Result.isInvalid())
6205 return Result;
6206
6207 // C++2a [intro.execution]p5:
6208 // A full-expression is [...] a constant-expression [...]
6209 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6210 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6212 if (Result.isInvalid())
6213 return Result;
6214
6215 // Check for a narrowing implicit conversion.
6216 bool ReturnPreNarrowingValue = false;
6217 QualType PreNarrowingType;
6218 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6219 PreNarrowingType)) {
6221 // Implicit conversion to a narrower type, but the expression is
6222 // value-dependent so we can't tell whether it's actually narrowing.
6224 // Implicit conversion to a narrower type, and the value is not a constant
6225 // expression. We'll diagnose this in a moment.
6226 case NK_Not_Narrowing:
6227 break;
6228
6230 if (CCE == Sema::CCEK_ArrayBound &&
6231 PreNarrowingType->isIntegralOrEnumerationType() &&
6232 PreNarrowingValue.isInt()) {
6233 // Don't diagnose array bound narrowing here; we produce more precise
6234 // errors by allowing the un-narrowed value through.
6235 ReturnPreNarrowingValue = true;
6236 break;
6237 }
6238 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6239 << CCE << /*Constant*/ 1
6240 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6241 break;
6242
6243 case NK_Type_Narrowing:
6244 // FIXME: It would be better to diagnose that the expression is not a
6245 // constant expression.
6246 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6247 << CCE << /*Constant*/ 0 << From->getType() << T;
6248 break;
6249 }
6250 if (!ReturnPreNarrowingValue)
6251 PreNarrowingValue = {};
6252
6253 return Result;
6254}
6255
6256/// CheckConvertedConstantExpression - Check that the expression From is a
6257/// converted constant expression of type T, perform the conversion and produce
6258/// the converted expression, per C++11 [expr.const]p3.
6261 Sema::CCEKind CCE,
6262 bool RequireInt,
6263 NamedDecl *Dest) {
6264
6265 APValue PreNarrowingValue;
6266 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6267 PreNarrowingValue);
6268 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6269 Value = APValue();
6270 return Result;
6271 }
6272 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6273 RequireInt, PreNarrowingValue);
6274}
6275
6277 CCEKind CCE,
6278 NamedDecl *Dest) {
6279 APValue PreNarrowingValue;
6280 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6281 PreNarrowingValue);
6282}
6283
6285 APValue &Value, CCEKind CCE,
6286 NamedDecl *Dest) {
6287 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6288 Dest);
6289}
6290
6292 llvm::APSInt &Value,
6293 CCEKind CCE) {
6294 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6295
6296 APValue V;
6297 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6298 /*Dest=*/nullptr);
6299 if (!R.isInvalid() && !R.get()->isValueDependent())
6300 Value = V.getInt();
6301 return R;
6302}
6303
6304/// EvaluateConvertedConstantExpression - Evaluate an Expression
6305/// That is a converted constant expression
6306/// (which was built with BuildConvertedConstantExpression)
6309 Sema::CCEKind CCE, bool RequireInt,
6310 const APValue &PreNarrowingValue) {
6311
6312 ExprResult Result = E;
6313 // Check the expression is a constant expression.
6315 Expr::EvalResult Eval;
6316 Eval.Diag = &Notes;
6317
6318 ConstantExprKind Kind;
6319 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6320 Kind = ConstantExprKind::ClassTemplateArgument;
6321 else if (CCE == Sema::CCEK_TemplateArg)
6322 Kind = ConstantExprKind::NonClassTemplateArgument;
6323 else
6324 Kind = ConstantExprKind::Normal;
6325
6326 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6327 (RequireInt && !Eval.Val.isInt())) {
6328 // The expression can't be folded, so we can't keep it at this position in
6329 // the AST.
6330 Result = ExprError();
6331 } else {
6332 Value = Eval.Val;
6333
6334 if (Notes.empty()) {
6335 // It's a constant expression.
6336 Expr *E = Result.get();
6337 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6338 // We expect a ConstantExpr to have a value associated with it
6339 // by this point.
6340 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6341 "ConstantExpr has no value associated with it");
6342 } else {
6343 E = ConstantExpr::Create(Context, Result.get(), Value);
6344 }
6345 if (!PreNarrowingValue.isAbsent())
6346 Value = std::move(PreNarrowingValue);
6347 return E;
6348 }
6349 }
6350
6351 // It's not a constant expression. Produce an appropriate diagnostic.
6352 if (Notes.size() == 1 &&
6353 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6354 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6355 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6356 diag::note_constexpr_invalid_template_arg) {
6357 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6358 for (unsigned I = 0; I < Notes.size(); ++I)
6359 Diag(Notes[I].first, Notes[I].second);
6360 } else {
6361 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6362 << CCE << E->getSourceRange();
6363 for (unsigned I = 0; I < Notes.size(); ++I)
6364 Diag(Notes[I].first, Notes[I].second);
6365 }
6366 return ExprError();
6367}
6368
6369/// dropPointerConversions - If the given standard conversion sequence
6370/// involves any pointer conversions, remove them. This may change
6371/// the result type of the conversion sequence.
6373 if (SCS.Second == ICK_Pointer_Conversion) {
6374 SCS.Second = ICK_Identity;
6375 SCS.Element = ICK_Identity;
6376 SCS.Third = ICK_Identity;
6377 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6378 }
6379}
6380
6381/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6382/// convert the expression From to an Objective-C pointer type.
6385 // Do an implicit conversion to 'id'.
6388 = TryImplicitConversion(S, From, Ty,
6389 // FIXME: Are these flags correct?
6390 /*SuppressUserConversions=*/false,
6391 AllowedExplicit::Conversions,
6392 /*InOverloadResolution=*/false,
6393 /*CStyle=*/false,
6394 /*AllowObjCWritebackConversion=*/false,
6395 /*AllowObjCConversionOnExplicit=*/true);
6396
6397 // Strip off any final conversions to 'id'.
6398 switch (ICS.getKind()) {
6403 break;
6404
6407 break;
6408
6411 break;
6412 }
6413
6414 return ICS;
6415}
6416
6417/// PerformContextuallyConvertToObjCPointer - Perform a contextual
6418/// conversion of the expression From to an Objective-C pointer type.
6419/// Returns a valid but null ExprResult if no conversion sequence exists.
6421 if (checkPlaceholderForOverload(*this, From))
6422 return ExprError();
6423
6424 QualType Ty = Context.getObjCIdType();
6427 if (!ICS.isBad())
6428 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6429 return ExprResult();
6430}
6431
6432static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6433 const Expr *Base = nullptr;
6434 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6435 "expected a member expression");
6436
6437 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6438 M && !M->isImplicitAccess())
6439 Base = M->getBase();
6440 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6441 M && !M->isImplicitAccess())
6442 Base = M->getBase();
6443
6444 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6445
6446 if (T->isPointerType())
6447 T = T->getPointeeType();
6448
6449 return T;
6450}
6451
6453 const FunctionDecl *Fun) {
6454 QualType ObjType = Obj->getType();
6455 if (ObjType->isPointerType()) {
6456 ObjType = ObjType->getPointeeType();
6457 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6459 /*CanOverflow=*/false, FPOptionsOverride());
6460 }
6461 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6463 ObjType, Obj,
6465 }
6466 return Obj;
6467}
6468
6470 FunctionDecl *Fun) {
6471 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6474 Obj->getExprLoc(), Obj);
6475}
6476
6478 Expr *Object, MultiExprArg &Args,
6479 SmallVectorImpl<Expr *> &NewArgs) {
6480 assert(Method->isExplicitObjectMemberFunction() &&
6481 "Method is not an explicit member function");
6482 assert(NewArgs.empty() && "NewArgs should be empty");
6483 NewArgs.reserve(Args.size() + 1);
6484 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6485 NewArgs.push_back(This);
6486 NewArgs.append(Args.begin(), Args.end());
6487 Args = NewArgs;
6488}
6489
6490/// Determine whether the provided type is an integral type, or an enumeration
6491/// type of a permitted flavor.
6493 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6495}
6496
6497static ExprResult
6500 QualType T, UnresolvedSetImpl &ViableConversions) {
6501
6502 if (Converter.Suppress)
6503 return ExprError();
6504
6505 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6506 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6507 CXXConversionDecl *Conv =
6508 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6510 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6511 }
6512 return From;
6513}
6514
6515static bool
6518 QualType T, bool HadMultipleCandidates,
6519 UnresolvedSetImpl &ExplicitConversions) {
6520 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6521 DeclAccessPair Found = ExplicitConversions[0];
6522 CXXConversionDecl *Conversion =
6523 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6524
6525 // The user probably meant to invoke the given explicit
6526 // conversion; use it.
6527 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6528 std::string TypeStr;
6529 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6530
6531 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6533 "static_cast<" + TypeStr + ">(")
6535 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6536 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6537
6538 // If we aren't in a SFINAE context, build a call to the
6539 // explicit conversion function.
6540 if (SemaRef.isSFINAEContext())
6541 return true;
6542
6543 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6544 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6545 HadMultipleCandidates);
6546 if (Result.isInvalid())
6547 return true;
6548 // Record usage of conversion in an implicit cast.
6549 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6550 CK_UserDefinedConversion, Result.get(),
6551 nullptr, Result.get()->getValueKind(),
6552 SemaRef.CurFPFeatureOverrides());
6553 }
6554 return false;
6555}
6556
6557static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6559 QualType T, bool HadMultipleCandidates,
6560 DeclAccessPair &Found) {
6561 CXXConversionDecl *Conversion =
6562 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6563 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6564
6565 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6566 if (!Converter.SuppressConversion) {
6567 if (SemaRef.isSFINAEContext())
6568 return true;
6569
6570 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6571 << From->getSourceRange();
6572 }
6573
6574 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6575 HadMultipleCandidates);
6576 if (Result.isInvalid())
6577 return true;
6578 // Record usage of conversion in an implicit cast.
6579 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6580 CK_UserDefinedConversion, Result.get(),
6581 nullptr, Result.get()->getValueKind(),
6582 SemaRef.CurFPFeatureOverrides());
6583 return false;
6584}
6585
6587 Sema &SemaRef, SourceLocation Loc, Expr *From,
6589 if (!Converter.match(From->getType()) && !Converter.Suppress)
6590 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6591 << From->getSourceRange();
6592
6593 return SemaRef.DefaultLvalueConversion(From);
6594}
6595
6596static void
6598 UnresolvedSetImpl &ViableConversions,
6599 OverloadCandidateSet &CandidateSet) {
6600 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6601 DeclAccessPair FoundDecl = ViableConversions[I];
6602 NamedDecl *D = FoundDecl.getDecl();
6603 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6604 if (isa<UsingShadowDecl>(D))
6605 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6606
6607 CXXConversionDecl *Conv;
6608 FunctionTemplateDecl *ConvTemplate;
6609 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6610 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6611 else
6612 Conv = cast<CXXConversionDecl>(D);
6613
6614 if (ConvTemplate)
6616 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6617 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6618 else
6619 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6620 ToType, CandidateSet,
6621 /*AllowObjCConversionOnExplicit=*/false,
6622 /*AllowExplicit*/ true);
6623 }
6624}
6625
6626/// Attempt to convert the given expression to a type which is accepted
6627/// by the given converter.
6628///
6629/// This routine will attempt to convert an expression of class type to a
6630/// type accepted by the specified converter. In C++11 and before, the class
6631/// must have a single non-explicit conversion function converting to a matching
6632/// type. In C++1y, there can be multiple such conversion functions, but only
6633/// one target type.
6634///
6635/// \param Loc The source location of the construct that requires the
6636/// conversion.
6637///
6638/// \param From The expression we're converting from.
6639///
6640/// \param Converter Used to control and diagnose the conversion process.
6641///
6642/// \returns The expression, converted to an integral or enumeration type if
6643/// successful.
6645 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6646 // We can't perform any more checking for type-dependent expressions.
6647 if (From->isTypeDependent())
6648 return From;
6649
6650 // Process placeholders immediately.
6651 if (From->hasPlaceholderType()) {
6652 ExprResult result = CheckPlaceholderExpr(From);
6653 if (result.isInvalid())
6654 return result;
6655 From = result.get();
6656 }
6657
6658 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6659 ExprResult Converted = DefaultLvalueConversion(From);
6660 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6661 // If the expression already has a matching type, we're golden.
6662 if (Converter.match(T))
6663 return Converted;
6664
6665 // FIXME: Check for missing '()' if T is a function type?
6666
6667 // We can only perform contextual implicit conversions on objects of class
6668 // type.
6669 const RecordType *RecordTy = T->getAs<RecordType>();
6670 if (!RecordTy || !getLangOpts().CPlusPlus) {
6671 if (!Converter.Suppress)
6672 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6673 return From;
6674 }
6675
6676 // We must have a complete class type.
6677 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6678 ContextualImplicitConverter &Converter;
6679 Expr *From;
6680
6681 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6682 : Converter(Converter), From(From) {}
6683
6684 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6685 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6686 }
6687 } IncompleteDiagnoser(Converter, From);
6688
6689 if (Converter.Suppress ? !isCompleteType(Loc, T)
6690 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6691 return From;
6692
6693 // Look for a conversion to an integral or enumeration type.
6695 ViableConversions; // These are *potentially* viable in C++1y.
6696 UnresolvedSet<4> ExplicitConversions;
6697 const auto &Conversions =
6698 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6699
6700 bool HadMultipleCandidates =
6701 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6702
6703 // To check that there is only one target type, in C++1y:
6704 QualType ToType;
6705 bool HasUniqueTargetType = true;
6706
6707 // Collect explicit or viable (potentially in C++1y) conversions.
6708 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6709 NamedDecl *D = (*I)->getUnderlyingDecl();
6710 CXXConversionDecl *Conversion;
6711 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6712 if (ConvTemplate) {
6713 if (getLangOpts().CPlusPlus14)
6714 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6715 else
6716 continue; // C++11 does not consider conversion operator templates(?).
6717 } else
6718 Conversion = cast<CXXConversionDecl>(D);
6719
6720 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6721 "Conversion operator templates are considered potentially "
6722 "viable in C++1y");
6723
6724 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6725 if (Converter.match(CurToType) || ConvTemplate) {
6726
6727 if (Conversion->isExplicit()) {
6728 // FIXME: For C++1y, do we need this restriction?
6729 // cf. diagnoseNoViableConversion()
6730 if (!ConvTemplate)
6731 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6732 } else {
6733 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6734 if (ToType.isNull())
6735 ToType = CurToType.getUnqualifiedType();
6736 else if (HasUniqueTargetType &&
6737 (CurToType.getUnqualifiedType() != ToType))
6738 HasUniqueTargetType = false;
6739 }
6740 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6741 }
6742 }
6743 }
6744
6745 if (getLangOpts().CPlusPlus14) {
6746 // C++1y [conv]p6:
6747 // ... An expression e of class type E appearing in such a context
6748 // is said to be contextually implicitly converted to a specified
6749 // type T and is well-formed if and only if e can be implicitly
6750 // converted to a type T that is determined as follows: E is searched
6751 // for conversion functions whose return type is cv T or reference to
6752 // cv T such that T is allowed by the context. There shall be
6753 // exactly one such T.
6754
6755 // If no unique T is found:
6756 if (ToType.isNull()) {
6757 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6758 HadMultipleCandidates,
6759 ExplicitConversions))
6760 return ExprError();
6761 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6762 }
6763
6764 // If more than one unique Ts are found:
6765 if (!HasUniqueTargetType)
6766 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6767 ViableConversions);
6768
6769 // If one unique T is found:
6770 // First, build a candidate set from the previously recorded
6771 // potentially viable conversions.
6773 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6774 CandidateSet);
6775
6776 // Then, perform overload resolution over the candidate set.
6778 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6779 case OR_Success: {
6780 // Apply this conversion.
6781 DeclAccessPair Found =
6782 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6783 if (recordConversion(*this, Loc, From, Converter, T,
6784 HadMultipleCandidates, Found))
6785 return ExprError();
6786 break;
6787 }
6788 case OR_Ambiguous:
6789 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6790 ViableConversions);
6792 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6793 HadMultipleCandidates,
6794 ExplicitConversions))
6795 return ExprError();
6796 [[fallthrough]];
6797 case OR_Deleted:
6798 // We'll complain below about a non-integral condition type.
6799 break;
6800 }
6801 } else {
6802 switch (ViableConversions.size()) {
6803 case 0: {
6804 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6805 HadMultipleCandidates,
6806 ExplicitConversions))
6807 return ExprError();
6808
6809 // We'll complain below about a non-integral condition type.
6810 break;
6811 }
6812 case 1: {
6813 // Apply this conversion.
6814 DeclAccessPair Found = ViableConversions[0];
6815 if (recordConversion(*this, Loc, From, Converter, T,
6816 HadMultipleCandidates, Found))
6817 return ExprError();
6818 break;
6819 }
6820 default:
6821 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6822 ViableConversions);
6823 }
6824 }
6825
6826 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6827}
6828
6829/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6830/// an acceptable non-member overloaded operator for a call whose
6831/// arguments have types T1 (and, if non-empty, T2). This routine
6832/// implements the check in C++ [over.match.oper]p3b2 concerning
6833/// enumeration types.
6835 FunctionDecl *Fn,
6836 ArrayRef<Expr *> Args) {
6837 QualType T1 = Args[0]->getType();
6838 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6839
6840 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6841 return true;
6842
6843 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6844 return true;
6845
6846 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6847 if (Proto->getNumParams() < 1)
6848 return false;
6849
6850 if (T1->isEnumeralType()) {
6851 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6852 if (Context.hasSameUnqualifiedType(T1, ArgType))
6853 return true;
6854 }
6855
6856 if (Proto->getNumParams() < 2)
6857 return false;
6858
6859 if (!T2.isNull() && T2->isEnumeralType()) {
6860 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6861 if (Context.hasSameUnqualifiedType(T2, ArgType))
6862 return true;
6863 }
6864
6865 return false;
6866}
6867
6868/// AddOverloadCandidate - Adds the given function to the set of
6869/// candidate functions, using the given function call arguments. If
6870/// @p SuppressUserConversions, then don't allow user-defined
6871/// conversions via constructors or conversion operators.
6872///
6873/// \param PartialOverloading true if we are performing "partial" overloading
6874/// based on an incomplete set of function arguments. This feature is used by
6875/// code completion.
6878 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6879 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6880 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6881 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6882 const FunctionProtoType *Proto
6883 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6884 assert(Proto && "Functions without a prototype cannot be overloaded");
6885 assert(!Function->getDescribedFunctionTemplate() &&
6886 "Use AddTemplateOverloadCandidate for function templates");
6887
6888 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6889 if (!isa<CXXConstructorDecl>(Method)) {
6890 // If we get here, it's because we're calling a member function
6891 // that is named without a member access expression (e.g.,
6892 // "this->f") that was either written explicitly or created
6893 // implicitly. This can happen with a qualified call to a member
6894 // function, e.g., X::f(). We use an empty type for the implied
6895 // object argument (C++ [over.call.func]p3), and the acting context
6896 // is irrelevant.
6897 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6899 CandidateSet, SuppressUserConversions,
6900 PartialOverloading, EarlyConversions, PO);
6901 return;
6902 }
6903 // We treat a constructor like a non-member function, since its object
6904 // argument doesn't participate in overload resolution.
6905 }
6906
6907 if (!CandidateSet.isNewCandidate(Function, PO))
6908 return;
6909
6910 // C++11 [class.copy]p11: [DR1402]
6911 // A defaulted move constructor that is defined as deleted is ignored by
6912 // overload resolution.
6913 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6914 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6915 Constructor->isMoveConstructor())
6916 return;
6917
6918 // Overload resolution is always an unevaluated context.
6921
6922 // C++ [over.match.oper]p3:
6923 // if no operand has a class type, only those non-member functions in the
6924 // lookup set that have a first parameter of type T1 or "reference to
6925 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6926 // is a right operand) a second parameter of type T2 or "reference to
6927 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6928 // candidate functions.
6929 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6931 return;
6932
6933 // Add this candidate
6934 OverloadCandidate &Candidate =
6935 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6936 Candidate.FoundDecl = FoundDecl;
6937 Candidate.Function = Function;
6938 Candidate.Viable = true;
6939 Candidate.RewriteKind =
6940 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6941 Candidate.IsSurrogate = false;
6942 Candidate.IsADLCandidate = IsADLCandidate;
6943 Candidate.IgnoreObjectArgument = false;
6944 Candidate.ExplicitCallArguments = Args.size();
6945
6946 // Explicit functions are not actually candidates at all if we're not
6947 // allowing them in this context, but keep them around so we can point
6948 // to them in diagnostics.
6949 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6950 Candidate.Viable = false;
6951 Candidate.FailureKind = ovl_fail_explicit;
6952 return;
6953 }
6954
6955 // Functions with internal linkage are only viable in the same module unit.
6956 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6957 /// FIXME: Currently, the semantics of linkage in clang is slightly
6958 /// different from the semantics in C++ spec. In C++ spec, only names
6959 /// have linkage. So that all entities of the same should share one
6960 /// linkage. But in clang, different entities of the same could have
6961 /// different linkage.
6962 NamedDecl *ND = Function;
6963 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6964 ND = SpecInfo->getTemplate();
6965
6966 if (ND->getFormalLinkage() == Linkage::Internal) {
6967 Candidate.Viable = false;
6969 return;
6970 }
6971 }
6972
6973 if (Function->isMultiVersion() &&
6974 ((Function->hasAttr<TargetAttr>() &&
6975 !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
6976 (Function->hasAttr<TargetVersionAttr>() &&
6977 !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
6978 Candidate.Viable = false;
6980 return;
6981 }
6982
6983 if (Constructor) {
6984 // C++ [class.copy]p3:
6985 // A member function template is never instantiated to perform the copy
6986 // of a class object to an object of its class type.
6987 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6988 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6989 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6990 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6991 ClassType))) {
6992 Candidate.Viable = false;
6994 return;
6995 }
6996
6997 // C++ [over.match.funcs]p8: (proposed DR resolution)
6998 // A constructor inherited from class type C that has a first parameter
6999 // of type "reference to P" (including such a constructor instantiated
7000 // from a template) is excluded from the set of candidate functions when
7001 // constructing an object of type cv D if the argument list has exactly
7002 // one argument and D is reference-related to P and P is reference-related
7003 // to C.
7004 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7005 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7006 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7007 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7008 QualType C = Context.getRecordType(Constructor->getParent());
7009 QualType D = Context.getRecordType(Shadow->getParent());
7010 SourceLocation Loc = Args.front()->getExprLoc();
7011 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7012 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7013 Candidate.Viable = false;
7015 return;
7016 }
7017 }
7018
7019 // Check that the constructor is capable of constructing an object in the
7020 // destination address space.
7022 Constructor->getMethodQualifiers().getAddressSpace(),
7023 CandidateSet.getDestAS())) {
7024 Candidate.Viable = false;
7026 }
7027 }
7028
7029 unsigned NumParams = Proto->getNumParams();
7030
7031 // (C++ 13.3.2p2): A candidate function having fewer than m
7032 // parameters is viable only if it has an ellipsis in its parameter
7033 // list (8.3.5).
7034 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7035 !Proto->isVariadic() &&
7036 shouldEnforceArgLimit(PartialOverloading, Function)) {
7037 Candidate.Viable = false;
7039 return;
7040 }
7041
7042 // (C++ 13.3.2p2): A candidate function having more than m parameters
7043 // is viable only if the (m+1)st parameter has a default argument
7044 // (8.3.6). For the purposes of overload resolution, the
7045 // parameter list is truncated on the right, so that there are
7046 // exactly m parameters.
7047 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7048 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7049 !PartialOverloading) {
7050 // Not enough arguments.
7051 Candidate.Viable = false;
7053 return;
7054 }
7055
7056 // (CUDA B.1): Check for invalid calls between targets.
7057 if (getLangOpts().CUDA) {
7058 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7059 // Skip the check for callers that are implicit members, because in this
7060 // case we may not yet know what the member's target is; the target is
7061 // inferred for the member automatically, based on the bases and fields of
7062 // the class.
7063 if (!(Caller && Caller->isImplicit()) &&
7064 !IsAllowedCUDACall(Caller, Function)) {
7065 Candidate.Viable = false;
7066 Candidate.FailureKind = ovl_fail_bad_target;
7067 return;
7068 }
7069 }
7070
7071 if (Function->getTrailingRequiresClause()) {
7072 ConstraintSatisfaction Satisfaction;
7073 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7074 /*ForOverloadResolution*/ true) ||
7075 !Satisfaction.IsSatisfied) {
7076 Candidate.Viable = false;
7078 return;
7079 }
7080 }
7081
7082 // Determine the implicit conversion sequences for each of the
7083 // arguments.
7084 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7085 unsigned ConvIdx =
7086 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7087 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7088 // We already formed a conversion sequence for this parameter during
7089 // template argument deduction.
7090 } else if (ArgIdx < NumParams) {
7091 // (C++ 13.3.2p3): for F to be a viable function, there shall
7092 // exist for each argument an implicit conversion sequence
7093 // (13.3.3.1) that converts that argument to the corresponding
7094 // parameter of F.
7095 QualType ParamType = Proto->getParamType(ArgIdx);
7096 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7097 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7098 /*InOverloadResolution=*/true,
7099 /*AllowObjCWritebackConversion=*/
7100 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7101 if (Candidate.Conversions[ConvIdx].isBad()) {
7102 Candidate.Viable = false;
7104 return;
7105 }
7106 } else {
7107 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7108 // argument for which there is no corresponding parameter is
7109 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7110 Candidate.Conversions[ConvIdx].setEllipsis();
7111 }
7112 }
7113
7114 if (EnableIfAttr *FailedAttr =
7115 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7116 Candidate.Viable = false;
7117 Candidate.FailureKind = ovl_fail_enable_if;
7118 Candidate.DeductionFailure.Data = FailedAttr;
7119 return;
7120 }
7121}
7122
7124Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7126 if (Methods.size() <= 1)
7127 return nullptr;
7128
7129 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7130 bool Match = true;
7131 ObjCMethodDecl *Method = Methods[b];
7132 unsigned NumNamedArgs = Sel.getNumArgs();
7133 // Method might have more arguments than selector indicates. This is due
7134 // to addition of c-style arguments in method.
7135 if (Method->param_size() > NumNamedArgs)
7136 NumNamedArgs = Method->param_size();
7137 if (Args.size() < NumNamedArgs)
7138 continue;
7139
7140 for (unsigned i = 0; i < NumNamedArgs; i++) {
7141 // We can't do any type-checking on a type-dependent argument.
7142 if (Args[i]->isTypeDependent()) {
7143 Match = false;
7144 break;
7145 }
7146
7147 ParmVarDecl *param = Method->parameters()[i];
7148 Expr *argExpr = Args[i];
7149 assert(argExpr && "SelectBestMethod(): missing expression");
7150
7151 // Strip the unbridged-cast placeholder expression off unless it's
7152 // a consumed argument.
7153 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7154 !param->hasAttr<CFConsumedAttr>())
7155 argExpr = stripARCUnbridgedCast(argExpr);
7156
7157 // If the parameter is __unknown_anytype, move on to the next method.
7158 if (param->getType() == Context.UnknownAnyTy) {
7159 Match = false;
7160 break;
7161 }
7162
7163 ImplicitConversionSequence ConversionState
7164 = TryCopyInitialization(*this, argExpr, param->getType(),
7165 /*SuppressUserConversions*/false,
7166 /*InOverloadResolution=*/true,
7167 /*AllowObjCWritebackConversion=*/
7168 getLangOpts().ObjCAutoRefCount,
7169 /*AllowExplicit*/false);
7170 // This function looks for a reasonably-exact match, so we consider
7171 // incompatible pointer conversions to be a failure here.
7172 if (ConversionState.isBad() ||
7173 (ConversionState.isStandard() &&
7174 ConversionState.Standard.Second ==
7176 Match = false;
7177 break;
7178 }
7179 }
7180 // Promote additional arguments to variadic methods.
7181 if (Match && Method->isVariadic()) {
7182 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7183 if (Args[i]->isTypeDependent()) {
7184 Match = false;
7185 break;
7186 }
7187 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7188 nullptr);
7189 if (Arg.isInvalid()) {
7190 Match = false;
7191 break;
7192 }
7193 }
7194 } else {
7195 // Check for extra arguments to non-variadic methods.
7196 if (Args.size() != NumNamedArgs)
7197 Match = false;
7198 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7199 // Special case when selectors have no argument. In this case, select
7200 // one with the most general result type of 'id'.
7201 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7202 QualType ReturnT = Methods[b]->getReturnType();
7203 if (ReturnT->isObjCIdType())
7204 return Methods[b];
7205 }
7206 }
7207 }
7208
7209 if (Match)
7210 return Method;
7211 }
7212 return nullptr;
7213}
7214
7216 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7217 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7218 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7219 if (ThisArg) {
7220 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7221 assert(!isa<CXXConstructorDecl>(Method) &&
7222 "Shouldn't have `this` for ctors!");
7223 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7225 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7226 if (R.isInvalid())
7227 return false;
7228 ConvertedThis = R.get();
7229 } else {
7230 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7231 (void)MD;
7232 assert((MissingImplicitThis || MD->isStatic() ||
7233 isa<CXXConstructorDecl>(MD)) &&
7234 "Expected `this` for non-ctor instance methods");
7235 }
7236 ConvertedThis = nullptr;
7237 }
7238
7239 // Ignore any variadic arguments. Converting them is pointless, since the
7240 // user can't refer to them in the function condition.
7241 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7242
7243 // Convert the arguments.
7244 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7245 ExprResult R;
7247 S.Context, Function->getParamDecl(I)),
7248 SourceLocation(), Args[I]);
7249
7250 if (R.isInvalid())
7251 return false;
7252
7253 ConvertedArgs.push_back(R.get());
7254 }
7255
7256 if (Trap.hasErrorOccurred())
7257 return false;
7258
7259 // Push default arguments if needed.
7260 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7261 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7262 ParmVarDecl *P = Function->getParamDecl(i);
7263 if (!P->hasDefaultArg())
7264 return false;
7266 if (R.isInvalid())
7267 return false;
7268 ConvertedArgs.push_back(R.get());
7269 }
7270
7271 if (Trap.hasErrorOccurred())
7272 return false;
7273 }
7274 return true;
7275}
7276
7278 SourceLocation CallLoc,
7279 ArrayRef<Expr *> Args,
7280 bool MissingImplicitThis) {
7281 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7282 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7283 return nullptr;
7284
7285 SFINAETrap Trap(*this);
7286 SmallVector<Expr *, 16> ConvertedArgs;
7287 // FIXME: We should look into making enable_if late-parsed.
7288 Expr *DiscardedThis;
7290 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7291 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7292 return *EnableIfAttrs.begin();
7293
7294 for (auto *EIA : EnableIfAttrs) {
7296 // FIXME: This doesn't consider value-dependent cases, because doing so is
7297 // very difficult. Ideally, we should handle them more gracefully.
7298 if (EIA->getCond()->isValueDependent() ||
7299 !EIA->getCond()->EvaluateWithSubstitution(
7300 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7301 return EIA;
7302
7303 if (!Result.isInt() || !Result.getInt().getBoolValue())
7304 return EIA;
7305 }
7306 return nullptr;
7307}
7308
7309template <typename CheckFn>
7311 bool ArgDependent, SourceLocation Loc,
7312 CheckFn &&IsSuccessful) {
7314 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7315 if (ArgDependent == DIA->getArgDependent())
7316 Attrs.push_back(DIA);
7317 }
7318
7319 // Common case: No diagnose_if attributes, so we can quit early.
7320 if (Attrs.empty())
7321 return false;
7322
7323 auto WarningBegin = std::stable_partition(
7324 Attrs.begin(), Attrs.end(),
7325 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7326
7327 // Note that diagnose_if attributes are late-parsed, so they appear in the
7328 // correct order (unlike enable_if attributes).
7329 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7330 IsSuccessful);
7331 if (ErrAttr != WarningBegin) {
7332 const DiagnoseIfAttr *DIA = *ErrAttr;
7333 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7334 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7335 << DIA->getParent() << DIA->getCond()->getSourceRange();
7336 return true;
7337 }
7338
7339 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7340 if (IsSuccessful(DIA)) {
7341 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7342 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7343 << DIA->getParent() << DIA->getCond()->getSourceRange();
7344 }
7345
7346 return false;
7347}
7348
7350 const Expr *ThisArg,
7352 SourceLocation Loc) {
7354 *this, Function, /*ArgDependent=*/true, Loc,
7355 [&](const DiagnoseIfAttr *DIA) {
7357 // It's sane to use the same Args for any redecl of this function, since
7358 // EvaluateWithSubstitution only cares about the position of each
7359 // argument in the arg list, not the ParmVarDecl* it maps to.
7360 if (!DIA->getCond()->EvaluateWithSubstitution(
7361 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7362 return false;
7363 return Result.isInt() && Result.getInt().getBoolValue();
7364 });
7365}
7366
7368 SourceLocation Loc) {
7370 *this, ND, /*ArgDependent=*/false, Loc,
7371 [&](const DiagnoseIfAttr *DIA) {
7372 bool Result;
7373 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7374 Result;
7375 });
7376}
7377
7378/// Add all of the function declarations in the given function set to
7379/// the overload candidate set.
7381 ArrayRef<Expr *> Args,
7382 OverloadCandidateSet &CandidateSet,
7383 TemplateArgumentListInfo *ExplicitTemplateArgs,
7384 bool SuppressUserConversions,
7385 bool PartialOverloading,
7386 bool FirstArgumentIsBase) {
7387 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7388 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7389 ArrayRef<Expr *> FunctionArgs = Args;
7390
7391 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7392 FunctionDecl *FD =
7393 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7394
7395 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7396 QualType ObjectType;
7397 Expr::Classification ObjectClassification;
7398 if (Args.size() > 0) {
7399 if (Expr *E = Args[0]) {
7400 // Use the explicit base to restrict the lookup:
7401 ObjectType = E->getType();
7402 // Pointers in the object arguments are implicitly dereferenced, so we
7403 // always classify them as l-values.
7404 if (!ObjectType.isNull() && ObjectType->isPointerType())
7405 ObjectClassification = Expr::Classification::makeSimpleLValue();
7406 else
7407 ObjectClassification = E->Classify(Context);
7408 } // .. else there is an implicit base.
7409 FunctionArgs = Args.slice(1);
7410 }
7411 if (FunTmpl) {
7412 AddMethodTemplateCandidate(
7413 FunTmpl, F.getPair(),
7414 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7415 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7416 FunctionArgs, CandidateSet, SuppressUserConversions,
7417 PartialOverloading);
7418 } else {
7419 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7420 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7421 ObjectClassification, FunctionArgs, CandidateSet,
7422 SuppressUserConversions, PartialOverloading);
7423 }
7424 } else {
7425 // This branch handles both standalone functions and static methods.
7426
7427 // Slice the first argument (which is the base) when we access
7428 // static method as non-static.
7429 if (Args.size() > 0 &&
7430 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7431 !isa<CXXConstructorDecl>(FD)))) {
7432 assert(cast<CXXMethodDecl>(FD)->isStatic());
7433 FunctionArgs = Args.slice(1);
7434 }
7435 if (FunTmpl) {
7436 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7437 ExplicitTemplateArgs, FunctionArgs,
7438 CandidateSet, SuppressUserConversions,
7439 PartialOverloading);
7440 } else {
7441 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7442 SuppressUserConversions, PartialOverloading);
7443 }
7444 }
7445 }
7446}
7447
7448/// AddMethodCandidate - Adds a named decl (which is some kind of
7449/// method) as a method candidate to the given overload set.
7451 Expr::Classification ObjectClassification,
7452 ArrayRef<Expr *> Args,
7453 OverloadCandidateSet &CandidateSet,
7454 bool SuppressUserConversions,
7456 NamedDecl *Decl = FoundDecl.getDecl();
7457 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7458
7459 if (isa<UsingShadowDecl>(Decl))
7460 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7461
7462 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7463 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7464 "Expected a member function template");
7465 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7466 /*ExplicitArgs*/ nullptr, ObjectType,
7467 ObjectClassification, Args, CandidateSet,
7468 SuppressUserConversions, false, PO);
7469 } else {
7470 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7471 ObjectType, ObjectClassification, Args, CandidateSet,
7472 SuppressUserConversions, false, std::nullopt, PO);
7473 }
7474}
7475
7476/// AddMethodCandidate - Adds the given C++ member function to the set
7477/// of candidate functions, using the given function call arguments
7478/// and the object argument (@c Object). For example, in a call
7479/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7480/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7481/// allow user-defined conversions via constructors or conversion
7482/// operators.
7483void
7485 CXXRecordDecl *ActingContext, QualType ObjectType,
7486 Expr::Classification ObjectClassification,
7487 ArrayRef<Expr *> Args,
7488 OverloadCandidateSet &CandidateSet,
7489 bool SuppressUserConversions,
7490 bool PartialOverloading,
7491 ConversionSequenceList EarlyConversions,
7493 const FunctionProtoType *Proto
7494 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7495 assert(Proto && "Methods without a prototype cannot be overloaded");
7496 assert(!isa<CXXConstructorDecl>(Method) &&
7497 "Use AddOverloadCandidate for constructors");
7498
7499 if (!CandidateSet.isNewCandidate(Method, PO))
7500 return;
7501
7502 // C++11 [class.copy]p23: [DR1402]
7503 // A defaulted move assignment operator that is defined as deleted is
7504 // ignored by overload resolution.
7505 if (Method->isDefaulted() && Method->isDeleted() &&
7506 Method->isMoveAssignmentOperator())
7507 return;
7508
7509 // Overload resolution is always an unevaluated context.
7512
7513 // Add this candidate
7514 OverloadCandidate &Candidate =
7515 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7516 Candidate.FoundDecl = FoundDecl;
7517 Candidate.Function = Method;
7518 Candidate.RewriteKind =
7519 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7520 Candidate.IsSurrogate = false;
7521 Candidate.IgnoreObjectArgument = false;
7522 Candidate.ExplicitCallArguments = Args.size();
7523
7524 unsigned NumParams = Method->getNumExplicitParams();
7525 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7526
7527 // (C++ 13.3.2p2): A candidate function having fewer than m
7528 // parameters is viable only if it has an ellipsis in its parameter
7529 // list (8.3.5).
7530 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7531 !Proto->isVariadic() &&
7532 shouldEnforceArgLimit(PartialOverloading, Method)) {
7533 Candidate.Viable = false;
7535 return;
7536 }
7537
7538 // (C++ 13.3.2p2): A candidate function having more than m parameters
7539 // is viable only if the (m+1)st parameter has a default argument
7540 // (8.3.6). For the purposes of overload resolution, the
7541 // parameter list is truncated on the right, so that there are
7542 // exactly m parameters.
7543 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7544 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7545 // Not enough arguments.
7546 Candidate.Viable = false;
7548 return;
7549 }
7550
7551 Candidate.Viable = true;
7552
7553 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7554 if (ObjectType.isNull())
7555 Candidate.IgnoreObjectArgument = true;
7556 else if (Method->isStatic()) {
7557 // [over.best.ics.general]p8
7558 // When the parameter is the implicit object parameter of a static member
7559 // function, the implicit conversion sequence is a standard conversion
7560 // sequence that is neither better nor worse than any other standard
7561 // conversion sequence.
7562 //
7563 // This is a rule that was introduced in C++23 to support static lambdas. We
7564 // apply it retroactively because we want to support static lambdas as an
7565 // extension and it doesn't hurt previous code.
7566 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7567 } else {
7568 // Determine the implicit conversion sequence for the object
7569 // parameter.
7570 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7571 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7572 Method, ActingContext, /*InOverloadResolution=*/true);
7573 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7574 Candidate.Viable = false;
7576 return;
7577 }
7578 }
7579
7580 // (CUDA B.1): Check for invalid calls between targets.
7581 if (getLangOpts().CUDA)
7582 if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) {
7583 Candidate.Viable = false;
7584 Candidate.FailureKind = ovl_fail_bad_target;
7585 return;
7586 }
7587
7588 if (Method->getTrailingRequiresClause()) {
7589 ConstraintSatisfaction Satisfaction;
7590 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7591 /*ForOverloadResolution*/ true) ||
7592 !Satisfaction.IsSatisfied) {
7593 Candidate.Viable = false;
7595 return;
7596 }
7597 }
7598
7599 // Determine the implicit conversion sequences for each of the
7600 // arguments.
7601 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7602 unsigned ConvIdx =
7603 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7604 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7605 // We already formed a conversion sequence for this parameter during
7606 // template argument deduction.
7607 } else if (ArgIdx < NumParams) {
7608 // (C++ 13.3.2p3): for F to be a viable function, there shall
7609 // exist for each argument an implicit conversion sequence
7610 // (13.3.3.1) that converts that argument to the corresponding
7611 // parameter of F.
7612 QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7613 Candidate.Conversions[ConvIdx]
7614 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7615 SuppressUserConversions,
7616 /*InOverloadResolution=*/true,
7617 /*AllowObjCWritebackConversion=*/
7618 getLangOpts().ObjCAutoRefCount);
7619 if (Candidate.Conversions[ConvIdx].isBad()) {
7620 Candidate.Viable = false;
7622 return;
7623 }
7624 } else {
7625 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7626 // argument for which there is no corresponding parameter is
7627 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7628 Candidate.Conversions[ConvIdx].setEllipsis();
7629 }
7630 }
7631
7632 if (EnableIfAttr *FailedAttr =
7633 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7634 Candidate.Viable = false;
7635 Candidate.FailureKind = ovl_fail_enable_if;
7636 Candidate.DeductionFailure.Data = FailedAttr;
7637 return;
7638 }
7639
7640 if (Method->isMultiVersion() &&
7641 ((Method->hasAttr<TargetAttr>() &&
7642 !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
7643 (Method->hasAttr<TargetVersionAttr>() &&
7644 !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7645 Candidate.Viable = false;
7647 }
7648}
7649
7650/// Add a C++ member function template as a candidate to the candidate
7651/// set, using template argument deduction to produce an appropriate member
7652/// function template specialization.
7654 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7655 CXXRecordDecl *ActingContext,
7656 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7657 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7658 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7659 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7660 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7661 return;
7662
7663 // C++ [over.match.funcs]p7:
7664 // In each case where a candidate is a function template, candidate
7665 // function template specializations are generated using template argument
7666 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7667 // candidate functions in the usual way.113) A given name can refer to one
7668 // or more function templates and also to a set of overloaded non-template
7669 // functions. In such a case, the candidate functions generated from each
7670 // function template are combined with the set of non-template candidate
7671 // functions.
7672 TemplateDeductionInfo Info(CandidateSet.getLocation());
7673 FunctionDecl *Specialization = nullptr;
7674 ConversionSequenceList Conversions;
7676 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7677 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7678 ObjectClassification,
7679 [&](ArrayRef<QualType> ParamTypes) {
7680 return CheckNonDependentConversions(
7681 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7682 SuppressUserConversions, ActingContext, ObjectType,
7683 ObjectClassification, PO);
7684 });
7686 OverloadCandidate &Candidate =
7687 CandidateSet.addCandidate(Conversions.size(), Conversions);
7688 Candidate.FoundDecl = FoundDecl;
7689 Candidate.Function = MethodTmpl->getTemplatedDecl();
7690 Candidate.Viable = false;
7691 Candidate.RewriteKind =
7692 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7693 Candidate.IsSurrogate = false;
7694 Candidate.IgnoreObjectArgument =
7695 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7696 ObjectType.isNull();
7697 Candidate.ExplicitCallArguments = Args.size();
7700 else {
7703 Info);
7704 }
7705 return;
7706 }
7707
7708 // Add the function template specialization produced by template argument
7709 // deduction as a candidate.
7710 assert(Specialization && "Missing member function template specialization?");
7711 assert(isa<CXXMethodDecl>(Specialization) &&
7712 "Specialization is not a member function?");
7713 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7714 ActingContext, ObjectType, ObjectClassification, Args,
7715 CandidateSet, SuppressUserConversions, PartialOverloading,
7716 Conversions, PO);
7717}
7718
7719/// Determine whether a given function template has a simple explicit specifier
7720/// or a non-value-dependent explicit-specification that evaluates to true.
7723}
7724
7725/// Add a C++ function template specialization as a candidate
7726/// in the candidate set, using template argument deduction to produce
7727/// an appropriate function template specialization.
7729 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7730 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7731 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7732 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7733 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7734 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7735 return;
7736
7737 // If the function template has a non-dependent explicit specification,
7738 // exclude it now if appropriate; we are not permitted to perform deduction
7739 // and substitution in this case.
7740 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7741 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7742 Candidate.FoundDecl = FoundDecl;
7743 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7744 Candidate.Viable = false;
7745 Candidate.FailureKind = ovl_fail_explicit;
7746 return;
7747 }
7748
7749 // C++ [over.match.funcs]p7:
7750 // In each case where a candidate is a function template, candidate
7751 // function template specializations are generated using template argument
7752 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7753 // candidate functions in the usual way.113) A given name can refer to one
7754 // or more function templates and also to a set of overloaded non-template
7755 // functions. In such a case, the candidate functions generated from each
7756 // function template are combined with the set of non-template candidate
7757 // functions.
7758 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7759 FunctionTemplate->getTemplateDepth());
7760 FunctionDecl *Specialization = nullptr;
7761 ConversionSequenceList Conversions;
7763 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7764 PartialOverloading, AggregateCandidateDeduction,
7765 /*ObjectType=*/QualType(),
7766 /*ObjectClassification=*/Expr::Classification(),
7767 [&](ArrayRef<QualType> ParamTypes) {
7768 return CheckNonDependentConversions(
7769 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7770 SuppressUserConversions, nullptr, QualType(), {}, PO);
7771 });
7773 OverloadCandidate &Candidate =
7774 CandidateSet.addCandidate(Conversions.size(), Conversions);
7775 Candidate.FoundDecl = FoundDecl;
7776 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7777 Candidate.Viable = false;
7778 Candidate.RewriteKind =
7779 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7780 Candidate.IsSurrogate = false;
7781 Candidate.IsADLCandidate = IsADLCandidate;
7782 // Ignore the object argument if there is one, since we don't have an object
7783 // type.
7784 Candidate.IgnoreObjectArgument =
7785 isa<CXXMethodDecl>(Candidate.Function) &&
7786 !isa<CXXConstructorDecl>(Candidate.Function);
7787 Candidate.ExplicitCallArguments = Args.size();
7790 else {
7793 Info);
7794 }
7795 return;
7796 }
7797
7798 // Add the function template specialization produced by template argument
7799 // deduction as a candidate.
7800 assert(Specialization && "Missing function template specialization?");
7801 AddOverloadCandidate(
7802 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7803 PartialOverloading, AllowExplicit,
7804 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7806}
7807
7808/// Check that implicit conversion sequences can be formed for each argument
7809/// whose corresponding parameter has a non-dependent type, per DR1391's
7810/// [temp.deduct.call]p10.
7812 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7813 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7814 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7815 CXXRecordDecl *ActingContext, QualType ObjectType,
7816 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7817 // FIXME: The cases in which we allow explicit conversions for constructor
7818 // arguments never consider calling a constructor template. It's not clear
7819 // that is correct.
7820 const bool AllowExplicit = false;
7821
7822 auto *FD = FunctionTemplate->getTemplatedDecl();
7823 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7824 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7825 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7826
7827 Conversions =
7828 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7829
7830 // Overload resolution is always an unevaluated context.
7833
7834 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7835 // require that, but this check should never result in a hard error, and
7836 // overload resolution is permitted to sidestep instantiations.
7837 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7838 !ObjectType.isNull()) {
7839 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7840 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7841 !ParamTypes[0]->isDependentType()) {
7842 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7843 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7844 Method, ActingContext, /*InOverloadResolution=*/true,
7845 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7846 : QualType());
7847 if (Conversions[ConvIdx].isBad())
7848 return true;
7849 }
7850 }
7851
7852 unsigned Offset =
7853 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7854
7855 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7856 I != N; ++I) {
7857 QualType ParamType = ParamTypes[I + Offset];
7858 if (!ParamType->isDependentType()) {
7859 unsigned ConvIdx;
7861 ConvIdx = Args.size() - 1 - I;
7862 assert(Args.size() + ThisConversions == 2 &&
7863 "number of args (including 'this') must be exactly 2 for "
7864 "reversed order");
7865 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7866 // would also be 0. 'this' got ConvIdx = 1 previously.
7867 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7868 } else {
7869 // For members, 'this' got ConvIdx = 0 previously.
7870 ConvIdx = ThisConversions + I;
7871 }
7872 Conversions[ConvIdx]
7873 = TryCopyInitialization(*this, Args[I], ParamType,
7874 SuppressUserConversions,
7875 /*InOverloadResolution=*/true,
7876 /*AllowObjCWritebackConversion=*/
7877 getLangOpts().ObjCAutoRefCount,
7878 AllowExplicit);
7879 if (Conversions[ConvIdx].isBad())
7880 return true;
7881 }
7882 }
7883
7884 return false;
7885}
7886
7887/// Determine whether this is an allowable conversion from the result
7888/// of an explicit conversion operator to the expected type, per C++
7889/// [over.match.conv]p1 and [over.match.ref]p1.
7890///
7891/// \param ConvType The return type of the conversion function.
7892///
7893/// \param ToType The type we are converting to.
7894///
7895/// \param AllowObjCPointerConversion Allow a conversion from one
7896/// Objective-C pointer to another.
7897///
7898/// \returns true if the conversion is allowable, false otherwise.
7900 QualType ConvType, QualType ToType,
7901 bool AllowObjCPointerConversion) {
7902 QualType ToNonRefType = ToType.getNonReferenceType();
7903
7904 // Easy case: the types are the same.
7905 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7906 return true;
7907
7908 // Allow qualification conversions.
7909 bool ObjCLifetimeConversion;
7910 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7911 ObjCLifetimeConversion))
7912 return true;
7913
7914 // If we're not allowed to consider Objective-C pointer conversions,
7915 // we're done.
7916 if (!AllowObjCPointerConversion)
7917 return false;
7918
7919 // Is this an Objective-C pointer conversion?
7920 bool IncompatibleObjC = false;
7921 QualType ConvertedType;
7922 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7923 IncompatibleObjC);
7924}
7925
7926/// AddConversionCandidate - Add a C++ conversion function as a
7927/// candidate in the candidate set (C++ [over.match.conv],
7928/// C++ [over.match.copy]). From is the expression we're converting from,
7929/// and ToType is the type that we're eventually trying to convert to
7930/// (which may or may not be the same type as the type that the
7931/// conversion function produces).
7933 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7934 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7935 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7936 bool AllowExplicit, bool AllowResultConversion) {
7937 assert(!Conversion->getDescribedFunctionTemplate() &&
7938 "Conversion function templates use AddTemplateConversionCandidate");
7939 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7940 if (!CandidateSet.isNewCandidate(Conversion))
7941 return;
7942
7943 // If the conversion function has an undeduced return type, trigger its
7944 // deduction now.
7945 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7946 if (DeduceReturnType(Conversion, From->getExprLoc()))
7947 return;
7948 ConvType = Conversion->getConversionType().getNonReferenceType();
7949 }
7950
7951 // If we don't allow any conversion of the result type, ignore conversion
7952 // functions that don't convert to exactly (possibly cv-qualified) T.
7953 if (!AllowResultConversion &&
7954 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7955 return;
7956
7957 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7958 // operator is only a candidate if its return type is the target type or
7959 // can be converted to the target type with a qualification conversion.
7960 //
7961 // FIXME: Include such functions in the candidate list and explain why we
7962 // can't select them.
7963 if (Conversion->isExplicit() &&
7964 !isAllowableExplicitConversion(*this, ConvType, ToType,
7965 AllowObjCConversionOnExplicit))
7966 return;
7967
7968 // Overload resolution is always an unevaluated context.
7971
7972 // Add this candidate
7973 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7974 Candidate.FoundDecl = FoundDecl;
7975 Candidate.Function = Conversion;
7976 Candidate.IsSurrogate = false;
7977 Candidate.IgnoreObjectArgument = false;
7979 Candidate.FinalConversion.setFromType(ConvType);
7980 Candidate.FinalConversion.setAllToTypes(ToType);
7981 Candidate.Viable = true;
7982 Candidate.ExplicitCallArguments = 1;
7983
7984 // Explicit functions are not actually candidates at all if we're not
7985 // allowing them in this context, but keep them around so we can point
7986 // to them in diagnostics.
7987 if (!AllowExplicit && Conversion->isExplicit()) {
7988 Candidate.Viable = false;
7989 Candidate.FailureKind = ovl_fail_explicit;
7990 return;
7991 }
7992
7993 // C++ [over.match.funcs]p4:
7994 // For conversion functions, the function is considered to be a member of
7995 // the class of the implicit implied object argument for the purpose of
7996 // defining the type of the implicit object parameter.
7997 //
7998 // Determine the implicit conversion sequence for the implicit
7999 // object parameter.
8000 QualType ObjectType = From->getType();
8001 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8002 ObjectType = FromPtrType->getPointeeType();
8003 const auto *ConversionContext =
8004 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8005
8006 // C++23 [over.best.ics.general]
8007 // However, if the target is [...]
8008 // - the object parameter of a user-defined conversion function
8009 // [...] user-defined conversion sequences are not considered.
8011 *this, CandidateSet.getLocation(), From->getType(),
8012 From->Classify(Context), Conversion, ConversionContext,
8013 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8014 /*SuppressUserConversion*/ true);
8015
8016 if (Candidate.Conversions[0].isBad()) {
8017 Candidate.Viable = false;
8019 return;
8020 }
8021
8022 if (Conversion->getTrailingRequiresClause()) {
8023 ConstraintSatisfaction Satisfaction;
8024 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8025 !Satisfaction.IsSatisfied) {
8026 Candidate.Viable = false;
8028 return;
8029 }
8030 }
8031
8032 // We won't go through a user-defined type conversion function to convert a
8033 // derived to base as such conversions are given Conversion Rank. They only
8034 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8035 QualType FromCanon
8036 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8037 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8038 if (FromCanon == ToCanon ||
8039 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8040 Candidate.Viable = false;
8042 return;
8043 }
8044
8045 // To determine what the conversion from the result of calling the
8046 // conversion function to the type we're eventually trying to
8047 // convert to (ToType), we need to synthesize a call to the
8048 // conversion function and attempt copy initialization from it. This
8049 // makes sure that we get the right semantics with respect to
8050 // lvalues/rvalues and the type. Fortunately, we can allocate this
8051 // call on the stack and we don't need its arguments to be
8052 // well-formed.
8053 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8054 VK_LValue, From->getBeginLoc());
8056 Context.getPointerType(Conversion->getType()),
8057 CK_FunctionToPointerDecay, &ConversionRef,
8059
8060 QualType ConversionType = Conversion->getConversionType();
8061 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8062 Candidate.Viable = false;
8064 return;
8065 }
8066
8067 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8068
8069 // Note that it is safe to allocate CallExpr on the stack here because
8070 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8071 // allocator).
8072 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8073
8074 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8075 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8076 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8077
8079 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8080 /*SuppressUserConversions=*/true,
8081 /*InOverloadResolution=*/false,
8082 /*AllowObjCWritebackConversion=*/false);
8083
8084 switch (ICS.getKind()) {
8086 Candidate.FinalConversion = ICS.Standard;
8087
8088 // C++ [over.ics.user]p3:
8089 // If the user-defined conversion is specified by a specialization of a
8090 // conversion function template, the second standard conversion sequence
8091 // shall have exact match rank.
8092 if (Conversion->getPrimaryTemplate() &&
8094 Candidate.Viable = false;
8096 return;
8097 }
8098
8099 // C++0x [dcl.init.ref]p5:
8100 // In the second case, if the reference is an rvalue reference and
8101 // the second standard conversion sequence of the user-defined
8102 // conversion sequence includes an lvalue-to-rvalue conversion, the
8103 // program is ill-formed.
8104 if (ToType->isRValueReferenceType() &&
8106 Candidate.Viable = false;
8108 return;
8109 }
8110 break;
8111
8113 Candidate.Viable = false;
8115 return;
8116
8117 default:
8118 llvm_unreachable(
8119 "Can only end up with a standard conversion sequence or failure");
8120 }
8121
8122 if (EnableIfAttr *FailedAttr =
8123 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8124 Candidate.Viable = false;
8125 Candidate.FailureKind = ovl_fail_enable_if;
8126 Candidate.DeductionFailure.Data = FailedAttr;
8127 return;
8128 }
8129
8130 if (Conversion->isMultiVersion() &&
8131 ((Conversion->hasAttr<TargetAttr>() &&
8132 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
8133 (Conversion->hasAttr<TargetVersionAttr>() &&
8134 !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
8135 Candidate.Viable = false;
8137 }
8138}
8139
8140/// Adds a conversion function template specialization
8141/// candidate to the overload set, using template argument deduction
8142/// to deduce the template arguments of the conversion function
8143/// template from the type that we are converting to (C++
8144/// [temp.deduct.conv]).
8146 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8147 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8148 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8149 bool AllowExplicit, bool AllowResultConversion) {
8150 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8151 "Only conversion function templates permitted here");
8152
8153 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8154 return;
8155
8156 // If the function template has a non-dependent explicit specification,
8157 // exclude it now if appropriate; we are not permitted to perform deduction
8158 // and substitution in this case.
8159 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8160 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8161 Candidate.FoundDecl = FoundDecl;
8162 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8163 Candidate.Viable = false;
8164 Candidate.FailureKind = ovl_fail_explicit;
8165 return;
8166 }
8167
8168 QualType ObjectType = From->getType();
8169 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8170
8171 TemplateDeductionInfo Info(CandidateSet.getLocation());
8174 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8175 Specialization, Info);
8177 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8178 Candidate.FoundDecl = FoundDecl;
8179 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8180 Candidate.Viable = false;
8182 Candidate.IsSurrogate = false;
8183 Candidate.IgnoreObjectArgument = false;
8184 Candidate.ExplicitCallArguments = 1;
8186 Info);
8187 return;
8188 }
8189
8190 // Add the conversion function template specialization produced by
8191 // template argument deduction as a candidate.
8192 assert(Specialization && "Missing function template specialization?");
8193 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8194 CandidateSet, AllowObjCConversionOnExplicit,
8195 AllowExplicit, AllowResultConversion);
8196}
8197
8198/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8199/// converts the given @c Object to a function pointer via the
8200/// conversion function @c Conversion, and then attempts to call it
8201/// with the given arguments (C++ [over.call.object]p2-4). Proto is
8202/// the type of function that we'll eventually be calling.
8204 DeclAccessPair FoundDecl,
8205 CXXRecordDecl *ActingContext,
8206 const FunctionProtoType *Proto,
8207 Expr *Object,
8208 ArrayRef<Expr *> Args,
8209 OverloadCandidateSet& CandidateSet) {
8210 if (!CandidateSet.isNewCandidate(Conversion))
8211 return;
8212
8213 // Overload resolution is always an unevaluated context.
8216
8217 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8218 Candidate.FoundDecl = FoundDecl;
8219 Candidate.Function = nullptr;
8220 Candidate.Surrogate = Conversion;
8221 Candidate.Viable = true;
8222 Candidate.IsSurrogate = true;
8223 Candidate.IgnoreObjectArgument = false;
8224 Candidate.ExplicitCallArguments = Args.size();
8225
8226 // Determine the implicit conversion sequence for the implicit
8227 // object parameter.
8228 ImplicitConversionSequence ObjectInit;
8229 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8230 ObjectInit = TryCopyInitialization(*this, Object,
8231 Conversion->getParamDecl(0)->getType(),
8232 /*SuppressUserConversions=*/false,
8233 /*InOverloadResolution=*/true, false);
8234 } else {
8236 *this, CandidateSet.getLocation(), Object->getType(),
8237 Object->Classify(Context), Conversion, ActingContext);
8238 }
8239
8240 if (ObjectInit.isBad()) {
8241 Candidate.Viable = false;
8243 Candidate.Conversions[0] = ObjectInit;
8244 return;
8245 }
8246
8247 // The first conversion is actually a user-defined conversion whose
8248 // first conversion is ObjectInit's standard conversion (which is
8249 // effectively a reference binding). Record it as such.
8250 Candidate.Conversions[0].setUserDefined();
8251 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8252 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8253 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8254 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8255 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8256 Candidate.Conversions[0].UserDefined.After
8257 = Candidate.Conversions[0].UserDefined.Before;
8258 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8259
8260 // Find the
8261 unsigned NumParams = Proto->getNumParams();
8262
8263 // (C++ 13.3.2p2): A candidate function having fewer than m
8264 // parameters is viable only if it has an ellipsis in its parameter
8265 // list (8.3.5).
8266 if (Args.size() > NumParams && !Proto->isVariadic()) {
8267 Candidate.Viable = false;
8269 return;
8270 }
8271
8272 // Function types don't have any default arguments, so just check if
8273 // we have enough arguments.
8274 if (Args.size() < NumParams) {
8275 // Not enough arguments.
8276 Candidate.Viable = false;
8278 return;
8279 }
8280
8281 // Determine the implicit conversion sequences for each of the
8282 // arguments.
8283 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8284 if (ArgIdx < NumParams) {
8285 // (C++ 13.3.2p3): for F to be a viable function, there shall
8286 // exist for each argument an implicit conversion sequence
8287 // (13.3.3.1) that converts that argument to the corresponding
8288 // parameter of F.
8289 QualType ParamType = Proto->getParamType(ArgIdx);
8290 Candidate.Conversions[ArgIdx + 1]
8291 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8292 /*SuppressUserConversions=*/false,
8293 /*InOverloadResolution=*/false,
8294 /*AllowObjCWritebackConversion=*/
8295 getLangOpts().ObjCAutoRefCount);
8296 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8297 Candidate.Viable = false;
8299 return;
8300 }
8301 } else {
8302 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8303 // argument for which there is no corresponding parameter is
8304 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8305 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8306 }
8307 }
8308
8309 if (Conversion->getTrailingRequiresClause()) {
8310 ConstraintSatisfaction Satisfaction;
8311 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8312 /*ForOverloadResolution*/ true) ||
8313 !Satisfaction.IsSatisfied) {
8314 Candidate.Viable = false;
8316 return;
8317 }
8318 }
8319
8320 if (EnableIfAttr *FailedAttr =
8321 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8322 Candidate.Viable = false;
8323 Candidate.FailureKind = ovl_fail_enable_if;
8324 Candidate.DeductionFailure.Data = FailedAttr;
8325 return;
8326 }
8327}
8328
8329/// Add all of the non-member operator function declarations in the given
8330/// function set to the overload candidate set.
8332 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8333 OverloadCandidateSet &CandidateSet,
8334 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8335 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8336 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8337 ArrayRef<Expr *> FunctionArgs = Args;
8338
8339 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8340 FunctionDecl *FD =
8341 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8342
8343 // Don't consider rewritten functions if we're not rewriting.
8344 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8345 continue;
8346
8347 assert(!isa<CXXMethodDecl>(FD) &&
8348 "unqualified operator lookup found a member function");
8349
8350 if (FunTmpl) {
8351 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8352 FunctionArgs, CandidateSet);
8353 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8354 AddTemplateOverloadCandidate(
8355 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8356 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8357 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8358 } else {
8359 if (ExplicitTemplateArgs)
8360 continue;
8361 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8362 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8363 AddOverloadCandidate(
8364 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8365 false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8367 }
8368 }
8369}
8370
8371/// Add overload candidates for overloaded operators that are
8372/// member functions.
8373///
8374/// Add the overloaded operator candidates that are member functions
8375/// for the operator Op that was used in an operator expression such
8376/// as "x Op y". , Args/NumArgs provides the operator arguments, and
8377/// CandidateSet will store the added overload candidates. (C++
8378/// [over.match.oper]).
8380 SourceLocation OpLoc,
8381 ArrayRef<Expr *> Args,
8382 OverloadCandidateSet &CandidateSet,
8385
8386 // C++ [over.match.oper]p3:
8387 // For a unary operator @ with an operand of a type whose
8388 // cv-unqualified version is T1, and for a binary operator @ with
8389 // a left operand of a type whose cv-unqualified version is T1 and
8390 // a right operand of a type whose cv-unqualified version is T2,
8391 // three sets of candidate functions, designated member
8392 // candidates, non-member candidates and built-in candidates, are
8393 // constructed as follows:
8394 QualType T1 = Args[0]->getType();
8395
8396 // -- If T1 is a complete class type or a class currently being
8397 // defined, the set of member candidates is the result of the
8398 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8399 // the set of member candidates is empty.
8400 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8401 // Complete the type if it can be completed.
8402 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8403 return;
8404 // If the type is neither complete nor being defined, bail out now.
8405 if (!T1Rec->getDecl()->getDefinition())
8406 return;
8407
8408 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8409 LookupQualifiedName(Operators, T1Rec->getDecl());
8410 Operators.suppressAccessDiagnostics();
8411
8412 for (LookupResult::iterator Oper = Operators.begin(),
8413 OperEnd = Operators.end();
8414 Oper != OperEnd; ++Oper) {
8415 if (Oper->getAsFunction() &&
8417 !CandidateSet.getRewriteInfo().shouldAddReversed(
8418 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8419 continue;
8420 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8421 Args[0]->Classify(Context), Args.slice(1),
8422 CandidateSet, /*SuppressUserConversion=*/false, PO);
8423 }
8424 }
8425}
8426
8427/// AddBuiltinCandidate - Add a candidate for a built-in
8428/// operator. ResultTy and ParamTys are the result and parameter types
8429/// of the built-in candidate, respectively. Args and NumArgs are the
8430/// arguments being passed to the candidate. IsAssignmentOperator
8431/// should be true when this built-in candidate is an assignment
8432/// operator. NumContextualBoolArguments is the number of arguments
8433/// (at the beginning of the argument list) that will be contextually
8434/// converted to bool.
8436 OverloadCandidateSet& CandidateSet,
8437 bool IsAssignmentOperator,
8438 unsigned NumContextualBoolArguments) {
8439 // Overload resolution is always an unevaluated context.
8442
8443 // Add this candidate
8444 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8445 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8446 Candidate.Function = nullptr;
8447 Candidate.IsSurrogate = false;
8448 Candidate.IgnoreObjectArgument = false;
8449 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8450
8451 // Determine the implicit conversion sequences for each of the
8452 // arguments.
8453 Candidate.Viable = true;
8454 Candidate.ExplicitCallArguments = Args.size();
8455 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8456 // C++ [over.match.oper]p4:
8457 // For the built-in assignment operators, conversions of the
8458 // left operand are restricted as follows:
8459 // -- no temporaries are introduced to hold the left operand, and
8460 // -- no user-defined conversions are applied to the left
8461 // operand to achieve a type match with the left-most
8462 // parameter of a built-in candidate.
8463 //
8464 // We block these conversions by turning off user-defined
8465 // conversions, since that is the only way that initialization of
8466 // a reference to a non-class type can occur from something that
8467 // is not of the same type.
8468 if (ArgIdx < NumContextualBoolArguments) {
8469 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8470 "Contextual conversion to bool requires bool type");
8471 Candidate.Conversions[ArgIdx]
8472 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8473 } else {
8474 Candidate.Conversions[ArgIdx]
8475 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8476 ArgIdx == 0 && IsAssignmentOperator,
8477 /*InOverloadResolution=*/false,
8478 /*AllowObjCWritebackConversion=*/
8479 getLangOpts().ObjCAutoRefCount);
8480 }
8481 if (Candidate.Conversions[ArgIdx].isBad()) {
8482 Candidate.Viable = false;
8484 break;
8485 }
8486 }
8487}
8488
8489namespace {
8490
8491/// BuiltinCandidateTypeSet - A set of types that will be used for the
8492/// candidate operator functions for built-in operators (C++
8493/// [over.built]). The types are separated into pointer types and
8494/// enumeration types.
8495class BuiltinCandidateTypeSet {
8496 /// TypeSet - A set of types.
8497 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8498
8499 /// PointerTypes - The set of pointer types that will be used in the
8500 /// built-in candidates.
8501 TypeSet PointerTypes;
8502
8503 /// MemberPointerTypes - The set of member pointer types that will be
8504 /// used in the built-in candidates.
8505 TypeSet MemberPointerTypes;
8506
8507 /// EnumerationTypes - The set of enumeration types that will be
8508 /// used in the built-in candidates.
8509 TypeSet EnumerationTypes;
8510
8511 /// The set of vector types that will be used in the built-in
8512 /// candidates.
8513 TypeSet VectorTypes;
8514
8515 /// The set of matrix types that will be used in the built-in
8516 /// candidates.
8517 TypeSet MatrixTypes;
8518
8519 /// The set of _BitInt types that will be used in the built-in candidates.
8520 TypeSet BitIntTypes;
8521
8522 /// A flag indicating non-record types are viable candidates
8523 bool HasNonRecordTypes;
8524
8525 /// A flag indicating whether either arithmetic or enumeration types
8526 /// were present in the candidate set.
8527 bool HasArithmeticOrEnumeralTypes;
8528
8529 /// A flag indicating whether the nullptr type was present in the
8530 /// candidate set.
8531 bool HasNullPtrType;
8532
8533 /// Sema - The semantic analysis instance where we are building the
8534 /// candidate type set.
8535 Sema &SemaRef;
8536
8537 /// Context - The AST context in which we will build the type sets.
8538 ASTContext &Context;
8539
8540 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8541 const Qualifiers &VisibleQuals);
8542 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8543
8544public:
8545 /// iterator - Iterates through the types that are part of the set.
8546 typedef TypeSet::iterator iterator;
8547
8548 BuiltinCandidateTypeSet(Sema &SemaRef)
8549 : HasNonRecordTypes(false),
8550 HasArithmeticOrEnumeralTypes(false),
8551 HasNullPtrType(false),
8552 SemaRef(SemaRef),
8553 Context(SemaRef.Context) { }
8554
8555 void AddTypesConvertedFrom(QualType Ty,
8556 SourceLocation Loc,
8557 bool AllowUserConversions,
8558 bool AllowExplicitConversions,
8559 const Qualifiers &VisibleTypeConversionsQuals);
8560
8561 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8562 llvm::iterator_range<iterator> member_pointer_types() {
8563 return MemberPointerTypes;
8564 }
8565 llvm::iterator_range<iterator> enumeration_types() {
8566 return EnumerationTypes;
8567 }
8568 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8569 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8570 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8571
8572 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8573 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8574 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8575 bool hasNullPtrType() const { return HasNullPtrType; }
8576};
8577
8578} // end anonymous namespace
8579
8580/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8581/// the set of pointer types along with any more-qualified variants of
8582/// that type. For example, if @p Ty is "int const *", this routine
8583/// will add "int const *", "int const volatile *", "int const
8584/// restrict *", and "int const volatile restrict *" to the set of
8585/// pointer types. Returns true if the add of @p Ty itself succeeded,
8586/// false otherwise.
8587///
8588/// FIXME: what to do about extended qualifiers?
8589bool
8590BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8591 const Qualifiers &VisibleQuals) {
8592
8593 // Insert this type.
8594 if (!PointerTypes.insert(Ty))
8595 return false;
8596
8597 QualType PointeeTy;
8598 const PointerType *PointerTy = Ty->getAs<PointerType>();
8599 bool buildObjCPtr = false;
8600 if (!PointerTy) {
8602 PointeeTy = PTy->getPointeeType();
8603 buildObjCPtr = true;
8604 } else {
8605 PointeeTy = PointerTy->getPointeeType();
8606 }
8607
8608 // Don't add qualified variants of arrays. For one, they're not allowed
8609 // (the qualifier would sink to the element type), and for another, the
8610 // only overload situation where it matters is subscript or pointer +- int,
8611 // and those shouldn't have qualifier variants anyway.
8612 if (PointeeTy->isArrayType())
8613 return true;
8614
8615 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8616 bool hasVolatile = VisibleQuals.hasVolatile();
8617 bool hasRestrict = VisibleQuals.hasRestrict();
8618
8619 // Iterate through all strict supersets of BaseCVR.
8620 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8621 if ((CVR | BaseCVR) != CVR) continue;
8622 // Skip over volatile if no volatile found anywhere in the types.
8623 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8624
8625 // Skip over restrict if no restrict found anywhere in the types, or if
8626 // the type cannot be restrict-qualified.
8627 if ((CVR & Qualifiers::Restrict) &&
8628 (!hasRestrict ||
8629 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8630 continue;
8631
8632 // Build qualified pointee type.
8633 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8634
8635 // Build qualified pointer type.
8636 QualType QPointerTy;
8637 if (!buildObjCPtr)
8638 QPointerTy = Context.getPointerType(QPointeeTy);
8639 else
8640 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8641
8642 // Insert qualified pointer type.
8643 PointerTypes.insert(QPointerTy);
8644 }
8645
8646 return true;
8647}
8648
8649/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8650/// to the set of pointer types along with any more-qualified variants of
8651/// that type. For example, if @p Ty is "int const *", this routine
8652/// will add "int const *", "int const volatile *", "int const
8653/// restrict *", and "int const volatile restrict *" to the set of
8654/// pointer types. Returns true if the add of @p Ty itself succeeded,
8655/// false otherwise.
8656///
8657/// FIXME: what to do about extended qualifiers?
8658bool
8659BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8660 QualType Ty) {
8661 // Insert this type.
8662 if (!MemberPointerTypes.insert(Ty))
8663 return false;
8664
8665 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8666 assert(PointerTy && "type was not a member pointer type!");
8667
8668 QualType PointeeTy = PointerTy->getPointeeType();
8669 // Don't add qualified variants of arrays. For one, they're not allowed
8670 // (the qualifier would sink to the element type), and for another, the
8671 // only overload situation where it matters is subscript or pointer +- int,
8672 // and those shouldn't have qualifier variants anyway.
8673 if (PointeeTy->isArrayType())
8674 return true;
8675 const Type *ClassTy = PointerTy->getClass();
8676
8677 // Iterate through all strict supersets of the pointee type's CVR
8678 // qualifiers.
8679 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8680 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8681 if ((CVR | BaseCVR) != CVR) continue;
8682
8683 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8684 MemberPointerTypes.insert(
8685 Context.getMemberPointerType(QPointeeTy, ClassTy));
8686 }
8687
8688 return true;
8689}
8690
8691/// AddTypesConvertedFrom - Add each of the types to which the type @p
8692/// Ty can be implicit converted to the given set of @p Types. We're
8693/// primarily interested in pointer types and enumeration types. We also
8694/// take member pointer types, for the conditional operator.
8695/// AllowUserConversions is true if we should look at the conversion
8696/// functions of a class type, and AllowExplicitConversions if we
8697/// should also include the explicit conversion functions of a class
8698/// type.
8699void
8700BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8701 SourceLocation Loc,
8702 bool AllowUserConversions,
8703 bool AllowExplicitConversions,
8704 const Qualifiers &VisibleQuals) {
8705 // Only deal with canonical types.
8706 Ty = Context.getCanonicalType(Ty);
8707
8708 // Look through reference types; they aren't part of the type of an
8709 // expression for the purposes of conversions.
8710 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8711 Ty = RefTy->getPointeeType();
8712
8713 // If we're dealing with an array type, decay to the pointer.
8714 if (Ty->isArrayType())
8715 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8716
8717 // Otherwise, we don't care about qualifiers on the type.
8718 Ty = Ty.getLocalUnqualifiedType();
8719
8720 // Flag if we ever add a non-record type.
8721 const RecordType *TyRec = Ty->getAs<RecordType>();
8722 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8723
8724 // Flag if we encounter an arithmetic type.
8725 HasArithmeticOrEnumeralTypes =
8726 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8727
8728 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8729 PointerTypes.insert(Ty);
8730 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8731 // Insert our type, and its more-qualified variants, into the set
8732 // of types.
8733 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8734 return;
8735 } else if (Ty->isMemberPointerType()) {
8736 // Member pointers are far easier, since the pointee can't be converted.
8737 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8738 return;
8739 } else if (Ty->isEnumeralType()) {
8740 HasArithmeticOrEnumeralTypes = true;
8741 EnumerationTypes.insert(Ty);
8742 } else if (Ty->isBitIntType()) {
8743 HasArithmeticOrEnumeralTypes = true;
8744 BitIntTypes.insert(Ty);
8745 } else if (Ty->isVectorType()) {
8746 // We treat vector types as arithmetic types in many contexts as an
8747 // extension.
8748 HasArithmeticOrEnumeralTypes = true;
8749 VectorTypes.insert(Ty);
8750 } else if (Ty->isMatrixType()) {
8751 // Similar to vector types, we treat vector types as arithmetic types in
8752 // many contexts as an extension.
8753 HasArithmeticOrEnumeralTypes = true;
8754 MatrixTypes.insert(Ty);
8755 } else if (Ty->isNullPtrType()) {
8756 HasNullPtrType = true;
8757 } else if (AllowUserConversions && TyRec) {
8758 // No conversion functions in incomplete types.
8759 if (!SemaRef.isCompleteType(Loc, Ty))
8760 return;
8761
8762 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8763 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8764 if (isa<UsingShadowDecl>(D))
8765 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8766
8767 // Skip conversion function templates; they don't tell us anything
8768 // about which builtin types we can convert to.
8769 if (isa<FunctionTemplateDecl>(D))
8770 continue;
8771
8772 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8773 if (AllowExplicitConversions || !Conv->isExplicit()) {
8774 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8775 VisibleQuals);
8776 }
8777 }
8778 }
8779}
8780/// Helper function for adjusting address spaces for the pointer or reference
8781/// operands of builtin operators depending on the argument.
8783 Expr *Arg) {
8785}
8786
8787/// Helper function for AddBuiltinOperatorCandidates() that adds
8788/// the volatile- and non-volatile-qualified assignment operators for the
8789/// given type to the candidate set.
8791 QualType T,
8792 ArrayRef<Expr *> Args,
8793 OverloadCandidateSet &CandidateSet) {
8794 QualType ParamTypes[2];
8795
8796 // T& operator=(T&, T)
8797 ParamTypes[0] = S.Context.getLValueReferenceType(
8799 ParamTypes[1] = T;
8800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8801 /*IsAssignmentOperator=*/true);
8802
8804 // volatile T& operator=(volatile T&, T)
8805 ParamTypes[0] = S.Context.getLValueReferenceType(
8807 Args[0]));
8808 ParamTypes[1] = T;
8809 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8810 /*IsAssignmentOperator=*/true);
8811 }
8812}
8813
8814/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8815/// if any, found in visible type conversion functions found in ArgExpr's type.
8816static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8817 Qualifiers VRQuals;
8818 const RecordType *TyRec;
8819 if (const MemberPointerType *RHSMPType =
8820 ArgExpr->getType()->getAs<MemberPointerType>())
8821 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8822 else
8823 TyRec = ArgExpr->getType()->getAs<RecordType>();
8824 if (!TyRec) {
8825 // Just to be safe, assume the worst case.
8826 VRQuals.addVolatile();
8827 VRQuals.addRestrict();
8828 return VRQuals;
8829 }
8830
8831 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8832 if (!ClassDecl->hasDefinition())
8833 return VRQuals;
8834
8835 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8836 if (isa<UsingShadowDecl>(D))
8837 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8838 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8839 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8840 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8841 CanTy = ResTypeRef->getPointeeType();
8842 // Need to go down the pointer/mempointer chain and add qualifiers
8843 // as see them.
8844 bool done = false;
8845 while (!done) {
8846 if (CanTy.isRestrictQualified())
8847 VRQuals.addRestrict();
8848 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8849 CanTy = ResTypePtr->getPointeeType();
8850 else if (const MemberPointerType *ResTypeMPtr =
8851 CanTy->getAs<MemberPointerType>())
8852 CanTy = ResTypeMPtr->getPointeeType();
8853 else
8854 done = true;
8855 if (CanTy.isVolatileQualified())
8856 VRQuals.addVolatile();
8857 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8858 return VRQuals;
8859 }
8860 }
8861 }
8862 return VRQuals;
8863}
8864
8865// Note: We're currently only handling qualifiers that are meaningful for the
8866// LHS of compound assignment overloading.
8868 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8869 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8870 // _Atomic
8871 if (Available.hasAtomic()) {
8872 Available.removeAtomic();
8873 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8874 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8875 return;
8876 }
8877
8878 // volatile
8879 if (Available.hasVolatile()) {
8880 Available.removeVolatile();
8881 assert(!Applied.hasVolatile());
8882 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8883 Callback);
8884 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8885 return;
8886 }
8887
8888 Callback(Applied);
8889}
8890
8892 QualifiersAndAtomic Quals,
8893 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8895 Callback);
8896}
8897
8899 QualifiersAndAtomic Quals,
8900 Sema &S) {
8901 if (Quals.hasAtomic())
8903 if (Quals.hasVolatile())
8906}
8907
8908namespace {
8909
8910/// Helper class to manage the addition of builtin operator overload
8911/// candidates. It provides shared state and utility methods used throughout
8912/// the process, as well as a helper method to add each group of builtin
8913/// operator overloads from the standard to a candidate set.
8914class BuiltinOperatorOverloadBuilder {
8915 // Common instance state available to all overload candidate addition methods.
8916 Sema &S;
8917 ArrayRef<Expr *> Args;
8918 QualifiersAndAtomic VisibleTypeConversionsQuals;
8919 bool HasArithmeticOrEnumeralCandidateType;
8921 OverloadCandidateSet &CandidateSet;
8922
8923 static constexpr int ArithmeticTypesCap = 26;
8925
8926 // Define some indices used to iterate over the arithmetic types in
8927 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8928 // types are that preserved by promotion (C++ [over.built]p2).
8929 unsigned FirstIntegralType,
8930 LastIntegralType;
8931 unsigned FirstPromotedIntegralType,
8932 LastPromotedIntegralType;
8933 unsigned FirstPromotedArithmeticType,
8934 LastPromotedArithmeticType;
8935 unsigned NumArithmeticTypes;
8936
8937 void InitArithmeticTypes() {
8938 // Start of promoted types.
8939 FirstPromotedArithmeticType = 0;
8940 ArithmeticTypes.push_back(S.Context.FloatTy);
8941 ArithmeticTypes.push_back(S.Context.DoubleTy);
8942 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8944 ArithmeticTypes.push_back(S.Context.Float128Ty);
8946 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8947
8948 // Start of integral types.
8949 FirstIntegralType = ArithmeticTypes.size();
8950 FirstPromotedIntegralType = ArithmeticTypes.size();
8951 ArithmeticTypes.push_back(S.Context.IntTy);
8952 ArithmeticTypes.push_back(S.Context.LongTy);
8953 ArithmeticTypes.push_back(S.Context.LongLongTy);
8957 ArithmeticTypes.push_back(S.Context.Int128Ty);
8958 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8959 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8960 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8964 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8965
8966 /// We add candidates for the unique, unqualified _BitInt types present in
8967 /// the candidate type set. The candidate set already handled ensuring the
8968 /// type is unqualified and canonical, but because we're adding from N
8969 /// different sets, we need to do some extra work to unique things. Insert
8970 /// the candidates into a unique set, then move from that set into the list
8971 /// of arithmetic types.
8972 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8973 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8974 BuiltinCandidateTypeSet &Candidate) {
8975 for (QualType BitTy : Candidate.bitint_types())
8976 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8977 });
8978 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8979 LastPromotedIntegralType = ArithmeticTypes.size();
8980 LastPromotedArithmeticType = ArithmeticTypes.size();
8981 // End of promoted types.
8982
8983 ArithmeticTypes.push_back(S.Context.BoolTy);
8984 ArithmeticTypes.push_back(S.Context.CharTy);
8985 ArithmeticTypes.push_back(S.Context.WCharTy);
8986 if (S.Context.getLangOpts().Char8)
8987 ArithmeticTypes.push_back(S.Context.Char8Ty);
8988 ArithmeticTypes.push_back(S.Context.Char16Ty);
8989 ArithmeticTypes.push_back(S.Context.Char32Ty);
8990 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8991 ArithmeticTypes.push_back(S.Context.ShortTy);
8992 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8993 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8994 LastIntegralType = ArithmeticTypes.size();
8995 NumArithmeticTypes = ArithmeticTypes.size();
8996 // End of integral types.
8997 // FIXME: What about complex? What about half?
8998
8999 // We don't know for sure how many bit-precise candidates were involved, so
9000 // we subtract those from the total when testing whether we're under the
9001 // cap or not.
9002 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9003 ArithmeticTypesCap &&
9004 "Enough inline storage for all arithmetic types.");
9005 }
9006
9007 /// Helper method to factor out the common pattern of adding overloads
9008 /// for '++' and '--' builtin operators.
9009 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9010 bool HasVolatile,
9011 bool HasRestrict) {
9012 QualType ParamTypes[2] = {
9013 S.Context.getLValueReferenceType(CandidateTy),
9014 S.Context.IntTy
9015 };
9016
9017 // Non-volatile version.
9018 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9019
9020 // Use a heuristic to reduce number of builtin candidates in the set:
9021 // add volatile version only if there are conversions to a volatile type.
9022 if (HasVolatile) {
9023 ParamTypes[0] =
9025 S.Context.getVolatileType(CandidateTy));
9026 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9027 }
9028
9029 // Add restrict version only if there are conversions to a restrict type
9030 // and our candidate type is a non-restrict-qualified pointer.
9031 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9032 !CandidateTy.isRestrictQualified()) {
9033 ParamTypes[0]
9036 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9037
9038 if (HasVolatile) {
9039 ParamTypes[0]
9041 S.Context.getCVRQualifiedType(CandidateTy,
9044 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9045 }
9046 }
9047
9048 }
9049
9050 /// Helper to add an overload candidate for a binary builtin with types \p L
9051 /// and \p R.
9052 void AddCandidate(QualType L, QualType R) {
9053 QualType LandR[2] = {L, R};
9054 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9055 }
9056
9057public:
9058 BuiltinOperatorOverloadBuilder(
9059 Sema &S, ArrayRef<Expr *> Args,
9060 QualifiersAndAtomic VisibleTypeConversionsQuals,
9061 bool HasArithmeticOrEnumeralCandidateType,
9063 OverloadCandidateSet &CandidateSet)
9064 : S(S), Args(Args),
9065 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9066 HasArithmeticOrEnumeralCandidateType(
9067 HasArithmeticOrEnumeralCandidateType),
9068 CandidateTypes(CandidateTypes),
9069 CandidateSet(CandidateSet) {
9070
9071 InitArithmeticTypes();
9072 }
9073
9074 // Increment is deprecated for bool since C++17.
9075 //
9076 // C++ [over.built]p3:
9077 //
9078 // For every pair (T, VQ), where T is an arithmetic type other
9079 // than bool, and VQ is either volatile or empty, there exist
9080 // candidate operator functions of the form
9081 //
9082 // VQ T& operator++(VQ T&);
9083 // T operator++(VQ T&, int);
9084 //
9085 // C++ [over.built]p4:
9086 //
9087 // For every pair (T, VQ), where T is an arithmetic type other
9088 // than bool, and VQ is either volatile or empty, there exist
9089 // candidate operator functions of the form
9090 //
9091 // VQ T& operator--(VQ T&);
9092 // T operator--(VQ T&, int);
9093 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9094 if (!HasArithmeticOrEnumeralCandidateType)
9095 return;
9096
9097 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9098 const auto TypeOfT = ArithmeticTypes[Arith];
9099 if (TypeOfT == S.Context.BoolTy) {
9100 if (Op == OO_MinusMinus)
9101 continue;
9102 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9103 continue;
9104 }
9105 addPlusPlusMinusMinusStyleOverloads(
9106 TypeOfT,
9107 VisibleTypeConversionsQuals.hasVolatile(),
9108 VisibleTypeConversionsQuals.hasRestrict());
9109 }
9110 }
9111
9112 // C++ [over.built]p5:
9113 //
9114 // For every pair (T, VQ), where T is a cv-qualified or
9115 // cv-unqualified object type, and VQ is either volatile or
9116 // empty, there exist candidate operator functions of the form
9117 //
9118 // T*VQ& operator++(T*VQ&);
9119 // T*VQ& operator--(T*VQ&);
9120 // T* operator++(T*VQ&, int);
9121 // T* operator--(T*VQ&, int);
9122 void addPlusPlusMinusMinusPointerOverloads() {
9123 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9124 // Skip pointer types that aren't pointers to object types.
9125 if (!PtrTy->getPointeeType()->isObjectType())
9126 continue;
9127
9128 addPlusPlusMinusMinusStyleOverloads(
9129 PtrTy,
9130 (!PtrTy.isVolatileQualified() &&
9131 VisibleTypeConversionsQuals.hasVolatile()),
9132 (!PtrTy.isRestrictQualified() &&
9133 VisibleTypeConversionsQuals.hasRestrict()));
9134 }
9135 }
9136
9137 // C++ [over.built]p6:
9138 // For every cv-qualified or cv-unqualified object type T, there
9139 // exist candidate operator functions of the form
9140 //
9141 // T& operator*(T*);
9142 //
9143 // C++ [over.built]p7:
9144 // For every function type T that does not have cv-qualifiers or a
9145 // ref-qualifier, there exist candidate operator functions of the form
9146 // T& operator*(T*);
9147 void addUnaryStarPointerOverloads() {
9148 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9149 QualType PointeeTy = ParamTy->getPointeeType();
9150 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9151 continue;
9152
9153 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9154 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9155 continue;
9156
9157 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9158 }
9159 }
9160
9161 // C++ [over.built]p9:
9162 // For every promoted arithmetic type T, there exist candidate
9163 // operator functions of the form
9164 //
9165 // T operator+(T);
9166 // T operator-(T);
9167 void addUnaryPlusOrMinusArithmeticOverloads() {
9168 if (!HasArithmeticOrEnumeralCandidateType)
9169 return;
9170
9171 for (unsigned Arith = FirstPromotedArithmeticType;
9172 Arith < LastPromotedArithmeticType; ++Arith) {
9173 QualType ArithTy = ArithmeticTypes[Arith];
9174 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9175 }
9176
9177 // Extension: We also add these operators for vector types.
9178 for (QualType VecTy : CandidateTypes[0].vector_types())
9179 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9180 }
9181
9182 // C++ [over.built]p8:
9183 // For every type T, there exist candidate operator functions of
9184 // the form
9185 //
9186 // T* operator+(T*);
9187 void addUnaryPlusPointerOverloads() {
9188 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9189 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9190 }
9191
9192 // C++ [over.built]p10:
9193 // For every promoted integral type T, there exist candidate
9194 // operator functions of the form
9195 //
9196 // T operator~(T);
9197 void addUnaryTildePromotedIntegralOverloads() {
9198 if (!HasArithmeticOrEnumeralCandidateType)
9199 return;
9200
9201 for (unsigned Int = FirstPromotedIntegralType;
9202 Int < LastPromotedIntegralType; ++Int) {
9203 QualType IntTy = ArithmeticTypes[Int];
9204 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9205 }
9206
9207 // Extension: We also add this operator for vector types.
9208 for (QualType VecTy : CandidateTypes[0].vector_types())
9209 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9210 }
9211
9212 // C++ [over.match.oper]p16:
9213 // For every pointer to member type T or type std::nullptr_t, there
9214 // exist candidate operator functions of the form
9215 //
9216 // bool operator==(T,T);
9217 // bool operator!=(T,T);
9218 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9219 /// Set of (canonical) types that we've already handled.
9221
9222 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9223 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9224 // Don't add the same builtin candidate twice.
9225 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9226 continue;
9227
9228 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9229 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9230 }
9231
9232 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9234 if (AddedTypes.insert(NullPtrTy).second) {
9235 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9236 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9237 }
9238 }
9239 }
9240 }
9241
9242 // C++ [over.built]p15:
9243 //
9244 // For every T, where T is an enumeration type or a pointer type,
9245 // there exist candidate operator functions of the form
9246 //
9247 // bool operator<(T, T);
9248 // bool operator>(T, T);
9249 // bool operator<=(T, T);
9250 // bool operator>=(T, T);
9251 // bool operator==(T, T);
9252 // bool operator!=(T, T);
9253 // R operator<=>(T, T)
9254 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9255 // C++ [over.match.oper]p3:
9256 // [...]the built-in candidates include all of the candidate operator
9257 // functions defined in 13.6 that, compared to the given operator, [...]
9258 // do not have the same parameter-type-list as any non-template non-member
9259 // candidate.
9260 //
9261 // Note that in practice, this only affects enumeration types because there
9262 // aren't any built-in candidates of record type, and a user-defined operator
9263 // must have an operand of record or enumeration type. Also, the only other
9264 // overloaded operator with enumeration arguments, operator=,
9265 // cannot be overloaded for enumeration types, so this is the only place
9266 // where we must suppress candidates like this.
9268 UserDefinedBinaryOperators;
9269
9270 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9271 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9272 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9273 CEnd = CandidateSet.end();
9274 C != CEnd; ++C) {
9275 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9276 continue;
9277
9278 if (C->Function->isFunctionTemplateSpecialization())
9279 continue;
9280
9281 // We interpret "same parameter-type-list" as applying to the
9282 // "synthesized candidate, with the order of the two parameters
9283 // reversed", not to the original function.
9284 bool Reversed = C->isReversed();
9285 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9286 ->getType()
9287 .getUnqualifiedType();
9288 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9289 ->getType()
9290 .getUnqualifiedType();
9291
9292 // Skip if either parameter isn't of enumeral type.
9293 if (!FirstParamType->isEnumeralType() ||
9294 !SecondParamType->isEnumeralType())
9295 continue;
9296
9297 // Add this operator to the set of known user-defined operators.
9298 UserDefinedBinaryOperators.insert(
9299 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9300 S.Context.getCanonicalType(SecondParamType)));
9301 }
9302 }
9303 }
9304
9305 /// Set of (canonical) types that we've already handled.
9307
9308 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9309 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9310 // Don't add the same builtin candidate twice.
9311 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9312 continue;
9313 if (IsSpaceship && PtrTy->isFunctionPointerType())
9314 continue;
9315
9316 QualType ParamTypes[2] = {PtrTy, PtrTy};
9317 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9318 }
9319 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9320 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9321
9322 // Don't add the same builtin candidate twice, or if a user defined
9323 // candidate exists.
9324 if (!AddedTypes.insert(CanonType).second ||
9325 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9326 CanonType)))
9327 continue;
9328 QualType ParamTypes[2] = {EnumTy, EnumTy};
9329 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9330 }
9331 }
9332 }
9333
9334 // C++ [over.built]p13:
9335 //
9336 // For every cv-qualified or cv-unqualified object type T
9337 // there exist candidate operator functions of the form
9338 //
9339 // T* operator+(T*, ptrdiff_t);
9340 // T& operator[](T*, ptrdiff_t); [BELOW]
9341 // T* operator-(T*, ptrdiff_t);
9342 // T* operator+(ptrdiff_t, T*);
9343 // T& operator[](ptrdiff_t, T*); [BELOW]
9344 //
9345 // C++ [over.built]p14:
9346 //
9347 // For every T, where T is a pointer to object type, there
9348 // exist candidate operator functions of the form
9349 //
9350 // ptrdiff_t operator-(T, T);
9351 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9352 /// Set of (canonical) types that we've already handled.
9354
9355 for (int Arg = 0; Arg < 2; ++Arg) {
9356 QualType AsymmetricParamTypes[2] = {
9359 };
9360 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9361 QualType PointeeTy = PtrTy->getPointeeType();
9362 if (!PointeeTy->isObjectType())
9363 continue;
9364
9365 AsymmetricParamTypes[Arg] = PtrTy;
9366 if (Arg == 0 || Op == OO_Plus) {
9367 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9368 // T* operator+(ptrdiff_t, T*);
9369 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9370 }
9371 if (Op == OO_Minus) {
9372 // ptrdiff_t operator-(T, T);
9373 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9374 continue;
9375
9376 QualType ParamTypes[2] = {PtrTy, PtrTy};
9377 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9378 }
9379 }
9380 }
9381 }
9382
9383 // C++ [over.built]p12:
9384 //
9385 // For every pair of promoted arithmetic types L and R, there
9386 // exist candidate operator functions of the form
9387 //
9388 // LR operator*(L, R);
9389 // LR operator/(L, R);
9390 // LR operator+(L, R);
9391 // LR operator-(L, R);
9392 // bool operator<(L, R);
9393 // bool operator>(L, R);
9394 // bool operator<=(L, R);
9395 // bool operator>=(L, R);
9396 // bool operator==(L, R);
9397 // bool operator!=(L, R);
9398 //
9399 // where LR is the result of the usual arithmetic conversions
9400 // between types L and R.
9401 //
9402 // C++ [over.built]p24:
9403 //
9404 // For every pair of promoted arithmetic types L and R, there exist
9405 // candidate operator functions of the form
9406 //
9407 // LR operator?(bool, L, R);
9408 //
9409 // where LR is the result of the usual arithmetic conversions
9410 // between types L and R.
9411 // Our candidates ignore the first parameter.
9412 void addGenericBinaryArithmeticOverloads() {
9413 if (!HasArithmeticOrEnumeralCandidateType)
9414 return;
9415
9416 for (unsigned Left = FirstPromotedArithmeticType;
9417 Left < LastPromotedArithmeticType; ++Left) {
9418 for (unsigned Right = FirstPromotedArithmeticType;
9419 Right < LastPromotedArithmeticType; ++Right) {
9420 QualType LandR[2] = { ArithmeticTypes[Left],
9421 ArithmeticTypes[Right] };
9422 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9423 }
9424 }
9425
9426 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9427 // conditional operator for vector types.
9428 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9429 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9430 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9431 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9432 }
9433 }
9434
9435 /// Add binary operator overloads for each candidate matrix type M1, M2:
9436 /// * (M1, M1) -> M1
9437 /// * (M1, M1.getElementType()) -> M1
9438 /// * (M2.getElementType(), M2) -> M2
9439 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9440 void addMatrixBinaryArithmeticOverloads() {
9441 if (!HasArithmeticOrEnumeralCandidateType)
9442 return;
9443
9444 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9445 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9446 AddCandidate(M1, M1);
9447 }
9448
9449 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9450 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9451 if (!CandidateTypes[0].containsMatrixType(M2))
9452 AddCandidate(M2, M2);
9453 }
9454 }
9455
9456 // C++2a [over.built]p14:
9457 //
9458 // For every integral type T there exists a candidate operator function
9459 // of the form
9460 //
9461 // std::strong_ordering operator<=>(T, T)
9462 //
9463 // C++2a [over.built]p15:
9464 //
9465 // For every pair of floating-point types L and R, there exists a candidate
9466 // operator function of the form
9467 //
9468 // std::partial_ordering operator<=>(L, R);
9469 //
9470 // FIXME: The current specification for integral types doesn't play nice with
9471 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9472 // comparisons. Under the current spec this can lead to ambiguity during
9473 // overload resolution. For example:
9474 //
9475 // enum A : int {a};
9476 // auto x = (a <=> (long)42);
9477 //
9478 // error: call is ambiguous for arguments 'A' and 'long'.
9479 // note: candidate operator<=>(int, int)
9480 // note: candidate operator<=>(long, long)
9481 //
9482 // To avoid this error, this function deviates from the specification and adds
9483 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9484 // arithmetic types (the same as the generic relational overloads).
9485 //
9486 // For now this function acts as a placeholder.
9487 void addThreeWayArithmeticOverloads() {
9488 addGenericBinaryArithmeticOverloads();
9489 }
9490
9491 // C++ [over.built]p17:
9492 //
9493 // For every pair of promoted integral types L and R, there
9494 // exist candidate operator functions of the form
9495 //
9496 // LR operator%(L, R);
9497 // LR operator&(L, R);
9498 // LR operator^(L, R);
9499 // LR operator|(L, R);
9500 // L operator<<(L, R);
9501 // L operator>>(L, R);
9502 //
9503 // where LR is the result of the usual arithmetic conversions
9504 // between types L and R.
9505 void addBinaryBitwiseArithmeticOverloads() {
9506 if (!HasArithmeticOrEnumeralCandidateType)
9507 return;
9508
9509 for (unsigned Left = FirstPromotedIntegralType;
9510 Left < LastPromotedIntegralType; ++Left) {
9511 for (unsigned Right = FirstPromotedIntegralType;
9512 Right < LastPromotedIntegralType; ++Right) {
9513 QualType LandR[2] = { ArithmeticTypes[Left],
9514 ArithmeticTypes[Right] };
9515 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9516 }
9517 }
9518 }
9519
9520 // C++ [over.built]p20:
9521 //
9522 // For every pair (T, VQ), where T is an enumeration or
9523 // pointer to member type and VQ is either volatile or
9524 // empty, there exist candidate operator functions of the form
9525 //
9526 // VQ T& operator=(VQ T&, T);
9527 void addAssignmentMemberPointerOrEnumeralOverloads() {
9528 /// Set of (canonical) types that we've already handled.
9530
9531 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9532 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9533 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9534 continue;
9535
9536 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9537 }
9538
9539 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9540 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9541 continue;
9542
9543 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9544 }
9545 }
9546 }
9547
9548 // C++ [over.built]p19:
9549 //
9550 // For every pair (T, VQ), where T is any type and VQ is either
9551 // volatile or empty, there exist candidate operator functions
9552 // of the form
9553 //
9554 // T*VQ& operator=(T*VQ&, T*);
9555 //
9556 // C++ [over.built]p21:
9557 //
9558 // For every pair (T, VQ), where T is a cv-qualified or
9559 // cv-unqualified object type and VQ is either volatile or
9560 // empty, there exist candidate operator functions of the form
9561 //
9562 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9563 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9564 void addAssignmentPointerOverloads(bool isEqualOp) {
9565 /// Set of (canonical) types that we've already handled.
9567
9568 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9569 // If this is operator=, keep track of the builtin candidates we added.
9570 if (isEqualOp)
9571 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9572 else if (!PtrTy->getPointeeType()->isObjectType())
9573 continue;
9574
9575 // non-volatile version
9576 QualType ParamTypes[2] = {
9578 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9579 };
9580 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9581 /*IsAssignmentOperator=*/ isEqualOp);
9582
9583 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9584 VisibleTypeConversionsQuals.hasVolatile();
9585 if (NeedVolatile) {
9586 // volatile version
9587 ParamTypes[0] =
9589 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9590 /*IsAssignmentOperator=*/isEqualOp);
9591 }
9592
9593 if (!PtrTy.isRestrictQualified() &&
9594 VisibleTypeConversionsQuals.hasRestrict()) {
9595 // restrict version
9596 ParamTypes[0] =
9598 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9599 /*IsAssignmentOperator=*/isEqualOp);
9600
9601 if (NeedVolatile) {
9602 // volatile restrict version
9603 ParamTypes[0] =
9606 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9607 /*IsAssignmentOperator=*/isEqualOp);
9608 }
9609 }
9610 }
9611
9612 if (isEqualOp) {
9613 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9614 // Make sure we don't add the same candidate twice.
9615 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9616 continue;
9617
9618 QualType ParamTypes[2] = {
9620 PtrTy,
9621 };
9622
9623 // non-volatile version
9624 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9625 /*IsAssignmentOperator=*/true);
9626
9627 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9628 VisibleTypeConversionsQuals.hasVolatile();
9629 if (NeedVolatile) {
9630 // volatile version
9631 ParamTypes[0] = S.Context.getLValueReferenceType(
9632 S.Context.getVolatileType(PtrTy));
9633 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9634 /*IsAssignmentOperator=*/true);
9635 }
9636
9637 if (!PtrTy.isRestrictQualified() &&
9638 VisibleTypeConversionsQuals.hasRestrict()) {
9639 // restrict version
9640 ParamTypes[0] = S.Context.getLValueReferenceType(
9641 S.Context.getRestrictType(PtrTy));
9642 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9643 /*IsAssignmentOperator=*/true);
9644
9645 if (NeedVolatile) {
9646 // volatile restrict version
9647 ParamTypes[0] =
9650 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9651 /*IsAssignmentOperator=*/true);
9652 }
9653 }
9654 }
9655 }
9656 }
9657
9658 // C++ [over.built]p18:
9659 //
9660 // For every triple (L, VQ, R), where L is an arithmetic type,
9661 // VQ is either volatile or empty, and R is a promoted
9662 // arithmetic type, there exist candidate operator functions of
9663 // the form
9664 //
9665 // VQ L& operator=(VQ L&, R);
9666 // VQ L& operator*=(VQ L&, R);
9667 // VQ L& operator/=(VQ L&, R);
9668 // VQ L& operator+=(VQ L&, R);
9669 // VQ L& operator-=(VQ L&, R);
9670 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9671 if (!HasArithmeticOrEnumeralCandidateType)
9672 return;
9673
9674 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9675 for (unsigned Right = FirstPromotedArithmeticType;
9676 Right < LastPromotedArithmeticType; ++Right) {
9677 QualType ParamTypes[2];
9678 ParamTypes[1] = ArithmeticTypes[Right];
9680 S, ArithmeticTypes[Left], Args[0]);
9681
9683 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9684 ParamTypes[0] =
9685 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9686 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9687 /*IsAssignmentOperator=*/isEqualOp);
9688 });
9689 }
9690 }
9691
9692 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9693 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9694 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9695 QualType ParamTypes[2];
9696 ParamTypes[1] = Vec2Ty;
9697 // Add this built-in operator as a candidate (VQ is empty).
9698 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9699 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9700 /*IsAssignmentOperator=*/isEqualOp);
9701
9702 // Add this built-in operator as a candidate (VQ is 'volatile').
9703 if (VisibleTypeConversionsQuals.hasVolatile()) {
9704 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9705 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9706 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9707 /*IsAssignmentOperator=*/isEqualOp);
9708 }
9709 }
9710 }
9711
9712 // C++ [over.built]p22:
9713 //
9714 // For every triple (L, VQ, R), where L is an integral type, VQ
9715 // is either volatile or empty, and R is a promoted integral
9716 // type, there exist candidate operator functions of the form
9717 //
9718 // VQ L& operator%=(VQ L&, R);
9719 // VQ L& operator<<=(VQ L&, R);
9720 // VQ L& operator>>=(VQ L&, R);
9721 // VQ L& operator&=(VQ L&, R);
9722 // VQ L& operator^=(VQ L&, R);
9723 // VQ L& operator|=(VQ L&, R);
9724 void addAssignmentIntegralOverloads() {
9725 if (!HasArithmeticOrEnumeralCandidateType)
9726 return;
9727
9728 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9729 for (unsigned Right = FirstPromotedIntegralType;
9730 Right < LastPromotedIntegralType; ++Right) {
9731 QualType ParamTypes[2];
9732 ParamTypes[1] = ArithmeticTypes[Right];
9734 S, ArithmeticTypes[Left], Args[0]);
9735
9737 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9738 ParamTypes[0] =
9739 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9740 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9741 });
9742 }
9743 }
9744 }
9745
9746 // C++ [over.operator]p23:
9747 //
9748 // There also exist candidate operator functions of the form
9749 //
9750 // bool operator!(bool);
9751 // bool operator&&(bool, bool);
9752 // bool operator||(bool, bool);
9753 void addExclaimOverload() {
9754 QualType ParamTy = S.Context.BoolTy;
9755 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9756 /*IsAssignmentOperator=*/false,
9757 /*NumContextualBoolArguments=*/1);
9758 }
9759 void addAmpAmpOrPipePipeOverload() {
9760 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9761 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9762 /*IsAssignmentOperator=*/false,
9763 /*NumContextualBoolArguments=*/2);
9764 }
9765
9766 // C++ [over.built]p13:
9767 //
9768 // For every cv-qualified or cv-unqualified object type T there
9769 // exist candidate operator functions of the form
9770 //
9771 // T* operator+(T*, ptrdiff_t); [ABOVE]
9772 // T& operator[](T*, ptrdiff_t);
9773 // T* operator-(T*, ptrdiff_t); [ABOVE]
9774 // T* operator+(ptrdiff_t, T*); [ABOVE]
9775 // T& operator[](ptrdiff_t, T*);
9776 void addSubscriptOverloads() {
9777 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9778 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9779 QualType PointeeType = PtrTy->getPointeeType();
9780 if (!PointeeType->isObjectType())
9781 continue;
9782
9783 // T& operator[](T*, ptrdiff_t)
9784 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9785 }
9786
9787 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9788 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9789 QualType PointeeType = PtrTy->getPointeeType();
9790 if (!PointeeType->isObjectType())
9791 continue;
9792
9793 // T& operator[](ptrdiff_t, T*)
9794 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9795 }
9796 }
9797
9798 // C++ [over.built]p11:
9799 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9800 // C1 is the same type as C2 or is a derived class of C2, T is an object
9801 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9802 // there exist candidate operator functions of the form
9803 //
9804 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9805 //
9806 // where CV12 is the union of CV1 and CV2.
9807 void addArrowStarOverloads() {
9808 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9809 QualType C1Ty = PtrTy;
9810 QualType C1;
9812 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9813 if (!isa<RecordType>(C1))
9814 continue;
9815 // heuristic to reduce number of builtin candidates in the set.
9816 // Add volatile/restrict version only if there are conversions to a
9817 // volatile/restrict type.
9818 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9819 continue;
9820 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9821 continue;
9822 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9823 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9824 QualType C2 = QualType(mptr->getClass(), 0);
9825 C2 = C2.getUnqualifiedType();
9826 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9827 break;
9828 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9829 // build CV12 T&
9830 QualType T = mptr->getPointeeType();
9831 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9833 continue;
9834 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9836 continue;
9837 T = Q1.apply(S.Context, T);
9838 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9839 }
9840 }
9841 }
9842
9843 // Note that we don't consider the first argument, since it has been
9844 // contextually converted to bool long ago. The candidates below are
9845 // therefore added as binary.
9846 //
9847 // C++ [over.built]p25:
9848 // For every type T, where T is a pointer, pointer-to-member, or scoped
9849 // enumeration type, there exist candidate operator functions of the form
9850 //
9851 // T operator?(bool, T, T);
9852 //
9853 void addConditionalOperatorOverloads() {
9854 /// Set of (canonical) types that we've already handled.
9856
9857 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9858 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9859 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9860 continue;
9861
9862 QualType ParamTypes[2] = {PtrTy, PtrTy};
9863 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9864 }
9865
9866 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9867 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9868 continue;
9869
9870 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9871 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9872 }
9873
9874 if (S.getLangOpts().CPlusPlus11) {
9875 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9876 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9877 continue;
9878
9879 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9880 continue;
9881
9882 QualType ParamTypes[2] = {EnumTy, EnumTy};
9883 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9884 }
9885 }
9886 }
9887 }
9888};
9889
9890} // end anonymous namespace
9891
9892/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9893/// operator overloads to the candidate set (C++ [over.built]), based
9894/// on the operator @p Op and the arguments given. For example, if the
9895/// operator is a binary '+', this routine might add "int
9896/// operator+(int, int)" to cover integer addition.
9898 SourceLocation OpLoc,
9899 ArrayRef<Expr *> Args,
9900 OverloadCandidateSet &CandidateSet) {
9901 // Find all of the types that the arguments can convert to, but only
9902 // if the operator we're looking at has built-in operator candidates
9903 // that make use of these types. Also record whether we encounter non-record
9904 // candidate types or either arithmetic or enumeral candidate types.
9905 QualifiersAndAtomic VisibleTypeConversionsQuals;
9906 VisibleTypeConversionsQuals.addConst();
9907 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9908 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9909 if (Args[ArgIdx]->getType()->isAtomicType())
9910 VisibleTypeConversionsQuals.addAtomic();
9911 }
9912
9913 bool HasNonRecordCandidateType = false;
9914 bool HasArithmeticOrEnumeralCandidateType = false;
9916 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9917 CandidateTypes.emplace_back(*this);
9918 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9919 OpLoc,
9920 true,
9921 (Op == OO_Exclaim ||
9922 Op == OO_AmpAmp ||
9923 Op == OO_PipePipe),
9924 VisibleTypeConversionsQuals);
9925 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9926 CandidateTypes[ArgIdx].hasNonRecordTypes();
9927 HasArithmeticOrEnumeralCandidateType =
9928 HasArithmeticOrEnumeralCandidateType ||
9929 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9930 }
9931
9932 // Exit early when no non-record types have been added to the candidate set
9933 // for any of the arguments to the operator.
9934 //
9935 // We can't exit early for !, ||, or &&, since there we have always have
9936 // 'bool' overloads.
9937 if (!HasNonRecordCandidateType &&
9938 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9939 return;
9940
9941 // Setup an object to manage the common state for building overloads.
9942 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9943 VisibleTypeConversionsQuals,
9944 HasArithmeticOrEnumeralCandidateType,
9945 CandidateTypes, CandidateSet);
9946
9947 // Dispatch over the operation to add in only those overloads which apply.
9948 switch (Op) {
9949 case OO_None:
9951 llvm_unreachable("Expected an overloaded operator");
9952
9953 case OO_New:
9954 case OO_Delete:
9955 case OO_Array_New:
9956 case OO_Array_Delete:
9957 case OO_Call:
9958 llvm_unreachable(
9959 "Special operators don't use AddBuiltinOperatorCandidates");
9960
9961 case OO_Comma:
9962 case OO_Arrow:
9963 case OO_Coawait:
9964 // C++ [over.match.oper]p3:
9965 // -- For the operator ',', the unary operator '&', the
9966 // operator '->', or the operator 'co_await', the
9967 // built-in candidates set is empty.
9968 break;
9969
9970 case OO_Plus: // '+' is either unary or binary
9971 if (Args.size() == 1)
9972 OpBuilder.addUnaryPlusPointerOverloads();
9973 [[fallthrough]];
9974
9975 case OO_Minus: // '-' is either unary or binary
9976 if (Args.size() == 1) {
9977 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9978 } else {
9979 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9980 OpBuilder.addGenericBinaryArithmeticOverloads();
9981 OpBuilder.addMatrixBinaryArithmeticOverloads();
9982 }
9983 break;
9984
9985 case OO_Star: // '*' is either unary or binary
9986 if (Args.size() == 1)
9987 OpBuilder.addUnaryStarPointerOverloads();
9988 else {
9989 OpBuilder.addGenericBinaryArithmeticOverloads();
9990 OpBuilder.addMatrixBinaryArithmeticOverloads();
9991 }
9992 break;
9993
9994 case OO_Slash:
9995 OpBuilder.addGenericBinaryArithmeticOverloads();
9996 break;
9997
9998 case OO_PlusPlus:
9999 case OO_MinusMinus:
10000 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10001 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10002 break;
10003
10004 case OO_EqualEqual:
10005 case OO_ExclaimEqual:
10006 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10007 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10008 OpBuilder.addGenericBinaryArithmeticOverloads();
10009 break;
10010
10011 case OO_Less:
10012 case OO_Greater:
10013 case OO_LessEqual:
10014 case OO_GreaterEqual:
10015 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10016 OpBuilder.addGenericBinaryArithmeticOverloads();
10017 break;
10018
10019 case OO_Spaceship:
10020 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10021 OpBuilder.addThreeWayArithmeticOverloads();
10022 break;
10023
10024 case OO_Percent:
10025 case OO_Caret:
10026 case OO_Pipe:
10027 case OO_LessLess:
10028 case OO_GreaterGreater:
10029 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10030 break;
10031
10032 case OO_Amp: // '&' is either unary or binary
10033 if (Args.size() == 1)
10034 // C++ [over.match.oper]p3:
10035 // -- For the operator ',', the unary operator '&', or the
10036 // operator '->', the built-in candidates set is empty.
10037 break;
10038
10039 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10040 break;
10041
10042 case OO_Tilde:
10043 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10044 break;
10045
10046 case OO_Equal:
10047 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10048 [[fallthrough]];
10049
10050 case OO_PlusEqual:
10051 case OO_MinusEqual:
10052 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10053 [[fallthrough]];
10054
10055 case OO_StarEqual:
10056 case OO_SlashEqual:
10057 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10058 break;
10059
10060 case OO_PercentEqual:
10061 case OO_LessLessEqual:
10062 case OO_GreaterGreaterEqual:
10063 case OO_AmpEqual:
10064 case OO_CaretEqual:
10065 case OO_PipeEqual:
10066 OpBuilder.addAssignmentIntegralOverloads();
10067 break;
10068
10069 case OO_Exclaim:
10070 OpBuilder.addExclaimOverload();
10071 break;
10072
10073 case OO_AmpAmp:
10074 case OO_PipePipe:
10075 OpBuilder.addAmpAmpOrPipePipeOverload();
10076 break;
10077
10078 case OO_Subscript:
10079 if (Args.size() == 2)
10080 OpBuilder.addSubscriptOverloads();
10081 break;
10082
10083 case OO_ArrowStar:
10084 OpBuilder.addArrowStarOverloads();
10085 break;
10086
10087 case OO_Conditional:
10088 OpBuilder.addConditionalOperatorOverloads();
10089 OpBuilder.addGenericBinaryArithmeticOverloads();
10090 break;
10091 }
10092}
10093
10094/// Add function candidates found via argument-dependent lookup
10095/// to the set of overloading candidates.
10096///
10097/// This routine performs argument-dependent name lookup based on the
10098/// given function name (which may also be an operator name) and adds
10099/// all of the overload candidates found by ADL to the overload
10100/// candidate set (C++ [basic.lookup.argdep]).
10101void
10103 SourceLocation Loc,
10104 ArrayRef<Expr *> Args,
10105 TemplateArgumentListInfo *ExplicitTemplateArgs,
10106 OverloadCandidateSet& CandidateSet,
10107 bool PartialOverloading) {
10108 ADLResult Fns;
10109
10110 // FIXME: This approach for uniquing ADL results (and removing
10111 // redundant candidates from the set) relies on pointer-equality,
10112 // which means we need to key off the canonical decl. However,
10113 // always going back to the canonical decl might not get us the
10114 // right set of default arguments. What default arguments are
10115 // we supposed to consider on ADL candidates, anyway?
10116
10117 // FIXME: Pass in the explicit template arguments?
10118 ArgumentDependentLookup(Name, Loc, Args, Fns);
10119
10120 // Erase all of the candidates we already knew about.
10121 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10122 CandEnd = CandidateSet.end();
10123 Cand != CandEnd; ++Cand)
10124 if (Cand->Function) {
10125 Fns.erase(Cand->Function);
10126 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
10127 Fns.erase(FunTmpl);
10128 }
10129
10130 // For each of the ADL candidates we found, add it to the overload
10131 // set.
10132 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10134
10135 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10136 if (ExplicitTemplateArgs)
10137 continue;
10138
10139 AddOverloadCandidate(
10140 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10141 PartialOverloading, /*AllowExplicit=*/true,
10142 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10143 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10144 AddOverloadCandidate(
10145 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10146 /*SuppressUserConversions=*/false, PartialOverloading,
10147 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10148 ADLCallKind::UsesADL, std::nullopt,
10150 }
10151 } else {
10152 auto *FTD = cast<FunctionTemplateDecl>(*I);
10153 AddTemplateOverloadCandidate(
10154 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10155 /*SuppressUserConversions=*/false, PartialOverloading,
10156 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10157 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10158 *this, Args, FTD->getTemplatedDecl())) {
10159 AddTemplateOverloadCandidate(
10160 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10161 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10162 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10164 }
10165 }
10166 }
10167}
10168
10169namespace {
10170enum class Comparison { Equal, Better, Worse };
10171}
10172
10173/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10174/// overload resolution.
10175///
10176/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10177/// Cand1's first N enable_if attributes have precisely the same conditions as
10178/// Cand2's first N enable_if attributes (where N = the number of enable_if
10179/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10180///
10181/// Note that you can have a pair of candidates such that Cand1's enable_if
10182/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10183/// worse than Cand1's.
10184static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10185 const FunctionDecl *Cand2) {
10186 // Common case: One (or both) decls don't have enable_if attrs.
10187 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10188 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10189 if (!Cand1Attr || !Cand2Attr) {
10190 if (Cand1Attr == Cand2Attr)
10191 return Comparison::Equal;
10192 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10193 }
10194
10195 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10196 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10197
10198 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10199 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10200 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10201 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10202
10203 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10204 // has fewer enable_if attributes than Cand2, and vice versa.
10205 if (!Cand1A)
10206 return Comparison::Worse;
10207 if (!Cand2A)
10208 return Comparison::Better;
10209
10210 Cand1ID.clear();
10211 Cand2ID.clear();
10212
10213 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10214 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10215 if (Cand1ID != Cand2ID)
10216 return Comparison::Worse;
10217 }
10218
10219 return Comparison::Equal;
10220}
10221
10222static Comparison
10224 const OverloadCandidate &Cand2) {
10225 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10226 !Cand2.Function->isMultiVersion())
10227 return Comparison::Equal;
10228
10229 // If both are invalid, they are equal. If one of them is invalid, the other
10230 // is better.
10231 if (Cand1.Function->isInvalidDecl()) {
10232 if (Cand2.Function->isInvalidDecl())
10233 return Comparison::Equal;
10234 return Comparison::Worse;
10235 }
10236 if (Cand2.Function->isInvalidDecl())
10237 return Comparison::Better;
10238
10239 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10240 // cpu_dispatch, else arbitrarily based on the identifiers.
10241 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10242 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10243 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10244 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10245
10246 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10247 return Comparison::Equal;
10248
10249 if (Cand1CPUDisp && !Cand2CPUDisp)
10250 return Comparison::Better;
10251 if (Cand2CPUDisp && !Cand1CPUDisp)
10252 return Comparison::Worse;
10253
10254 if (Cand1CPUSpec && Cand2CPUSpec) {
10255 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10256 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10257 ? Comparison::Better
10258 : Comparison::Worse;
10259
10260 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10261 FirstDiff = std::mismatch(
10262 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10263 Cand2CPUSpec->cpus_begin(),
10264 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10265 return LHS->getName() == RHS->getName();
10266 });
10267
10268 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10269 "Two different cpu-specific versions should not have the same "
10270 "identifier list, otherwise they'd be the same decl!");
10271 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10272 ? Comparison::Better
10273 : Comparison::Worse;
10274 }
10275 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10276}
10277
10278/// Compute the type of the implicit object parameter for the given function,
10279/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10280/// null QualType if there is a 'matches anything' implicit object parameter.
10281static std::optional<QualType>
10283 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10284 return std::nullopt;
10285
10286 auto *M = cast<CXXMethodDecl>(F);
10287 // Static member functions' object parameters match all types.
10288 if (M->isStatic())
10289 return QualType();
10290 return M->getFunctionObjectParameterReferenceType();
10291}
10292
10293// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10294// represent the same entity.
10295static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10296 const FunctionDecl *F2) {
10297 if (declaresSameEntity(F1, F2))
10298 return true;
10299 auto PT1 = F1->getPrimaryTemplate();
10300 auto PT2 = F2->getPrimaryTemplate();
10301 if (PT1 && PT2) {
10302 if (declaresSameEntity(PT1, PT2) ||
10303 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10304 PT2->getInstantiatedFromMemberTemplate()))
10305 return true;
10306 }
10307 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10308 // different functions with same params). Consider removing this (as no test
10309 // fail w/o it).
10310 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10311 if (First) {
10312 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10313 return *T;
10314 }
10315 assert(I < F->getNumParams());
10316 return F->getParamDecl(I++)->getType();
10317 };
10318
10319 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10320 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10321
10322 if (F1NumParams != F2NumParams)
10323 return false;
10324
10325 unsigned I1 = 0, I2 = 0;
10326 for (unsigned I = 0; I != F1NumParams; ++I) {
10327 QualType T1 = NextParam(F1, I1, I == 0);
10328 QualType T2 = NextParam(F2, I2, I == 0);
10329 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10330 if (!Context.hasSameUnqualifiedType(T1, T2))
10331 return false;
10332 }
10333 return true;
10334}
10335
10336/// We're allowed to use constraints partial ordering only if the candidates
10337/// have the same parameter types:
10338/// [over.match.best.general]p2.6
10339/// F1 and F2 are non-template functions with the same
10340/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10342 const OverloadCandidate &Cand1,
10343 const OverloadCandidate &Cand2) {
10344 if (!Cand1.Function || !Cand2.Function)
10345 return false;
10346
10347 FunctionDecl *Fn1 = Cand1.Function;
10348 FunctionDecl *Fn2 = Cand2.Function;
10349
10350 if (Fn1->isVariadic() != Fn1->isVariadic())
10351 return false;
10352
10354 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10355 return false;
10356
10357 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10358 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10359 if (Mem1 && Mem2) {
10360 // if they are member functions, both are direct members of the same class,
10361 // and
10362 if (Mem1->getParent() != Mem2->getParent())
10363 return false;
10364 // if both are non-static member functions, they have the same types for
10365 // their object parameters
10366 if (Mem1->isInstance() && Mem2->isInstance() &&
10368 Mem1->getFunctionObjectParameterReferenceType(),
10369 Mem1->getFunctionObjectParameterReferenceType()))
10370 return false;
10371 }
10372 return true;
10373}
10374
10375/// isBetterOverloadCandidate - Determines whether the first overload
10376/// candidate is a better candidate than the second (C++ 13.3.3p1).
10378 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10380 // Define viable functions to be better candidates than non-viable
10381 // functions.
10382 if (!Cand2.Viable)
10383 return Cand1.Viable;
10384 else if (!Cand1.Viable)
10385 return false;
10386
10387 // [CUDA] A function with 'never' preference is marked not viable, therefore
10388 // is never shown up here. The worst preference shown up here is 'wrong side',
10389 // e.g. an H function called by a HD function in device compilation. This is
10390 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10391 // function which is called only by an H function. A deferred diagnostic will
10392 // be triggered if it is emitted. However a wrong-sided function is still
10393 // a viable candidate here.
10394 //
10395 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10396 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10397 // can be emitted, Cand1 is not better than Cand2. This rule should have
10398 // precedence over other rules.
10399 //
10400 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10401 // other rules should be used to determine which is better. This is because
10402 // host/device based overloading resolution is mostly for determining
10403 // viability of a function. If two functions are both viable, other factors
10404 // should take precedence in preference, e.g. the standard-defined preferences
10405 // like argument conversion ranks or enable_if partial-ordering. The
10406 // preference for pass-object-size parameters is probably most similar to a
10407 // type-based-overloading decision and so should take priority.
10408 //
10409 // If other rules cannot determine which is better, CUDA preference will be
10410 // used again to determine which is better.
10411 //
10412 // TODO: Currently IdentifyCUDAPreference does not return correct values
10413 // for functions called in global variable initializers due to missing
10414 // correct context about device/host. Therefore we can only enforce this
10415 // rule when there is a caller. We should enforce this rule for functions
10416 // in global variable initializers once proper context is added.
10417 //
10418 // TODO: We can only enable the hostness based overloading resolution when
10419 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10420 // overloading resolution diagnostics.
10421 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10422 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10423 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10424 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
10425 bool IsCand1ImplicitHD =
10427 bool IsCand2ImplicitHD =
10429 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
10430 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
10431 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
10432 // The implicit HD function may be a function in a system header which
10433 // is forced by pragma. In device compilation, if we prefer HD candidates
10434 // over wrong-sided candidates, overloading resolution may change, which
10435 // may result in non-deferrable diagnostics. As a workaround, we let
10436 // implicit HD candidates take equal preference as wrong-sided candidates.
10437 // This will preserve the overloading resolution.
10438 // TODO: We still need special handling of implicit HD functions since
10439 // they may incur other diagnostics to be deferred. We should make all
10440 // host/device related diagnostics deferrable and remove special handling
10441 // of implicit HD functions.
10442 auto EmitThreshold =
10443 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10444 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10447 auto Cand1Emittable = P1 > EmitThreshold;
10448 auto Cand2Emittable = P2 > EmitThreshold;
10449 if (Cand1Emittable && !Cand2Emittable)
10450 return true;
10451 if (!Cand1Emittable && Cand2Emittable)
10452 return false;
10453 }
10454 }
10455
10456 // C++ [over.match.best]p1: (Changed in C++23)
10457 //
10458 // -- if F is a static member function, ICS1(F) is defined such
10459 // that ICS1(F) is neither better nor worse than ICS1(G) for
10460 // any function G, and, symmetrically, ICS1(G) is neither
10461 // better nor worse than ICS1(F).
10462 unsigned StartArg = 0;
10463 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10464 StartArg = 1;
10465
10466 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10467 // We don't allow incompatible pointer conversions in C++.
10468 if (!S.getLangOpts().CPlusPlus)
10469 return ICS.isStandard() &&
10470 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10471
10472 // The only ill-formed conversion we allow in C++ is the string literal to
10473 // char* conversion, which is only considered ill-formed after C++11.
10474 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10476 };
10477
10478 // Define functions that don't require ill-formed conversions for a given
10479 // argument to be better candidates than functions that do.
10480 unsigned NumArgs = Cand1.Conversions.size();
10481 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10482 bool HasBetterConversion = false;
10483 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10484 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10485 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10486 if (Cand1Bad != Cand2Bad) {
10487 if (Cand1Bad)
10488 return false;
10489 HasBetterConversion = true;
10490 }
10491 }
10492
10493 if (HasBetterConversion)
10494 return true;
10495
10496 // C++ [over.match.best]p1:
10497 // A viable function F1 is defined to be a better function than another
10498 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10499 // conversion sequence than ICSi(F2), and then...
10500 bool HasWorseConversion = false;
10501 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10503 Cand1.Conversions[ArgIdx],
10504 Cand2.Conversions[ArgIdx])) {
10506 // Cand1 has a better conversion sequence.
10507 HasBetterConversion = true;
10508 break;
10509
10511 if (Cand1.Function && Cand2.Function &&
10512 Cand1.isReversed() != Cand2.isReversed() &&
10513 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10514 // Work around large-scale breakage caused by considering reversed
10515 // forms of operator== in C++20:
10516 //
10517 // When comparing a function against a reversed function, if we have a
10518 // better conversion for one argument and a worse conversion for the
10519 // other, the implicit conversion sequences are treated as being equally
10520 // good.
10521 //
10522 // This prevents a comparison function from being considered ambiguous
10523 // with a reversed form that is written in the same way.
10524 //
10525 // We diagnose this as an extension from CreateOverloadedBinOp.
10526 HasWorseConversion = true;
10527 break;
10528 }
10529
10530 // Cand1 can't be better than Cand2.
10531 return false;
10532
10534 // Do nothing.
10535 break;
10536 }
10537 }
10538
10539 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10540 // ICSj(F2), or, if not that,
10541 if (HasBetterConversion && !HasWorseConversion)
10542 return true;
10543
10544 // -- the context is an initialization by user-defined conversion
10545 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10546 // from the return type of F1 to the destination type (i.e.,
10547 // the type of the entity being initialized) is a better
10548 // conversion sequence than the standard conversion sequence
10549 // from the return type of F2 to the destination type.
10551 Cand1.Function && Cand2.Function &&
10552 isa<CXXConversionDecl>(Cand1.Function) &&
10553 isa<CXXConversionDecl>(Cand2.Function)) {
10554 // First check whether we prefer one of the conversion functions over the
10555 // other. This only distinguishes the results in non-standard, extension
10556 // cases such as the conversion from a lambda closure type to a function
10557 // pointer or block.
10562 Cand1.FinalConversion,
10563 Cand2.FinalConversion);
10564
10567
10568 // FIXME: Compare kind of reference binding if conversion functions
10569 // convert to a reference type used in direct reference binding, per
10570 // C++14 [over.match.best]p1 section 2 bullet 3.
10571 }
10572
10573 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10574 // as combined with the resolution to CWG issue 243.
10575 //
10576 // When the context is initialization by constructor ([over.match.ctor] or
10577 // either phase of [over.match.list]), a constructor is preferred over
10578 // a conversion function.
10579 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10580 Cand1.Function && Cand2.Function &&
10581 isa<CXXConstructorDecl>(Cand1.Function) !=
10582 isa<CXXConstructorDecl>(Cand2.Function))
10583 return isa<CXXConstructorDecl>(Cand1.Function);
10584
10585 // -- F1 is a non-template function and F2 is a function template
10586 // specialization, or, if not that,
10587 bool Cand1IsSpecialization = Cand1.Function &&
10589 bool Cand2IsSpecialization = Cand2.Function &&
10591 if (Cand1IsSpecialization != Cand2IsSpecialization)
10592 return Cand2IsSpecialization;
10593
10594 // -- F1 and F2 are function template specializations, and the function
10595 // template for F1 is more specialized than the template for F2
10596 // according to the partial ordering rules described in 14.5.5.2, or,
10597 // if not that,
10598 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10599 const auto *Obj1Context =
10600 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10601 const auto *Obj2Context =
10602 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10603 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10605 Cand2.Function->getPrimaryTemplate(), Loc,
10606 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10607 : TPOC_Call,
10609 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10610 : QualType{},
10611 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10612 : QualType{},
10613 Cand1.isReversed() ^ Cand2.isReversed())) {
10614 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10615 }
10616 }
10617
10618 // -— F1 and F2 are non-template functions with the same
10619 // parameter-type-lists, and F1 is more constrained than F2 [...],
10620 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10621 sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10622 FunctionDecl *Function1 = Cand1.Function;
10623 FunctionDecl *Function2 = Cand2.Function;
10624 if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10625 Function1 = MF;
10626 if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10627 Function2 = MF;
10628
10629 const Expr *RC1 = Function1->getTrailingRequiresClause();
10630 const Expr *RC2 = Function2->getTrailingRequiresClause();
10631 if (RC1 && RC2) {
10632 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10633 if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10634 AtLeastAsConstrained1) ||
10635 S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10636 AtLeastAsConstrained2))
10637 return false;
10638 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10639 return AtLeastAsConstrained1;
10640 } else if (RC1 || RC2) {
10641 return RC1 != nullptr;
10642 }
10643 }
10644
10645 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10646 // class B of D, and for all arguments the corresponding parameters of
10647 // F1 and F2 have the same type.
10648 // FIXME: Implement the "all parameters have the same type" check.
10649 bool Cand1IsInherited =
10650 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10651 bool Cand2IsInherited =
10652 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10653 if (Cand1IsInherited != Cand2IsInherited)
10654 return Cand2IsInherited;
10655 else if (Cand1IsInherited) {
10656 assert(Cand2IsInherited);
10657 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10658 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10659 if (Cand1Class->isDerivedFrom(Cand2Class))
10660 return true;
10661 if (Cand2Class->isDerivedFrom(Cand1Class))
10662 return false;
10663 // Inherited from sibling base classes: still ambiguous.
10664 }
10665
10666 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10667 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10668 // with reversed order of parameters and F1 is not
10669 //
10670 // We rank reversed + different operator as worse than just reversed, but
10671 // that comparison can never happen, because we only consider reversing for
10672 // the maximally-rewritten operator (== or <=>).
10673 if (Cand1.RewriteKind != Cand2.RewriteKind)
10674 return Cand1.RewriteKind < Cand2.RewriteKind;
10675
10676 // Check C++17 tie-breakers for deduction guides.
10677 {
10678 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10679 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10680 if (Guide1 && Guide2) {
10681 // -- F1 is generated from a deduction-guide and F2 is not
10682 if (Guide1->isImplicit() != Guide2->isImplicit())
10683 return Guide2->isImplicit();
10684
10685 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10686 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10687 return true;
10688 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10689 return false;
10690
10691 // --F1 is generated from a non-template constructor and F2 is generated
10692 // from a constructor template
10693 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10694 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10695 if (Constructor1 && Constructor2) {
10696 bool isC1Templated = Constructor1->getTemplatedKind() !=
10698 bool isC2Templated = Constructor2->getTemplatedKind() !=
10700 if (isC1Templated != isC2Templated)
10701 return isC2Templated;
10702 }
10703 }
10704 }
10705
10706 // Check for enable_if value-based overload resolution.
10707 if (Cand1.Function && Cand2.Function) {
10708 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10709 if (Cmp != Comparison::Equal)
10710 return Cmp == Comparison::Better;
10711 }
10712
10713 bool HasPS1 = Cand1.Function != nullptr &&
10715 bool HasPS2 = Cand2.Function != nullptr &&
10717 if (HasPS1 != HasPS2 && HasPS1)
10718 return true;
10719
10720 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10721 if (MV == Comparison::Better)
10722 return true;
10723 if (MV == Comparison::Worse)
10724 return false;
10725
10726 // If other rules cannot determine which is better, CUDA preference is used
10727 // to determine which is better.
10728 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10729 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10730 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10731 S.IdentifyCUDAPreference(Caller, Cand2.Function);
10732 }
10733
10734 // General member function overloading is handled above, so this only handles
10735 // constructors with address spaces.
10736 // This only handles address spaces since C++ has no other
10737 // qualifier that can be used with constructors.
10738 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10739 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10740 if (CD1 && CD2) {
10741 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10742 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10743 if (AS1 != AS2) {
10745 return true;
10747 return false;
10748 }
10749 }
10750
10751 return false;
10752}
10753
10754/// Determine whether two declarations are "equivalent" for the purposes of
10755/// name lookup and overload resolution. This applies when the same internal/no
10756/// linkage entity is defined by two modules (probably by textually including
10757/// the same header). In such a case, we don't consider the declarations to
10758/// declare the same entity, but we also don't want lookups with both
10759/// declarations visible to be ambiguous in some cases (this happens when using
10760/// a modularized libstdc++).
10762 const NamedDecl *B) {
10763 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10764 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10765 if (!VA || !VB)
10766 return false;
10767
10768 // The declarations must be declaring the same name as an internal linkage
10769 // entity in different modules.
10770 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10771 VB->getDeclContext()->getRedeclContext()) ||
10772 getOwningModule(VA) == getOwningModule(VB) ||
10773 VA->isExternallyVisible() || VB->isExternallyVisible())
10774 return false;
10775
10776 // Check that the declarations appear to be equivalent.
10777 //
10778 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10779 // For constants and functions, we should check the initializer or body is
10780 // the same. For non-constant variables, we shouldn't allow it at all.
10781 if (Context.hasSameType(VA->getType(), VB->getType()))
10782 return true;
10783
10784 // Enum constants within unnamed enumerations will have different types, but
10785 // may still be similar enough to be interchangeable for our purposes.
10786 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10787 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10788 // Only handle anonymous enums. If the enumerations were named and
10789 // equivalent, they would have been merged to the same type.
10790 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10791 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10792 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10793 !Context.hasSameType(EnumA->getIntegerType(),
10794 EnumB->getIntegerType()))
10795 return false;
10796 // Allow this only if the value is the same for both enumerators.
10797 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10798 }
10799 }
10800
10801 // Nothing else is sufficiently similar.
10802 return false;
10803}
10804
10807 assert(D && "Unknown declaration");
10808 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10809
10810 Module *M = getOwningModule(D);
10811 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10812 << !M << (M ? M->getFullModuleName() : "");
10813
10814 for (auto *E : Equiv) {
10815 Module *M = getOwningModule(E);
10816 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10817 << !M << (M ? M->getFullModuleName() : "");
10818 }
10819}
10820
10822 return FailureKind == ovl_fail_bad_deduction &&
10823 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10825 static_cast<CNSInfo *>(DeductionFailure.Data)
10826 ->Satisfaction.ContainsErrors;
10827}
10828
10829/// Computes the best viable function (C++ 13.3.3)
10830/// within an overload candidate set.
10831///
10832/// \param Loc The location of the function name (or operator symbol) for
10833/// which overload resolution occurs.
10834///
10835/// \param Best If overload resolution was successful or found a deleted
10836/// function, \p Best points to the candidate function found.
10837///
10838/// \returns The result of overload resolution.
10841 iterator &Best) {
10843 std::transform(begin(), end(), std::back_inserter(Candidates),
10844 [](OverloadCandidate &Cand) { return &Cand; });
10845
10846 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10847 // are accepted by both clang and NVCC. However, during a particular
10848 // compilation mode only one call variant is viable. We need to
10849 // exclude non-viable overload candidates from consideration based
10850 // only on their host/device attributes. Specifically, if one
10851 // candidate call is WrongSide and the other is SameSide, we ignore
10852 // the WrongSide candidate.
10853 // We only need to remove wrong-sided candidates here if
10854 // -fgpu-exclude-wrong-side-overloads is off. When
10855 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10856 // uniformly in isBetterOverloadCandidate.
10857 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10858 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10859 bool ContainsSameSideCandidate =
10860 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10861 // Check viable function only.
10862 return Cand->Viable && Cand->Function &&
10863 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10865 });
10866 if (ContainsSameSideCandidate) {
10867 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10868 // Check viable function only to avoid unnecessary data copying/moving.
10869 return Cand->Viable && Cand->Function &&
10870 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10872 };
10873 llvm::erase_if(Candidates, IsWrongSideCandidate);
10874 }
10875 }
10876
10877 // Find the best viable function.
10878 Best = end();
10879 for (auto *Cand : Candidates) {
10880 Cand->Best = false;
10881 if (Cand->Viable) {
10882 if (Best == end() ||
10883 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10884 Best = Cand;
10885 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10886 // This candidate has constraint that we were unable to evaluate because
10887 // it referenced an expression that contained an error. Rather than fall
10888 // back onto a potentially unintended candidate (made worse by
10889 // subsuming constraints), treat this as 'no viable candidate'.
10890 Best = end();
10891 return OR_No_Viable_Function;
10892 }
10893 }
10894
10895 // If we didn't find any viable functions, abort.
10896 if (Best == end())
10897 return OR_No_Viable_Function;
10898
10900
10902 PendingBest.push_back(&*Best);
10903 Best->Best = true;
10904
10905 // Make sure that this function is better than every other viable
10906 // function. If not, we have an ambiguity.
10907 while (!PendingBest.empty()) {
10908 auto *Curr = PendingBest.pop_back_val();
10909 for (auto *Cand : Candidates) {
10910 if (Cand->Viable && !Cand->Best &&
10911 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10912 PendingBest.push_back(Cand);
10913 Cand->Best = true;
10914
10916 Curr->Function))
10917 EquivalentCands.push_back(Cand->Function);
10918 else
10919 Best = end();
10920 }
10921 }
10922 }
10923
10924 // If we found more than one best candidate, this is ambiguous.
10925 if (Best == end())
10926 return OR_Ambiguous;
10927
10928 // Best is the best viable function.
10929 if (Best->Function && Best->Function->isDeleted())
10930 return OR_Deleted;
10931
10932 if (!EquivalentCands.empty())
10934 EquivalentCands);
10935
10936 return OR_Success;
10937}
10938
10939namespace {
10940
10941enum OverloadCandidateKind {
10942 oc_function,
10943 oc_method,
10944 oc_reversed_binary_operator,
10945 oc_constructor,
10946 oc_implicit_default_constructor,
10947 oc_implicit_copy_constructor,
10948 oc_implicit_move_constructor,
10949 oc_implicit_copy_assignment,
10950 oc_implicit_move_assignment,
10951 oc_implicit_equality_comparison,
10952 oc_inherited_constructor
10953};
10954
10955enum OverloadCandidateSelect {
10956 ocs_non_template,
10957 ocs_template,
10958 ocs_described_template,
10959};
10960
10961static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10962ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10963 const FunctionDecl *Fn,
10965 std::string &Description) {
10966
10967 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10968 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10969 isTemplate = true;
10970 Description = S.getTemplateArgumentBindingsText(
10971 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10972 }
10973
10974 OverloadCandidateSelect Select = [&]() {
10975 if (!Description.empty())
10976 return ocs_described_template;
10977 return isTemplate ? ocs_template : ocs_non_template;
10978 }();
10979
10980 OverloadCandidateKind Kind = [&]() {
10981 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10982 return oc_implicit_equality_comparison;
10983
10984 if (CRK & CRK_Reversed)
10985 return oc_reversed_binary_operator;
10986
10987 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10988 if (!Ctor->isImplicit()) {
10989 if (isa<ConstructorUsingShadowDecl>(Found))
10990 return oc_inherited_constructor;
10991 else
10992 return oc_constructor;
10993 }
10994
10995 if (Ctor->isDefaultConstructor())
10996 return oc_implicit_default_constructor;
10997
10998 if (Ctor->isMoveConstructor())
10999 return oc_implicit_move_constructor;
11000
11001 assert(Ctor->isCopyConstructor() &&
11002 "unexpected sort of implicit constructor");
11003 return oc_implicit_copy_constructor;
11004 }
11005
11006 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11007 // This actually gets spelled 'candidate function' for now, but
11008 // it doesn't hurt to split it out.
11009 if (!Meth->isImplicit())
11010 return oc_method;
11011
11012 if (Meth->isMoveAssignmentOperator())
11013 return oc_implicit_move_assignment;
11014
11015 if (Meth->isCopyAssignmentOperator())
11016 return oc_implicit_copy_assignment;
11017
11018 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11019 return oc_method;
11020 }
11021
11022 return oc_function;
11023 }();
11024
11025 return std::make_pair(Kind, Select);
11026}
11027
11028void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11029 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11030 // set.
11031 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11032 S.Diag(FoundDecl->getLocation(),
11033 diag::note_ovl_candidate_inherited_constructor)
11034 << Shadow->getNominatedBaseClass();
11035}
11036
11037} // end anonymous namespace
11038
11040 const FunctionDecl *FD) {
11041 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11042 bool AlwaysTrue;
11043 if (EnableIf->getCond()->isValueDependent() ||
11044 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11045 return false;
11046 if (!AlwaysTrue)
11047 return false;
11048 }
11049 return true;
11050}
11051
11052/// Returns true if we can take the address of the function.
11053///
11054/// \param Complain - If true, we'll emit a diagnostic
11055/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11056/// we in overload resolution?
11057/// \param Loc - The location of the statement we're complaining about. Ignored
11058/// if we're not complaining, or if we're in overload resolution.
11060 bool Complain,
11061 bool InOverloadResolution,
11062 SourceLocation Loc) {
11063 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11064 if (Complain) {
11065 if (InOverloadResolution)
11066 S.Diag(FD->getBeginLoc(),
11067 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11068 else
11069 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11070 }
11071 return false;
11072 }
11073
11074 if (FD->getTrailingRequiresClause()) {
11075 ConstraintSatisfaction Satisfaction;
11076 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11077 return false;
11078 if (!Satisfaction.IsSatisfied) {
11079 if (Complain) {
11080 if (InOverloadResolution) {
11081 SmallString<128> TemplateArgString;
11082 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11083 TemplateArgString += " ";
11084 TemplateArgString += S.getTemplateArgumentBindingsText(
11085 FunTmpl->getTemplateParameters(),
11087 }
11088
11089 S.Diag(FD->getBeginLoc(),
11090 diag::note_ovl_candidate_unsatisfied_constraints)
11091 << TemplateArgString;
11092 } else
11093 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11094 << FD;
11095 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11096 }
11097 return false;
11098 }
11099 }
11100
11101 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11102 return P->hasAttr<PassObjectSizeAttr>();
11103 });
11104 if (I == FD->param_end())
11105 return true;
11106
11107 if (Complain) {
11108 // Add one to ParamNo because it's user-facing
11109 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11110 if (InOverloadResolution)
11111 S.Diag(FD->getLocation(),
11112 diag::note_ovl_candidate_has_pass_object_size_params)
11113 << ParamNo;
11114 else
11115 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11116 << FD << ParamNo;
11117 }
11118 return false;
11119}
11120
11122 const FunctionDecl *FD) {
11123 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11124 /*InOverloadResolution=*/true,
11125 /*Loc=*/SourceLocation());
11126}
11127
11129 bool Complain,
11130 SourceLocation Loc) {
11131 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11132 /*InOverloadResolution=*/false,
11133 Loc);
11134}
11135
11136// Don't print candidates other than the one that matches the calling
11137// convention of the call operator, since that is guaranteed to exist.
11139 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11140
11141 if (!ConvD)
11142 return false;
11143 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11144 if (!RD->isLambda())
11145 return false;
11146
11147 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11148 CallingConv CallOpCC =
11149 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11150 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11151 CallingConv ConvToCC =
11152 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11153
11154 return ConvToCC != CallOpCC;
11155}
11156
11157// Notes the location of an overload candidate.
11159 OverloadCandidateRewriteKind RewriteKind,
11160 QualType DestType, bool TakingAddress) {
11161 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11162 return;
11163 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11164 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11165 return;
11166 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11167 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11168 return;
11170 return;
11171
11172 std::string FnDesc;
11173 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11174 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11175 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11176 << (unsigned)KSPair.first << (unsigned)KSPair.second
11177 << Fn << FnDesc;
11178
11179 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11180 Diag(Fn->getLocation(), PD);
11181 MaybeEmitInheritedConstructorNote(*this, Found);
11182}
11183
11184static void
11186 // Perhaps the ambiguity was caused by two atomic constraints that are
11187 // 'identical' but not equivalent:
11188 //
11189 // void foo() requires (sizeof(T) > 4) { } // #1
11190 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11191 //
11192 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11193 // #2 to subsume #1, but these constraint are not considered equivalent
11194 // according to the subsumption rules because they are not the same
11195 // source-level construct. This behavior is quite confusing and we should try
11196 // to help the user figure out what happened.
11197
11198 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11199 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11200 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11201 if (!I->Function)
11202 continue;
11204 if (auto *Template = I->Function->getPrimaryTemplate())
11205 Template->getAssociatedConstraints(AC);
11206 else
11207 I->Function->getAssociatedConstraints(AC);
11208 if (AC.empty())
11209 continue;
11210 if (FirstCand == nullptr) {
11211 FirstCand = I->Function;
11212 FirstAC = AC;
11213 } else if (SecondCand == nullptr) {
11214 SecondCand = I->Function;
11215 SecondAC = AC;
11216 } else {
11217 // We have more than one pair of constrained functions - this check is
11218 // expensive and we'd rather not try to diagnose it.
11219 return;
11220 }
11221 }
11222 if (!SecondCand)
11223 return;
11224 // The diagnostic can only happen if there are associated constraints on
11225 // both sides (there needs to be some identical atomic constraint).
11226 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11227 SecondCand, SecondAC))
11228 // Just show the user one diagnostic, they'll probably figure it out
11229 // from here.
11230 return;
11231}
11232
11233// Notes the location of all overload candidates designated through
11234// OverloadedExpr
11235void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11236 bool TakingAddress) {
11237 assert(OverloadedExpr->getType() == Context.OverloadTy);
11238
11239 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11240 OverloadExpr *OvlExpr = Ovl.Expression;
11241
11242 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11243 IEnd = OvlExpr->decls_end();
11244 I != IEnd; ++I) {
11245 if (FunctionTemplateDecl *FunTmpl =
11246 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11247 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11248 TakingAddress);
11249 } else if (FunctionDecl *Fun
11250 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11251 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11252 }
11253 }
11254}
11255
11256/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11257/// "lead" diagnostic; it will be given two arguments, the source and
11258/// target types of the conversion.
11260 Sema &S,
11261 SourceLocation CaretLoc,
11262 const PartialDiagnostic &PDiag) const {
11263 S.Diag(CaretLoc, PDiag)
11264 << Ambiguous.getFromType() << Ambiguous.getToType();
11265 unsigned CandsShown = 0;
11267 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11268 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11269 break;
11270 ++CandsShown;
11271 S.NoteOverloadCandidate(I->first, I->second);
11272 }
11273 S.Diags.overloadCandidatesShown(CandsShown);
11274 if (I != E)
11275 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11276}
11277
11279 unsigned I, bool TakingCandidateAddress) {
11280 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11281 assert(Conv.isBad());
11282 assert(Cand->Function && "for now, candidate must be a function");
11283 FunctionDecl *Fn = Cand->Function;
11284
11285 // There's a conversion slot for the object argument if this is a
11286 // non-constructor method. Note that 'I' corresponds the
11287 // conversion-slot index.
11288 bool isObjectArgument = false;
11289 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11290 if (I == 0)
11291 isObjectArgument = true;
11292 else
11293 I--;
11294 }
11295
11296 std::string FnDesc;
11297 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11298 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11299 FnDesc);
11300
11301 Expr *FromExpr = Conv.Bad.FromExpr;
11302 QualType FromTy = Conv.Bad.getFromType();
11303 QualType ToTy = Conv.Bad.getToType();
11304 SourceRange ToParamRange =
11305 !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
11306
11307 if (FromTy == S.Context.OverloadTy) {
11308 assert(FromExpr && "overload set argument came from implicit argument?");
11309 Expr *E = FromExpr->IgnoreParens();
11310 if (isa<UnaryOperator>(E))
11311 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11312 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11313
11314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11315 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11316 << ToParamRange << ToTy << Name << I + 1;
11317 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11318 return;
11319 }
11320
11321 // Do some hand-waving analysis to see if the non-viability is due
11322 // to a qualifier mismatch.
11323 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11324 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11325 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11326 CToTy = RT->getPointeeType();
11327 else {
11328 // TODO: detect and diagnose the full richness of const mismatches.
11329 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11330 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11331 CFromTy = FromPT->getPointeeType();
11332 CToTy = ToPT->getPointeeType();
11333 }
11334 }
11335
11336 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11337 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11338 Qualifiers FromQs = CFromTy.getQualifiers();
11339 Qualifiers ToQs = CToTy.getQualifiers();
11340
11341 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11342 if (isObjectArgument)
11343 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11344 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11345 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11346 else
11347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11348 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11349 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11350 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11351 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11352 return;
11353 }
11354
11355 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11356 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11357 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11358 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11359 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11360 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11361 return;
11362 }
11363
11364 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11366 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11367 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11368 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11369 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11370 return;
11371 }
11372
11373 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11374 assert(CVR && "expected qualifiers mismatch");
11375
11376 if (isObjectArgument) {
11377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11378 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11379 << FromTy << (CVR - 1);
11380 } else {
11381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11382 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11383 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11384 }
11385 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11386 return;
11387 }
11388
11391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11392 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11393 << (unsigned)isObjectArgument << I + 1
11395 << ToParamRange;
11396 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11397 return;
11398 }
11399
11400 // Special diagnostic for failure to convert an initializer list, since
11401 // telling the user that it has type void is not useful.
11402 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11403 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11404 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11405 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11408 ? 2
11409 : 0);
11410 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11411 return;
11412 }
11413
11414 // Diagnose references or pointers to incomplete types differently,
11415 // since it's far from impossible that the incompleteness triggered
11416 // the failure.
11417 QualType TempFromTy = FromTy.getNonReferenceType();
11418 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11419 TempFromTy = PTy->getPointeeType();
11420 if (TempFromTy->isIncompleteType()) {
11421 // Emit the generic diagnostic and, optionally, add the hints to it.
11422 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11423 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11424 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11425 << (unsigned)(Cand->Fix.Kind);
11426
11427 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11428 return;
11429 }
11430
11431 // Diagnose base -> derived pointer conversions.
11432 unsigned BaseToDerivedConversion = 0;
11433 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11434 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11435 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11436 FromPtrTy->getPointeeType()) &&
11437 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11438 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11439 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11440 FromPtrTy->getPointeeType()))
11441 BaseToDerivedConversion = 1;
11442 }
11443 } else if (const ObjCObjectPointerType *FromPtrTy
11444 = FromTy->getAs<ObjCObjectPointerType>()) {
11445 if (const ObjCObjectPointerType *ToPtrTy
11446 = ToTy->getAs<ObjCObjectPointerType>())
11447 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11448 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11449 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11450 FromPtrTy->getPointeeType()) &&
11451 FromIface->isSuperClassOf(ToIface))
11452 BaseToDerivedConversion = 2;
11453 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11454 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11455 !FromTy->isIncompleteType() &&
11456 !ToRefTy->getPointeeType()->isIncompleteType() &&
11457 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11458 BaseToDerivedConversion = 3;
11459 }
11460 }
11461
11462 if (BaseToDerivedConversion) {
11463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11464 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11465 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11466 << I + 1;
11467 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11468 return;
11469 }
11470
11471 if (isa<ObjCObjectPointerType>(CFromTy) &&
11472 isa<PointerType>(CToTy)) {
11473 Qualifiers FromQs = CFromTy.getQualifiers();
11474 Qualifiers ToQs = CToTy.getQualifiers();
11475 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11477 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11478 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11479 << I + 1;
11480 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11481 return;
11482 }
11483 }
11484
11485 if (TakingCandidateAddress &&
11487 return;
11488
11489 // Emit the generic diagnostic and, optionally, add the hints to it.
11490 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11491 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11492 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11493 << (unsigned)(Cand->Fix.Kind);
11494
11495 // Check that location of Fn is not in system header.
11496 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11497 // If we can fix the conversion, suggest the FixIts.
11498 for (const FixItHint &HI : Cand->Fix.Hints)
11499 FDiag << HI;
11500 }
11501
11502 S.Diag(Fn->getLocation(), FDiag);
11503
11504 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11505}
11506
11507/// Additional arity mismatch diagnosis specific to a function overload
11508/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11509/// over a candidate in any candidate set.
11511 unsigned NumArgs) {
11512 FunctionDecl *Fn = Cand->Function;
11513 unsigned MinParams = Fn->getMinRequiredArguments();
11514
11515 // With invalid overloaded operators, it's possible that we think we
11516 // have an arity mismatch when in fact it looks like we have the
11517 // right number of arguments, because only overloaded operators have
11518 // the weird behavior of overloading member and non-member functions.
11519 // Just don't report anything.
11520 if (Fn->isInvalidDecl() &&
11522 return true;
11523
11524 if (NumArgs < MinParams) {
11525 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11527 Cand->DeductionFailure.getResult() ==
11529 } else {
11530 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11532 Cand->DeductionFailure.getResult() ==
11534 }
11535
11536 return false;
11537}
11538
11539/// General arity mismatch diagnosis over a candidate in a candidate set.
11540static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11541 unsigned NumFormalArgs) {
11542 assert(isa<FunctionDecl>(D) &&
11543 "The templated declaration should at least be a function"
11544 " when diagnosing bad template argument deduction due to too many"
11545 " or too few arguments");
11546
11547 FunctionDecl *Fn = cast<FunctionDecl>(D);
11548
11549 // TODO: treat calls to a missing default constructor as a special case
11550 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11551 unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11552
11553 // at least / at most / exactly
11554 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11555 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11556 unsigned mode, modeCount;
11557 if (NumFormalArgs < MinParams) {
11558 if (MinParams != ParamCount || FnTy->isVariadic() ||
11559 FnTy->isTemplateVariadic())
11560 mode = 0; // "at least"
11561 else
11562 mode = 2; // "exactly"
11563 modeCount = MinParams;
11564 } else {
11565 if (MinParams != ParamCount)
11566 mode = 1; // "at most"
11567 else
11568 mode = 2; // "exactly"
11569 modeCount = ParamCount;
11570 }
11571
11572 std::string Description;
11573 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11574 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11575
11576 if (modeCount == 1 &&
11577 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11578 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11579 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11580 << Description << mode
11581 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11582 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11583 else
11584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11585 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11586 << Description << mode << modeCount << NumFormalArgs
11587 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11588
11589 MaybeEmitInheritedConstructorNote(S, Found);
11590}
11591
11592/// Arity mismatch diagnosis specific to a function overload candidate.
11594 unsigned NumFormalArgs) {
11595 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11596 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11597}
11598
11600 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11601 return TD;
11602 llvm_unreachable("Unsupported: Getting the described template declaration"
11603 " for bad deduction diagnosis");
11604}
11605
11606/// Diagnose a failed template-argument deduction.
11607static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11608 DeductionFailureInfo &DeductionFailure,
11609 unsigned NumArgs,
11610 bool TakingCandidateAddress) {
11611 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11612 NamedDecl *ParamD;
11613 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11614 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11615 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11616 switch (DeductionFailure.getResult()) {
11618 llvm_unreachable(
11619 "TemplateDeductionResult::Success while diagnosing bad deduction");
11621 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11622 "while diagnosing bad deduction");
11625 return;
11626
11628 assert(ParamD && "no parameter found for incomplete deduction result");
11629 S.Diag(Templated->getLocation(),
11630 diag::note_ovl_candidate_incomplete_deduction)
11631 << ParamD->getDeclName();
11632 MaybeEmitInheritedConstructorNote(S, Found);
11633 return;
11634 }
11635
11637 assert(ParamD && "no parameter found for incomplete deduction result");
11638 S.Diag(Templated->getLocation(),
11639 diag::note_ovl_candidate_incomplete_deduction_pack)
11640 << ParamD->getDeclName()
11641 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11642 << *DeductionFailure.getFirstArg();
11643 MaybeEmitInheritedConstructorNote(S, Found);
11644 return;
11645 }
11646
11648 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11649 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11650
11651 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11652
11653 // Param will have been canonicalized, but it should just be a
11654 // qualified version of ParamD, so move the qualifiers to that.
11656 Qs.strip(Param);
11657 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11658 assert(S.Context.hasSameType(Param, NonCanonParam));
11659
11660 // Arg has also been canonicalized, but there's nothing we can do
11661 // about that. It also doesn't matter as much, because it won't
11662 // have any template parameters in it (because deduction isn't
11663 // done on dependent types).
11664 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11665
11666 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11667 << ParamD->getDeclName() << Arg << NonCanonParam;
11668 MaybeEmitInheritedConstructorNote(S, Found);
11669 return;
11670 }
11671
11673 assert(ParamD && "no parameter found for inconsistent deduction result");
11674 int which = 0;
11675 if (isa<TemplateTypeParmDecl>(ParamD))
11676 which = 0;
11677 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11678 // Deduction might have failed because we deduced arguments of two
11679 // different types for a non-type template parameter.
11680 // FIXME: Use a different TDK value for this.
11681 QualType T1 =
11682 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11683 QualType T2 =
11684 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11685 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11686 S.Diag(Templated->getLocation(),
11687 diag::note_ovl_candidate_inconsistent_deduction_types)
11688 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11689 << *DeductionFailure.getSecondArg() << T2;
11690 MaybeEmitInheritedConstructorNote(S, Found);
11691 return;
11692 }
11693
11694 which = 1;
11695 } else {
11696 which = 2;
11697 }
11698
11699 // Tweak the diagnostic if the problem is that we deduced packs of
11700 // different arities. We'll print the actual packs anyway in case that
11701 // includes additional useful information.
11702 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11703 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11704 DeductionFailure.getFirstArg()->pack_size() !=
11705 DeductionFailure.getSecondArg()->pack_size()) {
11706 which = 3;
11707 }
11708
11709 S.Diag(Templated->getLocation(),
11710 diag::note_ovl_candidate_inconsistent_deduction)
11711 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11712 << *DeductionFailure.getSecondArg();
11713 MaybeEmitInheritedConstructorNote(S, Found);
11714 return;
11715 }
11716
11718 assert(ParamD && "no parameter found for invalid explicit arguments");
11719 if (ParamD->getDeclName())
11720 S.Diag(Templated->getLocation(),
11721 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11722 << ParamD->getDeclName();
11723 else {
11724 int index = 0;
11725 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11726 index = TTP->getIndex();
11727 else if (NonTypeTemplateParmDecl *NTTP
11728 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11729 index = NTTP->getIndex();
11730 else
11731 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11732 S.Diag(Templated->getLocation(),
11733 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11734 << (index + 1);
11735 }
11736 MaybeEmitInheritedConstructorNote(S, Found);
11737 return;
11738
11740 // Format the template argument list into the argument string.
11741 SmallString<128> TemplateArgString;
11742 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11743 TemplateArgString = " ";
11744 TemplateArgString += S.getTemplateArgumentBindingsText(
11745 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11746 if (TemplateArgString.size() == 1)
11747 TemplateArgString.clear();
11748 S.Diag(Templated->getLocation(),
11749 diag::note_ovl_candidate_unsatisfied_constraints)
11750 << TemplateArgString;
11751
11753 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11754 return;
11755 }
11758 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11759 return;
11760
11762 S.Diag(Templated->getLocation(),
11763 diag::note_ovl_candidate_instantiation_depth);
11764 MaybeEmitInheritedConstructorNote(S, Found);
11765 return;
11766
11768 // Format the template argument list into the argument string.
11769 SmallString<128> TemplateArgString;
11770 if (TemplateArgumentList *Args =
11771 DeductionFailure.getTemplateArgumentList()) {
11772 TemplateArgString = " ";
11773 TemplateArgString += S.getTemplateArgumentBindingsText(
11774 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11775 if (TemplateArgString.size() == 1)
11776 TemplateArgString.clear();
11777 }
11778
11779 // If this candidate was disabled by enable_if, say so.
11780 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11781 if (PDiag && PDiag->second.getDiagID() ==
11782 diag::err_typename_nested_not_found_enable_if) {
11783 // FIXME: Use the source range of the condition, and the fully-qualified
11784 // name of the enable_if template. These are both present in PDiag.
11785 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11786 << "'enable_if'" << TemplateArgString;
11787 return;
11788 }
11789
11790 // We found a specific requirement that disabled the enable_if.
11791 if (PDiag && PDiag->second.getDiagID() ==
11792 diag::err_typename_nested_not_found_requirement) {
11793 S.Diag(Templated->getLocation(),
11794 diag::note_ovl_candidate_disabled_by_requirement)
11795 << PDiag->second.getStringArg(0) << TemplateArgString;
11796 return;
11797 }
11798
11799 // Format the SFINAE diagnostic into the argument string.
11800 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11801 // formatted message in another diagnostic.
11802 SmallString<128> SFINAEArgString;
11803 SourceRange R;
11804 if (PDiag) {
11805 SFINAEArgString = ": ";
11806 R = SourceRange(PDiag->first, PDiag->first);
11807 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11808 }
11809
11810 S.Diag(Templated->getLocation(),
11811 diag::note_ovl_candidate_substitution_failure)
11812 << TemplateArgString << SFINAEArgString << R;
11813 MaybeEmitInheritedConstructorNote(S, Found);
11814 return;
11815 }
11816
11819 // Format the template argument list into the argument string.
11820 SmallString<128> TemplateArgString;
11821 if (TemplateArgumentList *Args =
11822 DeductionFailure.getTemplateArgumentList()) {
11823 TemplateArgString = " ";
11824 TemplateArgString += S.getTemplateArgumentBindingsText(
11825 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11826 if (TemplateArgString.size() == 1)
11827 TemplateArgString.clear();
11828 }
11829
11830 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11831 << (*DeductionFailure.getCallArgIndex() + 1)
11832 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11833 << TemplateArgString
11834 << (DeductionFailure.getResult() ==
11836 break;
11837 }
11838
11840 // FIXME: Provide a source location to indicate what we couldn't match.
11841 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11842 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11843 if (FirstTA.getKind() == TemplateArgument::Template &&
11844 SecondTA.getKind() == TemplateArgument::Template) {
11845 TemplateName FirstTN = FirstTA.getAsTemplate();
11846 TemplateName SecondTN = SecondTA.getAsTemplate();
11847 if (FirstTN.getKind() == TemplateName::Template &&
11848 SecondTN.getKind() == TemplateName::Template) {
11849 if (FirstTN.getAsTemplateDecl()->getName() ==
11850 SecondTN.getAsTemplateDecl()->getName()) {
11851 // FIXME: This fixes a bad diagnostic where both templates are named
11852 // the same. This particular case is a bit difficult since:
11853 // 1) It is passed as a string to the diagnostic printer.
11854 // 2) The diagnostic printer only attempts to find a better
11855 // name for types, not decls.
11856 // Ideally, this should folded into the diagnostic printer.
11857 S.Diag(Templated->getLocation(),
11858 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11859 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11860 return;
11861 }
11862 }
11863 }
11864
11865 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11866 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11867 return;
11868
11869 // FIXME: For generic lambda parameters, check if the function is a lambda
11870 // call operator, and if so, emit a prettier and more informative
11871 // diagnostic that mentions 'auto' and lambda in addition to
11872 // (or instead of?) the canonical template type parameters.
11873 S.Diag(Templated->getLocation(),
11874 diag::note_ovl_candidate_non_deduced_mismatch)
11875 << FirstTA << SecondTA;
11876 return;
11877 }
11878 // TODO: diagnose these individually, then kill off
11879 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11881 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11882 MaybeEmitInheritedConstructorNote(S, Found);
11883 return;
11885 S.Diag(Templated->getLocation(),
11886 diag::note_cuda_ovl_candidate_target_mismatch);
11887 return;
11888 }
11889}
11890
11891/// Diagnose a failed template-argument deduction, for function calls.
11893 unsigned NumArgs,
11894 bool TakingCandidateAddress) {
11898 if (CheckArityMismatch(S, Cand, NumArgs))
11899 return;
11900 }
11901 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11902 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11903}
11904
11905/// CUDA: diagnose an invalid call across targets.
11907 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11908 FunctionDecl *Callee = Cand->Function;
11909
11910 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11911 CalleeTarget = S.IdentifyCUDATarget(Callee);
11912
11913 std::string FnDesc;
11914 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11915 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11916 Cand->getRewriteKind(), FnDesc);
11917
11918 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11919 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11920 << FnDesc /* Ignored */
11921 << CalleeTarget << CallerTarget;
11922
11923 // This could be an implicit constructor for which we could not infer the
11924 // target due to a collsion. Diagnose that case.
11925 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11926 if (Meth != nullptr && Meth->isImplicit()) {
11927 CXXRecordDecl *ParentClass = Meth->getParent();
11929
11930 switch (FnKindPair.first) {
11931 default:
11932 return;
11933 case oc_implicit_default_constructor:
11935 break;
11936 case oc_implicit_copy_constructor:
11938 break;
11939 case oc_implicit_move_constructor:
11941 break;
11942 case oc_implicit_copy_assignment:
11944 break;
11945 case oc_implicit_move_assignment:
11947 break;
11948 };
11949
11950 bool ConstRHS = false;
11951 if (Meth->getNumParams()) {
11952 if (const ReferenceType *RT =
11953 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11954 ConstRHS = RT->getPointeeType().isConstQualified();
11955 }
11956 }
11957
11958 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11959 /* ConstRHS */ ConstRHS,
11960 /* Diagnose */ true);
11961 }
11962}
11963
11965 FunctionDecl *Callee = Cand->Function;
11966 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11967
11968 S.Diag(Callee->getLocation(),
11969 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11970 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11971}
11972
11975 assert(ES.isExplicit() && "not an explicit candidate");
11976
11977 unsigned Kind;
11978 switch (Cand->Function->getDeclKind()) {
11979 case Decl::Kind::CXXConstructor:
11980 Kind = 0;
11981 break;
11982 case Decl::Kind::CXXConversion:
11983 Kind = 1;
11984 break;
11985 case Decl::Kind::CXXDeductionGuide:
11986 Kind = Cand->Function->isImplicit() ? 0 : 2;
11987 break;
11988 default:
11989 llvm_unreachable("invalid Decl");
11990 }
11991
11992 // Note the location of the first (in-class) declaration; a redeclaration
11993 // (particularly an out-of-class definition) will typically lack the
11994 // 'explicit' specifier.
11995 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11997 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11998 First = Pattern->getFirstDecl();
11999
12000 S.Diag(First->getLocation(),
12001 diag::note_ovl_candidate_explicit)
12002 << Kind << (ES.getExpr() ? 1 : 0)
12003 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12004}
12005
12006/// Generates a 'note' diagnostic for an overload candidate. We've
12007/// already generated a primary error at the call site.
12008///
12009/// It really does need to be a single diagnostic with its caret
12010/// pointed at the candidate declaration. Yes, this creates some
12011/// major challenges of technical writing. Yes, this makes pointing
12012/// out problems with specific arguments quite awkward. It's still
12013/// better than generating twenty screens of text for every failed
12014/// overload.
12015///
12016/// It would be great to be able to express per-candidate problems
12017/// more richly for those diagnostic clients that cared, but we'd
12018/// still have to be just as careful with the default diagnostics.
12019/// \param CtorDestAS Addr space of object being constructed (for ctor
12020/// candidates only).
12022 unsigned NumArgs,
12023 bool TakingCandidateAddress,
12024 LangAS CtorDestAS = LangAS::Default) {
12025 FunctionDecl *Fn = Cand->Function;
12027 return;
12028
12029 // There is no physical candidate declaration to point to for OpenCL builtins.
12030 // Except for failed conversions, the notes are identical for each candidate,
12031 // so do not generate such notes.
12032 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12034 return;
12035
12036 // Note deleted candidates, but only if they're viable.
12037 if (Cand->Viable) {
12038 if (Fn->isDeleted()) {
12039 std::string FnDesc;
12040 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12041 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12042 Cand->getRewriteKind(), FnDesc);
12043
12044 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12045 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12046 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12047 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12048 return;
12049 }
12050
12051 // We don't really have anything else to say about viable candidates.
12052 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12053 return;
12054 }
12055
12056 switch (Cand->FailureKind) {
12059 return DiagnoseArityMismatch(S, Cand, NumArgs);
12060
12062 return DiagnoseBadDeduction(S, Cand, NumArgs,
12063 TakingCandidateAddress);
12064
12066 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12067 << (Fn->getPrimaryTemplate() ? 1 : 0);
12068 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12069 return;
12070 }
12071
12073 Qualifiers QualsForPrinting;
12074 QualsForPrinting.setAddressSpace(CtorDestAS);
12075 S.Diag(Fn->getLocation(),
12076 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12077 << QualsForPrinting;
12078 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12079 return;
12080 }
12081
12085 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12086
12088 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12089 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12090 if (Cand->Conversions[I].isBad())
12091 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12092
12093 // FIXME: this currently happens when we're called from SemaInit
12094 // when user-conversion overload fails. Figure out how to handle
12095 // those conditions and diagnose them well.
12096 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12097 }
12098
12100 return DiagnoseBadTarget(S, Cand);
12101
12102 case ovl_fail_enable_if:
12103 return DiagnoseFailedEnableIfAttr(S, Cand);
12104
12105 case ovl_fail_explicit:
12106 return DiagnoseFailedExplicitSpec(S, Cand);
12107
12109 // It's generally not interesting to note copy/move constructors here.
12110 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12111 return;
12112 S.Diag(Fn->getLocation(),
12113 diag::note_ovl_candidate_inherited_constructor_slice)
12114 << (Fn->getPrimaryTemplate() ? 1 : 0)
12116 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12117 return;
12118
12120 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
12121 (void)Available;
12122 assert(!Available);
12123 break;
12124 }
12126 // Do nothing, these should simply be ignored.
12127 break;
12128
12130 std::string FnDesc;
12131 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12132 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12133 Cand->getRewriteKind(), FnDesc);
12134
12135 S.Diag(Fn->getLocation(),
12136 diag::note_ovl_candidate_constraints_not_satisfied)
12137 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12138 << FnDesc /* Ignored */;
12139 ConstraintSatisfaction Satisfaction;
12140 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12141 break;
12142 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12143 }
12144 }
12145}
12146
12149 return;
12150
12151 // Desugar the type of the surrogate down to a function type,
12152 // retaining as many typedefs as possible while still showing
12153 // the function type (and, therefore, its parameter types).
12154 QualType FnType = Cand->Surrogate->getConversionType();
12155 bool isLValueReference = false;
12156 bool isRValueReference = false;
12157 bool isPointer = false;
12158 if (const LValueReferenceType *FnTypeRef =
12159 FnType->getAs<LValueReferenceType>()) {
12160 FnType = FnTypeRef->getPointeeType();
12161 isLValueReference = true;
12162 } else if (const RValueReferenceType *FnTypeRef =
12163 FnType->getAs<RValueReferenceType>()) {
12164 FnType = FnTypeRef->getPointeeType();
12165 isRValueReference = true;
12166 }
12167 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12168 FnType = FnTypePtr->getPointeeType();
12169 isPointer = true;
12170 }
12171 // Desugar down to a function type.
12172 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12173 // Reconstruct the pointer/reference as appropriate.
12174 if (isPointer) FnType = S.Context.getPointerType(FnType);
12175 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12176 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12177
12178 if (!Cand->Viable &&
12180 S.Diag(Cand->Surrogate->getLocation(),
12181 diag::note_ovl_surrogate_constraints_not_satisfied)
12182 << Cand->Surrogate;
12183 ConstraintSatisfaction Satisfaction;
12184 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12185 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12186 } else {
12187 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12188 << FnType;
12189 }
12190}
12191
12192static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12193 SourceLocation OpLoc,
12194 OverloadCandidate *Cand) {
12195 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12196 std::string TypeStr("operator");
12197 TypeStr += Opc;
12198 TypeStr += "(";
12199 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12200 if (Cand->Conversions.size() == 1) {
12201 TypeStr += ")";
12202 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12203 } else {
12204 TypeStr += ", ";
12205 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12206 TypeStr += ")";
12207 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12208 }
12209}
12210
12212 OverloadCandidate *Cand) {
12213 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12214 if (ICS.isBad()) break; // all meaningless after first invalid
12215 if (!ICS.isAmbiguous()) continue;
12216
12218 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12219 }
12220}
12221
12223 if (Cand->Function)
12224 return Cand->Function->getLocation();
12225 if (Cand->IsSurrogate)
12226 return Cand->Surrogate->getLocation();
12227 return SourceLocation();
12228}
12229
12230static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12231 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12235 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12236
12240 return 1;
12241
12244 return 2;
12245
12253 return 3;
12254
12256 return 4;
12257
12259 return 5;
12260
12263 return 6;
12264 }
12265 llvm_unreachable("Unhandled deduction result");
12266}
12267
12268namespace {
12269
12270struct CompareOverloadCandidatesForDisplay {
12271 Sema &S;
12272 SourceLocation Loc;
12273 size_t NumArgs;
12275
12276 CompareOverloadCandidatesForDisplay(
12277 Sema &S, SourceLocation Loc, size_t NArgs,
12279 : S(S), NumArgs(NArgs), CSK(CSK) {}
12280
12281 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12282 // If there are too many or too few arguments, that's the high-order bit we
12283 // want to sort by, even if the immediate failure kind was something else.
12284 if (C->FailureKind == ovl_fail_too_many_arguments ||
12285 C->FailureKind == ovl_fail_too_few_arguments)
12286 return static_cast<OverloadFailureKind>(C->FailureKind);
12287
12288 if (C->Function) {
12289 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12291 if (NumArgs < C->Function->getMinRequiredArguments())
12293 }
12294
12295 return static_cast<OverloadFailureKind>(C->FailureKind);
12296 }
12297
12298 bool operator()(const OverloadCandidate *L,
12299 const OverloadCandidate *R) {
12300 // Fast-path this check.
12301 if (L == R) return false;
12302
12303 // Order first by viability.
12304 if (L->Viable) {
12305 if (!R->Viable) return true;
12306
12307 if (int Ord = CompareConversions(*L, *R))
12308 return Ord < 0;
12309 // Use other tie breakers.
12310 } else if (R->Viable)
12311 return false;
12312
12313 assert(L->Viable == R->Viable);
12314
12315 // Criteria by which we can sort non-viable candidates:
12316 if (!L->Viable) {
12317 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12318 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12319
12320 // 1. Arity mismatches come after other candidates.
12321 if (LFailureKind == ovl_fail_too_many_arguments ||
12322 LFailureKind == ovl_fail_too_few_arguments) {
12323 if (RFailureKind == ovl_fail_too_many_arguments ||
12324 RFailureKind == ovl_fail_too_few_arguments) {
12325 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12326 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12327 if (LDist == RDist) {
12328 if (LFailureKind == RFailureKind)
12329 // Sort non-surrogates before surrogates.
12330 return !L->IsSurrogate && R->IsSurrogate;
12331 // Sort candidates requiring fewer parameters than there were
12332 // arguments given after candidates requiring more parameters
12333 // than there were arguments given.
12334 return LFailureKind == ovl_fail_too_many_arguments;
12335 }
12336 return LDist < RDist;
12337 }
12338 return false;
12339 }
12340 if (RFailureKind == ovl_fail_too_many_arguments ||
12341 RFailureKind == ovl_fail_too_few_arguments)
12342 return true;
12343
12344 // 2. Bad conversions come first and are ordered by the number
12345 // of bad conversions and quality of good conversions.
12346 if (LFailureKind == ovl_fail_bad_conversion) {
12347 if (RFailureKind != ovl_fail_bad_conversion)
12348 return true;
12349
12350 // The conversion that can be fixed with a smaller number of changes,
12351 // comes first.
12352 unsigned numLFixes = L->Fix.NumConversionsFixed;
12353 unsigned numRFixes = R->Fix.NumConversionsFixed;
12354 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12355 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12356 if (numLFixes != numRFixes) {
12357 return numLFixes < numRFixes;
12358 }
12359
12360 // If there's any ordering between the defined conversions...
12361 if (int Ord = CompareConversions(*L, *R))
12362 return Ord < 0;
12363 } else if (RFailureKind == ovl_fail_bad_conversion)
12364 return false;
12365
12366 if (LFailureKind == ovl_fail_bad_deduction) {
12367 if (RFailureKind != ovl_fail_bad_deduction)
12368 return true;
12369
12371 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12372 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12373 if (LRank != RRank)
12374 return LRank < RRank;
12375 }
12376 } else if (RFailureKind == ovl_fail_bad_deduction)
12377 return false;
12378
12379 // TODO: others?
12380 }
12381
12382 // Sort everything else by location.
12385
12386 // Put candidates without locations (e.g. builtins) at the end.
12387 if (LLoc.isValid() && RLoc.isValid())
12388 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12389 if (LLoc.isValid() && !RLoc.isValid())
12390 return true;
12391 if (RLoc.isValid() && !LLoc.isValid())
12392 return false;
12393 assert(!LLoc.isValid() && !RLoc.isValid());
12394 // For builtins and other functions without locations, fallback to the order
12395 // in which they were added into the candidate set.
12396 return L < R;
12397 }
12398
12399private:
12400 struct ConversionSignals {
12401 unsigned KindRank = 0;
12403
12404 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12405 ConversionSignals Sig;
12406 Sig.KindRank = Seq.getKindRank();
12407 if (Seq.isStandard())
12408 Sig.Rank = Seq.Standard.getRank();
12409 else if (Seq.isUserDefined())
12410 Sig.Rank = Seq.UserDefined.After.getRank();
12411 // We intend StaticObjectArgumentConversion to compare the same as
12412 // StandardConversion with ICR_ExactMatch rank.
12413 return Sig;
12414 }
12415
12416 static ConversionSignals ForObjectArgument() {
12417 // We intend StaticObjectArgumentConversion to compare the same as
12418 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12419 return {};
12420 }
12421 };
12422
12423 // Returns -1 if conversions in L are considered better.
12424 // 0 if they are considered indistinguishable.
12425 // 1 if conversions in R are better.
12426 int CompareConversions(const OverloadCandidate &L,
12427 const OverloadCandidate &R) {
12428 // We cannot use `isBetterOverloadCandidate` because it is defined
12429 // according to the C++ standard and provides a partial order, but we need
12430 // a total order as this function is used in sort.
12431 assert(L.Conversions.size() == R.Conversions.size());
12432 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12433 auto LS = L.IgnoreObjectArgument && I == 0
12434 ? ConversionSignals::ForObjectArgument()
12435 : ConversionSignals::ForSequence(L.Conversions[I]);
12436 auto RS = R.IgnoreObjectArgument
12437 ? ConversionSignals::ForObjectArgument()
12438 : ConversionSignals::ForSequence(R.Conversions[I]);
12439 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12440 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12441 ? -1
12442 : 1;
12443 }
12444 // FIXME: find a way to compare templates for being more or less
12445 // specialized that provides a strict weak ordering.
12446 return 0;
12447 }
12448};
12449}
12450
12451/// CompleteNonViableCandidate - Normally, overload resolution only
12452/// computes up to the first bad conversion. Produces the FixIt set if
12453/// possible.
12454static void
12456 ArrayRef<Expr *> Args,
12458 assert(!Cand->Viable);
12459
12460 // Don't do anything on failures other than bad conversion.
12462 return;
12463
12464 // We only want the FixIts if all the arguments can be corrected.
12465 bool Unfixable = false;
12466 // Use a implicit copy initialization to check conversion fixes.
12468
12469 // Attempt to fix the bad conversion.
12470 unsigned ConvCount = Cand->Conversions.size();
12471 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12472 ++ConvIdx) {
12473 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12474 if (Cand->Conversions[ConvIdx].isInitialized() &&
12475 Cand->Conversions[ConvIdx].isBad()) {
12476 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12477 break;
12478 }
12479 }
12480
12481 // FIXME: this should probably be preserved from the overload
12482 // operation somehow.
12483 bool SuppressUserConversions = false;
12484
12485 unsigned ConvIdx = 0;
12486 unsigned ArgIdx = 0;
12487 ArrayRef<QualType> ParamTypes;
12488 bool Reversed = Cand->isReversed();
12489
12490 if (Cand->IsSurrogate) {
12491 QualType ConvType
12493 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12494 ConvType = ConvPtrType->getPointeeType();
12495 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12496 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12497 ConvIdx = 1;
12498 } else if (Cand->Function) {
12499 ParamTypes =
12500 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12501 if (isa<CXXMethodDecl>(Cand->Function) &&
12502 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12503 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12504 ConvIdx = 1;
12506 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12508 OO_Subscript)
12509 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12510 ArgIdx = 1;
12511 }
12512 } else {
12513 // Builtin operator.
12514 assert(ConvCount <= 3);
12515 ParamTypes = Cand->BuiltinParamTypes;
12516 }
12517
12518 // Fill in the rest of the conversions.
12519 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12520 ConvIdx != ConvCount;
12521 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12522 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12523 if (Cand->Conversions[ConvIdx].isInitialized()) {
12524 // We've already checked this conversion.
12525 } else if (ParamIdx < ParamTypes.size()) {
12526 if (ParamTypes[ParamIdx]->isDependentType())
12527 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12528 Args[ArgIdx]->getType());
12529 else {
12530 Cand->Conversions[ConvIdx] =
12531 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12532 SuppressUserConversions,
12533 /*InOverloadResolution=*/true,
12534 /*AllowObjCWritebackConversion=*/
12535 S.getLangOpts().ObjCAutoRefCount);
12536 // Store the FixIt in the candidate if it exists.
12537 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12538 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12539 }
12540 } else
12541 Cand->Conversions[ConvIdx].setEllipsis();
12542 }
12543}
12544
12547 SourceLocation OpLoc,
12548 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12549 // Sort the candidates by viability and position. Sorting directly would
12550 // be prohibitive, so we make a set of pointers and sort those.
12552 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12553 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12554 if (!Filter(*Cand))
12555 continue;
12556 switch (OCD) {
12557 case OCD_AllCandidates:
12558 if (!Cand->Viable) {
12559 if (!Cand->Function && !Cand->IsSurrogate) {
12560 // This a non-viable builtin candidate. We do not, in general,
12561 // want to list every possible builtin candidate.
12562 continue;
12563 }
12564 CompleteNonViableCandidate(S, Cand, Args, Kind);
12565 }
12566 break;
12567
12569 if (!Cand->Viable)
12570 continue;
12571 break;
12572
12574 if (!Cand->Best)
12575 continue;
12576 break;
12577 }
12578
12579 Cands.push_back(Cand);
12580 }
12581
12582 llvm::stable_sort(
12583 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12584
12585 return Cands;
12586}
12587
12589 SourceLocation OpLoc) {
12590 bool DeferHint = false;
12591 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12592 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12593 // host device candidates.
12594 auto WrongSidedCands =
12595 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12596 return (Cand.Viable == false &&
12597 Cand.FailureKind == ovl_fail_bad_target) ||
12598 (Cand.Function &&
12599 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12600 Cand.Function->template hasAttr<CUDADeviceAttr>());
12601 });
12602 DeferHint = !WrongSidedCands.empty();
12603 }
12604 return DeferHint;
12605}
12606
12607/// When overload resolution fails, prints diagnostic messages containing the
12608/// candidates in the candidate set.
12611 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12612 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12613
12614 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12615
12616 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12617
12618 // In WebAssembly we don't want to emit further diagnostics if a table is
12619 // passed as an argument to a function.
12620 bool NoteCands = true;
12621 for (const Expr *Arg : Args) {
12622 if (Arg->getType()->isWebAssemblyTableType())
12623 NoteCands = false;
12624 }
12625
12626 if (NoteCands)
12627 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12628
12629 if (OCD == OCD_AmbiguousCandidates)
12631}
12632
12635 StringRef Opc, SourceLocation OpLoc) {
12636 bool ReportedAmbiguousConversions = false;
12637
12638 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12639 unsigned CandsShown = 0;
12640 auto I = Cands.begin(), E = Cands.end();
12641 for (; I != E; ++I) {
12642 OverloadCandidate *Cand = *I;
12643
12644 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12645 ShowOverloads == Ovl_Best) {
12646 break;
12647 }
12648 ++CandsShown;
12649
12650 if (Cand->Function)
12651 NoteFunctionCandidate(S, Cand, Args.size(),
12652 /*TakingCandidateAddress=*/false, DestAS);
12653 else if (Cand->IsSurrogate)
12654 NoteSurrogateCandidate(S, Cand);
12655 else {
12656 assert(Cand->Viable &&
12657 "Non-viable built-in candidates are not added to Cands.");
12658 // Generally we only see ambiguities including viable builtin
12659 // operators if overload resolution got screwed up by an
12660 // ambiguous user-defined conversion.
12661 //
12662 // FIXME: It's quite possible for different conversions to see
12663 // different ambiguities, though.
12664 if (!ReportedAmbiguousConversions) {
12665 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12666 ReportedAmbiguousConversions = true;
12667 }
12668
12669 // If this is a viable builtin, print it.
12670 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12671 }
12672 }
12673
12674 // Inform S.Diags that we've shown an overload set with N elements. This may
12675 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12676 S.Diags.overloadCandidatesShown(CandsShown);
12677
12678 if (I != E)
12679 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12680 shouldDeferDiags(S, Args, OpLoc))
12681 << int(E - I);
12682}
12683
12684static SourceLocation
12686 return Cand->Specialization ? Cand->Specialization->getLocation()
12687 : SourceLocation();
12688}
12689
12690namespace {
12691struct CompareTemplateSpecCandidatesForDisplay {
12692 Sema &S;
12693 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12694
12695 bool operator()(const TemplateSpecCandidate *L,
12696 const TemplateSpecCandidate *R) {
12697 // Fast-path this check.
12698 if (L == R)
12699 return false;
12700
12701 // Assuming that both candidates are not matches...
12702
12703 // Sort by the ranking of deduction failures.
12707
12708 // Sort everything else by location.
12711
12712 // Put candidates without locations (e.g. builtins) at the end.
12713 if (LLoc.isInvalid())
12714 return false;
12715 if (RLoc.isInvalid())
12716 return true;
12717
12718 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12719 }
12720};
12721}
12722
12723/// Diagnose a template argument deduction failure.
12724/// We are treating these failures as overload failures due to bad
12725/// deductions.
12727 bool ForTakingAddress) {
12728 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12729 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12730}
12731
12732void TemplateSpecCandidateSet::destroyCandidates() {
12733 for (iterator i = begin(), e = end(); i != e; ++i) {
12734 i->DeductionFailure.Destroy();
12735 }
12736}
12737
12739 destroyCandidates();
12740 Candidates.clear();
12741}
12742
12743/// NoteCandidates - When no template specialization match is found, prints
12744/// diagnostic messages containing the non-matching specializations that form
12745/// the candidate set.
12746/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12747/// OCD == OCD_AllCandidates and Cand->Viable == false.
12749 // Sort the candidates by position (assuming no candidate is a match).
12750 // Sorting directly would be prohibitive, so we make a set of pointers
12751 // and sort those.
12753 Cands.reserve(size());
12754 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12755 if (Cand->Specialization)
12756 Cands.push_back(Cand);
12757 // Otherwise, this is a non-matching builtin candidate. We do not,
12758 // in general, want to list every possible builtin candidate.
12759 }
12760
12761 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12762
12763 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12764 // for generalization purposes (?).
12765 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12766
12768 unsigned CandsShown = 0;
12769 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12770 TemplateSpecCandidate *Cand = *I;
12771
12772 // Set an arbitrary limit on the number of candidates we'll spam
12773 // the user with. FIXME: This limit should depend on details of the
12774 // candidate list.
12775 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12776 break;
12777 ++CandsShown;
12778
12779 assert(Cand->Specialization &&
12780 "Non-matching built-in candidates are not added to Cands.");
12781 Cand->NoteDeductionFailure(S, ForTakingAddress);
12782 }
12783
12784 if (I != E)
12785 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12786}
12787
12788// [PossiblyAFunctionType] --> [Return]
12789// NonFunctionType --> NonFunctionType
12790// R (A) --> R(A)
12791// R (*)(A) --> R (A)
12792// R (&)(A) --> R (A)
12793// R (S::*)(A) --> R (A)
12795 QualType Ret = PossiblyAFunctionType;
12796 if (const PointerType *ToTypePtr =
12797 PossiblyAFunctionType->getAs<PointerType>())
12798 Ret = ToTypePtr->getPointeeType();
12799 else if (const ReferenceType *ToTypeRef =
12800 PossiblyAFunctionType->getAs<ReferenceType>())
12801 Ret = ToTypeRef->getPointeeType();
12802 else if (const MemberPointerType *MemTypePtr =
12803 PossiblyAFunctionType->getAs<MemberPointerType>())
12804 Ret = MemTypePtr->getPointeeType();
12805 Ret =
12806 Context.getCanonicalType(Ret).getUnqualifiedType();
12807 return Ret;
12808}
12809
12811 bool Complain = true) {
12812 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12813 S.DeduceReturnType(FD, Loc, Complain))
12814 return true;
12815
12816 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12817 if (S.getLangOpts().CPlusPlus17 &&
12818 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12819 !S.ResolveExceptionSpec(Loc, FPT))
12820 return true;
12821
12822 return false;
12823}
12824
12825namespace {
12826// A helper class to help with address of function resolution
12827// - allows us to avoid passing around all those ugly parameters
12828class AddressOfFunctionResolver {
12829 Sema& S;
12830 Expr* SourceExpr;
12831 const QualType& TargetType;
12832 QualType TargetFunctionType; // Extracted function type from target type
12833
12834 bool Complain;
12835 //DeclAccessPair& ResultFunctionAccessPair;
12836 ASTContext& Context;
12837
12838 bool TargetTypeIsNonStaticMemberFunction;
12839 bool FoundNonTemplateFunction;
12840 bool StaticMemberFunctionFromBoundPointer;
12841 bool HasComplained;
12842
12843 OverloadExpr::FindResult OvlExprInfo;
12844 OverloadExpr *OvlExpr;
12845 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12847 TemplateSpecCandidateSet FailedCandidates;
12848
12849public:
12850 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12851 const QualType &TargetType, bool Complain)
12852 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12853 Complain(Complain), Context(S.getASTContext()),
12854 TargetTypeIsNonStaticMemberFunction(
12855 !!TargetType->getAs<MemberPointerType>()),
12856 FoundNonTemplateFunction(false),
12857 StaticMemberFunctionFromBoundPointer(false),
12858 HasComplained(false),
12859 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12860 OvlExpr(OvlExprInfo.Expression),
12861 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12862 ExtractUnqualifiedFunctionTypeFromTargetType();
12863
12864 if (TargetFunctionType->isFunctionType()) {
12865 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12866 if (!UME->isImplicitAccess() &&
12868 StaticMemberFunctionFromBoundPointer = true;
12869 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12870 DeclAccessPair dap;
12872 OvlExpr, false, &dap)) {
12873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12874 if (!Method->isStatic()) {
12875 // If the target type is a non-function type and the function found
12876 // is a non-static member function, pretend as if that was the
12877 // target, it's the only possible type to end up with.
12878 TargetTypeIsNonStaticMemberFunction = true;
12879
12880 // And skip adding the function if its not in the proper form.
12881 // We'll diagnose this due to an empty set of functions.
12882 if (!OvlExprInfo.HasFormOfMemberPointer)
12883 return;
12884 }
12885
12886 Matches.push_back(std::make_pair(dap, Fn));
12887 }
12888 return;
12889 }
12890
12891 if (OvlExpr->hasExplicitTemplateArgs())
12892 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12893
12894 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12895 // C++ [over.over]p4:
12896 // If more than one function is selected, [...]
12897 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12898 if (FoundNonTemplateFunction)
12899 EliminateAllTemplateMatches();
12900 else
12901 EliminateAllExceptMostSpecializedTemplate();
12902 }
12903 }
12904
12905 if (S.getLangOpts().CUDA && Matches.size() > 1)
12906 EliminateSuboptimalCudaMatches();
12907 }
12908
12909 bool hasComplained() const { return HasComplained; }
12910
12911private:
12912 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12913 QualType Discard;
12914 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12915 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12916 }
12917
12918 /// \return true if A is considered a better overload candidate for the
12919 /// desired type than B.
12920 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12921 // If A doesn't have exactly the correct type, we don't want to classify it
12922 // as "better" than anything else. This way, the user is required to
12923 // disambiguate for us if there are multiple candidates and no exact match.
12924 return candidateHasExactlyCorrectType(A) &&
12925 (!candidateHasExactlyCorrectType(B) ||
12926 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12927 }
12928
12929 /// \return true if we were able to eliminate all but one overload candidate,
12930 /// false otherwise.
12931 bool eliminiateSuboptimalOverloadCandidates() {
12932 // Same algorithm as overload resolution -- one pass to pick the "best",
12933 // another pass to be sure that nothing is better than the best.
12934 auto Best = Matches.begin();
12935 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12936 if (isBetterCandidate(I->second, Best->second))
12937 Best = I;
12938
12939 const FunctionDecl *BestFn = Best->second;
12940 auto IsBestOrInferiorToBest = [this, BestFn](
12941 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12942 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12943 };
12944
12945 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12946 // option, so we can potentially give the user a better error
12947 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12948 return false;
12949 Matches[0] = *Best;
12950 Matches.resize(1);
12951 return true;
12952 }
12953
12954 bool isTargetTypeAFunction() const {
12955 return TargetFunctionType->isFunctionType();
12956 }
12957
12958 // [ToType] [Return]
12959
12960 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12961 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12962 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12963 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12964 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12965 }
12966
12967 // return true if any matching specializations were found
12968 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12969 const DeclAccessPair& CurAccessFunPair) {
12970 if (CXXMethodDecl *Method
12971 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12972 // Skip non-static function templates when converting to pointer, and
12973 // static when converting to member pointer.
12974 bool CanConvertToFunctionPointer =
12975 Method->isStatic() || Method->isExplicitObjectMemberFunction();
12976 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
12977 return false;
12978 }
12979 else if (TargetTypeIsNonStaticMemberFunction)
12980 return false;
12981
12982 // C++ [over.over]p2:
12983 // If the name is a function template, template argument deduction is
12984 // done (14.8.2.2), and if the argument deduction succeeds, the
12985 // resulting template argument list is used to generate a single
12986 // function template specialization, which is added to the set of
12987 // overloaded functions considered.
12988 FunctionDecl *Specialization = nullptr;
12989 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12991 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
12992 Specialization, Info, /*IsAddressOfFunction*/ true);
12993 Result != TemplateDeductionResult::Success) {
12994 // Make a note of the failed deduction for diagnostics.
12995 FailedCandidates.addCandidate()
12996 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12997 MakeDeductionFailureInfo(Context, Result, Info));
12998 return false;
12999 }
13000
13001 // Template argument deduction ensures that we have an exact match or
13002 // compatible pointer-to-function arguments that would be adjusted by ICS.
13003 // This function template specicalization works.
13005 Context.getCanonicalType(Specialization->getType()),
13006 Context.getCanonicalType(TargetFunctionType)));
13007
13009 return false;
13010
13011 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13012 return true;
13013 }
13014
13015 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13016 const DeclAccessPair& CurAccessFunPair) {
13017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13018 // Skip non-static functions when converting to pointer, and static
13019 // when converting to member pointer.
13020 bool CanConvertToFunctionPointer =
13021 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13022 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13023 return false;
13024 }
13025 else if (TargetTypeIsNonStaticMemberFunction)
13026 return false;
13027
13028 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13029 if (S.getLangOpts().CUDA) {
13030 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13031 if (!(Caller && Caller->isImplicit()) &&
13032 !S.IsAllowedCUDACall(Caller, FunDecl))
13033 return false;
13034 }
13035 if (FunDecl->isMultiVersion()) {
13036 const auto *TA = FunDecl->getAttr<TargetAttr>();
13037 if (TA && !TA->isDefaultVersion())
13038 return false;
13039 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13040 if (TVA && !TVA->isDefaultVersion())
13041 return false;
13042 }
13043
13044 // If any candidate has a placeholder return type, trigger its deduction
13045 // now.
13046 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13047 Complain)) {
13048 HasComplained |= Complain;
13049 return false;
13050 }
13051
13052 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13053 return false;
13054
13055 // If we're in C, we need to support types that aren't exactly identical.
13056 if (!S.getLangOpts().CPlusPlus ||
13057 candidateHasExactlyCorrectType(FunDecl)) {
13058 Matches.push_back(std::make_pair(
13059 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13060 FoundNonTemplateFunction = true;
13061 return true;
13062 }
13063 }
13064
13065 return false;
13066 }
13067
13068 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13069 bool Ret = false;
13070
13071 // If the overload expression doesn't have the form of a pointer to
13072 // member, don't try to convert it to a pointer-to-member type.
13073 if (IsInvalidFormOfPointerToMemberFunction())
13074 return false;
13075
13076 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13077 E = OvlExpr->decls_end();
13078 I != E; ++I) {
13079 // Look through any using declarations to find the underlying function.
13080 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13081
13082 // C++ [over.over]p3:
13083 // Non-member functions and static member functions match
13084 // targets of type "pointer-to-function" or "reference-to-function."
13085 // Nonstatic member functions match targets of
13086 // type "pointer-to-member-function."
13087 // Note that according to DR 247, the containing class does not matter.
13088 if (FunctionTemplateDecl *FunctionTemplate
13089 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13090 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13091 Ret = true;
13092 }
13093 // If we have explicit template arguments supplied, skip non-templates.
13094 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13095 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13096 Ret = true;
13097 }
13098 assert(Ret || Matches.empty());
13099 return Ret;
13100 }
13101
13102 void EliminateAllExceptMostSpecializedTemplate() {
13103 // [...] and any given function template specialization F1 is
13104 // eliminated if the set contains a second function template
13105 // specialization whose function template is more specialized
13106 // than the function template of F1 according to the partial
13107 // ordering rules of 14.5.5.2.
13108
13109 // The algorithm specified above is quadratic. We instead use a
13110 // two-pass algorithm (similar to the one used to identify the
13111 // best viable function in an overload set) that identifies the
13112 // best function template (if it exists).
13113
13114 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13115 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13116 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13117
13118 // TODO: It looks like FailedCandidates does not serve much purpose
13119 // here, since the no_viable diagnostic has index 0.
13121 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13122 SourceExpr->getBeginLoc(), S.PDiag(),
13123 S.PDiag(diag::err_addr_ovl_ambiguous)
13124 << Matches[0].second->getDeclName(),
13125 S.PDiag(diag::note_ovl_candidate)
13126 << (unsigned)oc_function << (unsigned)ocs_described_template,
13127 Complain, TargetFunctionType);
13128
13129 if (Result != MatchesCopy.end()) {
13130 // Make it the first and only element
13131 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13132 Matches[0].second = cast<FunctionDecl>(*Result);
13133 Matches.resize(1);
13134 } else
13135 HasComplained |= Complain;
13136 }
13137
13138 void EliminateAllTemplateMatches() {
13139 // [...] any function template specializations in the set are
13140 // eliminated if the set also contains a non-template function, [...]
13141 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13142 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13143 ++I;
13144 else {
13145 Matches[I] = Matches[--N];
13146 Matches.resize(N);
13147 }
13148 }
13149 }
13150
13151 void EliminateSuboptimalCudaMatches() {
13152 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13153 Matches);
13154 }
13155
13156public:
13157 void ComplainNoMatchesFound() const {
13158 assert(Matches.empty());
13159 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13160 << OvlExpr->getName() << TargetFunctionType
13161 << OvlExpr->getSourceRange();
13162 if (FailedCandidates.empty())
13163 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13164 /*TakingAddress=*/true);
13165 else {
13166 // We have some deduction failure messages. Use them to diagnose
13167 // the function templates, and diagnose the non-template candidates
13168 // normally.
13169 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13170 IEnd = OvlExpr->decls_end();
13171 I != IEnd; ++I)
13172 if (FunctionDecl *Fun =
13173 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13175 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13176 /*TakingAddress=*/true);
13177 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13178 }
13179 }
13180
13181 bool IsInvalidFormOfPointerToMemberFunction() const {
13182 return TargetTypeIsNonStaticMemberFunction &&
13183 !OvlExprInfo.HasFormOfMemberPointer;
13184 }
13185
13186 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13187 // TODO: Should we condition this on whether any functions might
13188 // have matched, or is it more appropriate to do that in callers?
13189 // TODO: a fixit wouldn't hurt.
13190 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13191 << TargetType << OvlExpr->getSourceRange();
13192 }
13193
13194 bool IsStaticMemberFunctionFromBoundPointer() const {
13195 return StaticMemberFunctionFromBoundPointer;
13196 }
13197
13198 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13199 S.Diag(OvlExpr->getBeginLoc(),
13200 diag::err_invalid_form_pointer_member_function)
13201 << OvlExpr->getSourceRange();
13202 }
13203
13204 void ComplainOfInvalidConversion() const {
13205 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13206 << OvlExpr->getName() << TargetType;
13207 }
13208
13209 void ComplainMultipleMatchesFound() const {
13210 assert(Matches.size() > 1);
13211 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13212 << OvlExpr->getName() << OvlExpr->getSourceRange();
13213 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13214 /*TakingAddress=*/true);
13215 }
13216
13217 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13218
13219 int getNumMatches() const { return Matches.size(); }
13220
13221 FunctionDecl* getMatchingFunctionDecl() const {
13222 if (Matches.size() != 1) return nullptr;
13223 return Matches[0].second;
13224 }
13225
13226 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13227 if (Matches.size() != 1) return nullptr;
13228 return &Matches[0].first;
13229 }
13230};
13231}
13232
13233/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13234/// an overloaded function (C++ [over.over]), where @p From is an
13235/// expression with overloaded function type and @p ToType is the type
13236/// we're trying to resolve to. For example:
13237///
13238/// @code
13239/// int f(double);
13240/// int f(int);
13241///
13242/// int (*pfd)(double) = f; // selects f(double)
13243/// @endcode
13244///
13245/// This routine returns the resulting FunctionDecl if it could be
13246/// resolved, and NULL otherwise. When @p Complain is true, this
13247/// routine will emit diagnostics if there is an error.
13250 QualType TargetType,
13251 bool Complain,
13252 DeclAccessPair &FoundResult,
13253 bool *pHadMultipleCandidates) {
13254 assert(AddressOfExpr->getType() == Context.OverloadTy);
13255
13256 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13257 Complain);
13258 int NumMatches = Resolver.getNumMatches();
13259 FunctionDecl *Fn = nullptr;
13260 bool ShouldComplain = Complain && !Resolver.hasComplained();
13261 if (NumMatches == 0 && ShouldComplain) {
13262 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13263 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13264 else
13265 Resolver.ComplainNoMatchesFound();
13266 }
13267 else if (NumMatches > 1 && ShouldComplain)
13268 Resolver.ComplainMultipleMatchesFound();
13269 else if (NumMatches == 1) {
13270 Fn = Resolver.getMatchingFunctionDecl();
13271 assert(Fn);
13272 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13273 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13274 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13275 if (Complain) {
13276 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13277 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13278 else
13279 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13280 }
13281 }
13282
13283 if (pHadMultipleCandidates)
13284 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13285 return Fn;
13286}
13287
13288/// Given an expression that refers to an overloaded function, try to
13289/// resolve that function to a single function that can have its address taken.
13290/// This will modify `Pair` iff it returns non-null.
13291///
13292/// This routine can only succeed if from all of the candidates in the overload
13293/// set for SrcExpr that can have their addresses taken, there is one candidate
13294/// that is more constrained than the rest.
13298 OverloadExpr *Ovl = R.Expression;
13299 bool IsResultAmbiguous = false;
13300 FunctionDecl *Result = nullptr;
13301 DeclAccessPair DAP;
13302 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13303
13304 // Return positive for better, negative for worse, 0 for equal preference.
13305 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13306 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13307 return static_cast<int>(IdentifyCUDAPreference(Caller, FD1)) -
13308 static_cast<int>(IdentifyCUDAPreference(Caller, FD2));
13309 };
13310
13311 auto CheckMoreConstrained = [&](FunctionDecl *FD1,
13312 FunctionDecl *FD2) -> std::optional<bool> {
13314 FD1 = MF;
13316 FD2 = MF;
13318 FD1->getAssociatedConstraints(AC1);
13319 FD2->getAssociatedConstraints(AC2);
13320 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
13321 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
13322 return std::nullopt;
13323 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
13324 return std::nullopt;
13325 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
13326 return std::nullopt;
13327 return AtLeastAsConstrained1;
13328 };
13329
13330 // Don't use the AddressOfResolver because we're specifically looking for
13331 // cases where we have one overload candidate that lacks
13332 // enable_if/pass_object_size/...
13333 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13334 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13335 if (!FD)
13336 return nullptr;
13337
13339 continue;
13340
13341 // If we found a better result, update Result.
13342 auto FoundBetter = [&]() {
13343 IsResultAmbiguous = false;
13344 DAP = I.getPair();
13345 Result = FD;
13346 };
13347
13348 // We have more than one result - see if it is more constrained than the
13349 // previous one.
13350 if (Result) {
13351 // Check CUDA preference first. If the candidates have differennt CUDA
13352 // preference, choose the one with higher CUDA preference. Otherwise,
13353 // choose the one with more constraints.
13354 if (getLangOpts().CUDA) {
13355 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13356 // FD has different preference than Result.
13357 if (PreferenceByCUDA != 0) {
13358 // FD is more preferable than Result.
13359 if (PreferenceByCUDA > 0)
13360 FoundBetter();
13361 continue;
13362 }
13363 }
13364 // FD has the same CUDA prefernece than Result. Continue check
13365 // constraints.
13366 std::optional<bool> MoreConstrainedThanPrevious =
13367 CheckMoreConstrained(FD, Result);
13368 if (!MoreConstrainedThanPrevious) {
13369 IsResultAmbiguous = true;
13370 AmbiguousDecls.push_back(FD);
13371 continue;
13372 }
13373 if (!*MoreConstrainedThanPrevious)
13374 continue;
13375 // FD is more constrained - replace Result with it.
13376 }
13377 FoundBetter();
13378 }
13379
13380 if (IsResultAmbiguous)
13381 return nullptr;
13382
13383 if (Result) {
13385 // We skipped over some ambiguous declarations which might be ambiguous with
13386 // the selected result.
13387 for (FunctionDecl *Skipped : AmbiguousDecls) {
13388 // If skipped candidate has different CUDA preference than the result,
13389 // there is no ambiguity. Otherwise check whether they have different
13390 // constraints.
13391 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13392 continue;
13393 if (!CheckMoreConstrained(Skipped, Result))
13394 return nullptr;
13395 }
13396 Pair = DAP;
13397 }
13398 return Result;
13399}
13400
13401/// Given an overloaded function, tries to turn it into a non-overloaded
13402/// function reference using resolveAddressOfSingleOverloadCandidate. This
13403/// will perform access checks, diagnose the use of the resultant decl, and, if
13404/// requested, potentially perform a function-to-pointer decay.
13405///
13406/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13407/// Otherwise, returns true. This may emit diagnostics and return true.
13409 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13410 Expr *E = SrcExpr.get();
13411 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13412
13413 DeclAccessPair DAP;
13414 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13415 if (!Found || Found->isCPUDispatchMultiVersion() ||
13417 return false;
13418
13419 // Emitting multiple diagnostics for a function that is both inaccessible and
13420 // unavailable is consistent with our behavior elsewhere. So, always check
13421 // for both.
13422 DiagnoseUseOfDecl(Found, E->getExprLoc());
13423 CheckAddressOfMemberAccess(E, DAP);
13424 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13425 if (Res.isInvalid())
13426 return false;
13427 Expr *Fixed = Res.get();
13428 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13429 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13430 else
13431 SrcExpr = Fixed;
13432 return true;
13433}
13434
13435/// Given an expression that refers to an overloaded function, try to
13436/// resolve that overloaded function expression down to a single function.
13437///
13438/// This routine can only resolve template-ids that refer to a single function
13439/// template, where that template-id refers to a single template whose template
13440/// arguments are either provided by the template-id or have defaults,
13441/// as described in C++0x [temp.arg.explicit]p3.
13442///
13443/// If no template-ids are found, no diagnostics are emitted and NULL is
13444/// returned.
13446 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13447 TemplateSpecCandidateSet *FailedTSC) {
13448 // C++ [over.over]p1:
13449 // [...] [Note: any redundant set of parentheses surrounding the
13450 // overloaded function name is ignored (5.1). ]
13451 // C++ [over.over]p1:
13452 // [...] The overloaded function name can be preceded by the &
13453 // operator.
13454
13455 // If we didn't actually find any template-ids, we're done.
13456 if (!ovl->hasExplicitTemplateArgs())
13457 return nullptr;
13458
13459 TemplateArgumentListInfo ExplicitTemplateArgs;
13460 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13461
13462 // Look through all of the overloaded functions, searching for one
13463 // whose type matches exactly.
13464 FunctionDecl *Matched = nullptr;
13465 for (UnresolvedSetIterator I = ovl->decls_begin(),
13466 E = ovl->decls_end(); I != E; ++I) {
13467 // C++0x [temp.arg.explicit]p3:
13468 // [...] In contexts where deduction is done and fails, or in contexts
13469 // where deduction is not done, if a template argument list is
13470 // specified and it, along with any default template arguments,
13471 // identifies a single function template specialization, then the
13472 // template-id is an lvalue for the function template specialization.
13473 FunctionTemplateDecl *FunctionTemplate
13474 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13475
13476 // C++ [over.over]p2:
13477 // If the name is a function template, template argument deduction is
13478 // done (14.8.2.2), and if the argument deduction succeeds, the
13479 // resulting template argument list is used to generate a single
13480 // function template specialization, which is added to the set of
13481 // overloaded functions considered.
13482 FunctionDecl *Specialization = nullptr;
13483 TemplateDeductionInfo Info(ovl->getNameLoc());
13485 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13486 /*IsAddressOfFunction*/ true);
13488 // Make a note of the failed deduction for diagnostics.
13489 if (FailedTSC)
13490 FailedTSC->addCandidate().set(
13491 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13492 MakeDeductionFailureInfo(Context, Result, Info));
13493 continue;
13494 }
13495
13496 assert(Specialization && "no specialization and no error?");
13497
13498 // Multiple matches; we can't resolve to a single declaration.
13499 if (Matched) {
13500 if (Complain) {
13501 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13502 << ovl->getName();
13503 NoteAllOverloadCandidates(ovl);
13504 }
13505 return nullptr;
13506 }
13507
13508 Matched = Specialization;
13509 if (FoundResult) *FoundResult = I.getPair();
13510 }
13511
13512 if (Matched &&
13513 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13514 return nullptr;
13515
13516 return Matched;
13517}
13518
13519// Resolve and fix an overloaded expression that can be resolved
13520// because it identifies a single function template specialization.
13521//
13522// Last three arguments should only be supplied if Complain = true
13523//
13524// Return true if it was logically possible to so resolve the
13525// expression, regardless of whether or not it succeeded. Always
13526// returns true if 'complain' is set.
13528 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13529 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13530 unsigned DiagIDForComplaining) {
13531 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13532
13534
13535 DeclAccessPair found;
13536 ExprResult SingleFunctionExpression;
13537 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13538 ovl.Expression, /*complain*/ false, &found)) {
13539 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13540 SrcExpr = ExprError();
13541 return true;
13542 }
13543
13544 // It is only correct to resolve to an instance method if we're
13545 // resolving a form that's permitted to be a pointer to member.
13546 // Otherwise we'll end up making a bound member expression, which
13547 // is illegal in all the contexts we resolve like this.
13548 if (!ovl.HasFormOfMemberPointer &&
13549 isa<CXXMethodDecl>(fn) &&
13550 cast<CXXMethodDecl>(fn)->isInstance()) {
13551 if (!complain) return false;
13552
13553 Diag(ovl.Expression->getExprLoc(),
13554 diag::err_bound_member_function)
13555 << 0 << ovl.Expression->getSourceRange();
13556
13557 // TODO: I believe we only end up here if there's a mix of
13558 // static and non-static candidates (otherwise the expression
13559 // would have 'bound member' type, not 'overload' type).
13560 // Ideally we would note which candidate was chosen and why
13561 // the static candidates were rejected.
13562 SrcExpr = ExprError();
13563 return true;
13564 }
13565
13566 // Fix the expression to refer to 'fn'.
13567 SingleFunctionExpression =
13568 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13569
13570 // If desired, do function-to-pointer decay.
13571 if (doFunctionPointerConversion) {
13572 SingleFunctionExpression =
13573 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13574 if (SingleFunctionExpression.isInvalid()) {
13575 SrcExpr = ExprError();
13576 return true;
13577 }
13578 }
13579 }
13580
13581 if (!SingleFunctionExpression.isUsable()) {
13582 if (complain) {
13583 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13584 << ovl.Expression->getName()
13585 << DestTypeForComplaining
13586 << OpRangeForComplaining
13588 NoteAllOverloadCandidates(SrcExpr.get());
13589
13590 SrcExpr = ExprError();
13591 return true;
13592 }
13593
13594 return false;
13595 }
13596
13597 SrcExpr = SingleFunctionExpression;
13598 return true;
13599}
13600
13601/// Add a single candidate to the overload set.
13603 DeclAccessPair FoundDecl,
13604 TemplateArgumentListInfo *ExplicitTemplateArgs,
13605 ArrayRef<Expr *> Args,
13606 OverloadCandidateSet &CandidateSet,
13607 bool PartialOverloading,
13608 bool KnownValid) {
13609 NamedDecl *Callee = FoundDecl.getDecl();
13610 if (isa<UsingShadowDecl>(Callee))
13611 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13612
13613 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13614 if (ExplicitTemplateArgs) {
13615 assert(!KnownValid && "Explicit template arguments?");
13616 return;
13617 }
13618 // Prevent ill-formed function decls to be added as overload candidates.
13619 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13620 return;
13621
13622 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13623 /*SuppressUserConversions=*/false,
13624 PartialOverloading);
13625 return;
13626 }
13627
13628 if (FunctionTemplateDecl *FuncTemplate
13629 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13630 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13631 ExplicitTemplateArgs, Args, CandidateSet,
13632 /*SuppressUserConversions=*/false,
13633 PartialOverloading);
13634 return;
13635 }
13636
13637 assert(!KnownValid && "unhandled case in overloaded call candidate");
13638}
13639
13640/// Add the overload candidates named by callee and/or found by argument
13641/// dependent lookup to the given overload set.
13643 ArrayRef<Expr *> Args,
13644 OverloadCandidateSet &CandidateSet,
13645 bool PartialOverloading) {
13646
13647#ifndef NDEBUG
13648 // Verify that ArgumentDependentLookup is consistent with the rules
13649 // in C++0x [basic.lookup.argdep]p3:
13650 //
13651 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13652 // and let Y be the lookup set produced by argument dependent
13653 // lookup (defined as follows). If X contains
13654 //
13655 // -- a declaration of a class member, or
13656 //
13657 // -- a block-scope function declaration that is not a
13658 // using-declaration, or
13659 //
13660 // -- a declaration that is neither a function or a function
13661 // template
13662 //
13663 // then Y is empty.
13664
13665 if (ULE->requiresADL()) {
13667 E = ULE->decls_end(); I != E; ++I) {
13668 assert(!(*I)->getDeclContext()->isRecord());
13669 assert(isa<UsingShadowDecl>(*I) ||
13670 !(*I)->getDeclContext()->isFunctionOrMethod());
13671 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13672 }
13673 }
13674#endif
13675
13676 // It would be nice to avoid this copy.
13677 TemplateArgumentListInfo TABuffer;
13678 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13679 if (ULE->hasExplicitTemplateArgs()) {
13680 ULE->copyTemplateArgumentsInto(TABuffer);
13681 ExplicitTemplateArgs = &TABuffer;
13682 }
13683
13685 E = ULE->decls_end(); I != E; ++I)
13686 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13687 CandidateSet, PartialOverloading,
13688 /*KnownValid*/ true);
13689
13690 if (ULE->requiresADL())
13691 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13692 Args, ExplicitTemplateArgs,
13693 CandidateSet, PartialOverloading);
13694}
13695
13696/// Add the call candidates from the given set of lookup results to the given
13697/// overload set. Non-function lookup results are ignored.
13699 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13700 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13701 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13702 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13703 CandidateSet, false, /*KnownValid*/ false);
13704}
13705
13706/// Determine whether a declaration with the specified name could be moved into
13707/// a different namespace.
13709 switch (Name.getCXXOverloadedOperator()) {
13710 case OO_New: case OO_Array_New:
13711 case OO_Delete: case OO_Array_Delete:
13712 return false;
13713
13714 default:
13715 return true;
13716 }
13717}
13718
13719/// Attempt to recover from an ill-formed use of a non-dependent name in a
13720/// template, where the non-dependent name was declared after the template
13721/// was defined. This is common in code written for a compilers which do not
13722/// correctly implement two-stage name lookup.
13723///
13724/// Returns true if a viable candidate was found and a diagnostic was issued.
13726 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13728 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13729 CXXRecordDecl **FoundInClass = nullptr) {
13730 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13731 return false;
13732
13733 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13734 if (DC->isTransparentContext())
13735 continue;
13736
13737 SemaRef.LookupQualifiedName(R, DC);
13738
13739 if (!R.empty()) {
13741
13742 OverloadCandidateSet Candidates(FnLoc, CSK);
13743 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13744 Candidates);
13745
13748 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13749
13750 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13751 // We either found non-function declarations or a best viable function
13752 // at class scope. A class-scope lookup result disables ADL. Don't
13753 // look past this, but let the caller know that we found something that
13754 // either is, or might be, usable in this class.
13755 if (FoundInClass) {
13756 *FoundInClass = RD;
13757 if (OR == OR_Success) {
13758 R.clear();
13759 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13760 R.resolveKind();
13761 }
13762 }
13763 return false;
13764 }
13765
13766 if (OR != OR_Success) {
13767 // There wasn't a unique best function or function template.
13768 return false;
13769 }
13770
13771 // Find the namespaces where ADL would have looked, and suggest
13772 // declaring the function there instead.
13773 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13774 Sema::AssociatedClassSet AssociatedClasses;
13775 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13776 AssociatedNamespaces,
13777 AssociatedClasses);
13778 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13780 DeclContext *Std = SemaRef.getStdNamespace();
13781 for (Sema::AssociatedNamespaceSet::iterator
13782 it = AssociatedNamespaces.begin(),
13783 end = AssociatedNamespaces.end(); it != end; ++it) {
13784 // Never suggest declaring a function within namespace 'std'.
13785 if (Std && Std->Encloses(*it))
13786 continue;
13787
13788 // Never suggest declaring a function within a namespace with a
13789 // reserved name, like __gnu_cxx.
13790 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13791 if (NS &&
13792 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13793 continue;
13794
13795 SuggestedNamespaces.insert(*it);
13796 }
13797 }
13798
13799 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13800 << R.getLookupName();
13801 if (SuggestedNamespaces.empty()) {
13802 SemaRef.Diag(Best->Function->getLocation(),
13803 diag::note_not_found_by_two_phase_lookup)
13804 << R.getLookupName() << 0;
13805 } else if (SuggestedNamespaces.size() == 1) {
13806 SemaRef.Diag(Best->Function->getLocation(),
13807 diag::note_not_found_by_two_phase_lookup)
13808 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13809 } else {
13810 // FIXME: It would be useful to list the associated namespaces here,
13811 // but the diagnostics infrastructure doesn't provide a way to produce
13812 // a localized representation of a list of items.
13813 SemaRef.Diag(Best->Function->getLocation(),
13814 diag::note_not_found_by_two_phase_lookup)
13815 << R.getLookupName() << 2;
13816 }
13817
13818 // Try to recover by calling this function.
13819 return true;
13820 }
13821
13822 R.clear();
13823 }
13824
13825 return false;
13826}
13827
13828/// Attempt to recover from ill-formed use of a non-dependent operator in a
13829/// template, where the non-dependent operator was declared after the template
13830/// was defined.
13831///
13832/// Returns true if a viable candidate was found and a diagnostic was issued.
13833static bool
13835 SourceLocation OpLoc,
13836 ArrayRef<Expr *> Args) {
13837 DeclarationName OpName =
13839 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13840 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13842 /*ExplicitTemplateArgs=*/nullptr, Args);
13843}
13844
13845namespace {
13846class BuildRecoveryCallExprRAII {
13847 Sema &SemaRef;
13849
13850public:
13851 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13852 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13853 SemaRef.IsBuildingRecoveryCallExpr = true;
13854 }
13855
13856 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13857};
13858}
13859
13860/// Attempts to recover from a call where no functions were found.
13861///
13862/// This function will do one of three things:
13863/// * Diagnose, recover, and return a recovery expression.
13864/// * Diagnose, fail to recover, and return ExprError().
13865/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13866/// expected to diagnose as appropriate.
13867static ExprResult
13870 SourceLocation LParenLoc,
13872 SourceLocation RParenLoc,
13873 bool EmptyLookup, bool AllowTypoCorrection) {
13874 // Do not try to recover if it is already building a recovery call.
13875 // This stops infinite loops for template instantiations like
13876 //
13877 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13878 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13879 if (SemaRef.IsBuildingRecoveryCallExpr)
13880 return ExprResult();
13881 BuildRecoveryCallExprRAII RCE(SemaRef);
13882
13883 CXXScopeSpec SS;
13884 SS.Adopt(ULE->getQualifierLoc());
13885 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13886
13887 TemplateArgumentListInfo TABuffer;
13888 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13889 if (ULE->hasExplicitTemplateArgs()) {
13890 ULE->copyTemplateArgumentsInto(TABuffer);
13891 ExplicitTemplateArgs = &TABuffer;
13892 }
13893
13894 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13896 CXXRecordDecl *FoundInClass = nullptr;
13897 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13899 ExplicitTemplateArgs, Args, &FoundInClass)) {
13900 // OK, diagnosed a two-phase lookup issue.
13901 } else if (EmptyLookup) {
13902 // Try to recover from an empty lookup with typo correction.
13903 R.clear();
13904 NoTypoCorrectionCCC NoTypoValidator{};
13905 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13906 ExplicitTemplateArgs != nullptr,
13907 dyn_cast<MemberExpr>(Fn));
13908 CorrectionCandidateCallback &Validator =
13909 AllowTypoCorrection
13910 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13911 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13912 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13913 Args))
13914 return ExprError();
13915 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13916 // We found a usable declaration of the name in a dependent base of some
13917 // enclosing class.
13918 // FIXME: We should also explain why the candidates found by name lookup
13919 // were not viable.
13920 if (SemaRef.DiagnoseDependentMemberLookup(R))
13921 return ExprError();
13922 } else {
13923 // We had viable candidates and couldn't recover; let the caller diagnose
13924 // this.
13925 return ExprResult();
13926 }
13927
13928 // If we get here, we should have issued a diagnostic and formed a recovery
13929 // lookup result.
13930 assert(!R.empty() && "lookup results empty despite recovery");
13931
13932 // If recovery created an ambiguity, just bail out.
13933 if (R.isAmbiguous()) {
13935 return ExprError();
13936 }
13937
13938 // Build an implicit member call if appropriate. Just drop the
13939 // casts and such from the call, we don't really care.
13940 ExprResult NewFn = ExprError();
13941 if ((*R.begin())->isCXXClassMember())
13942 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13943 ExplicitTemplateArgs, S);
13944 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13945 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13946 ExplicitTemplateArgs);
13947 else
13948 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13949
13950 if (NewFn.isInvalid())
13951 return ExprError();
13952
13953 // This shouldn't cause an infinite loop because we're giving it
13954 // an expression with viable lookup results, which should never
13955 // end up here.
13956 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13957 MultiExprArg(Args.data(), Args.size()),
13958 RParenLoc);
13959}
13960
13961/// Constructs and populates an OverloadedCandidateSet from
13962/// the given function.
13963/// \returns true when an the ExprResult output parameter has been set.
13966 MultiExprArg Args,
13967 SourceLocation RParenLoc,
13968 OverloadCandidateSet *CandidateSet,
13969 ExprResult *Result) {
13970#ifndef NDEBUG
13971 if (ULE->requiresADL()) {
13972 // To do ADL, we must have found an unqualified name.
13973 assert(!ULE->getQualifier() && "qualified name with ADL");
13974
13975 // We don't perform ADL for implicit declarations of builtins.
13976 // Verify that this was correctly set up.
13977 FunctionDecl *F;
13978 if (ULE->decls_begin() != ULE->decls_end() &&
13979 ULE->decls_begin() + 1 == ULE->decls_end() &&
13980 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13981 F->getBuiltinID() && F->isImplicit())
13982 llvm_unreachable("performing ADL for builtin");
13983
13984 // We don't perform ADL in C.
13985 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13986 }
13987#endif
13988
13989 UnbridgedCastsSet UnbridgedCasts;
13990 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13991 *Result = ExprError();
13992 return true;
13993 }
13994
13995 // Add the functions denoted by the callee to the set of candidate
13996 // functions, including those from argument-dependent lookup.
13997 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13998
13999 if (getLangOpts().MSVCCompat &&
14000 CurContext->isDependentContext() && !isSFINAEContext() &&
14001 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14002
14004 if (CandidateSet->empty() ||
14005 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14007 // In Microsoft mode, if we are inside a template class member function
14008 // then create a type dependent CallExpr. The goal is to postpone name
14009 // lookup to instantiation time to be able to search into type dependent
14010 // base classes.
14011 CallExpr *CE =
14012 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14013 RParenLoc, CurFPFeatureOverrides());
14015 *Result = CE;
14016 return true;
14017 }
14018 }
14019
14020 if (CandidateSet->empty())
14021 return false;
14022
14023 UnbridgedCasts.restore();
14024 return false;
14025}
14026
14027// Guess at what the return type for an unresolvable overload should be.
14030 std::optional<QualType> Result;
14031 // Adjust Type after seeing a candidate.
14032 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14033 if (!Candidate.Function)
14034 return;
14035 if (Candidate.Function->isInvalidDecl())
14036 return;
14037 QualType T = Candidate.Function->getReturnType();
14038 if (T.isNull())
14039 return;
14040 if (!Result)
14041 Result = T;
14042 else if (Result != T)
14043 Result = QualType();
14044 };
14045
14046 // Look for an unambiguous type from a progressively larger subset.
14047 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14048 //
14049 // First, consider only the best candidate.
14050 if (Best && *Best != CS.end())
14051 ConsiderCandidate(**Best);
14052 // Next, consider only viable candidates.
14053 if (!Result)
14054 for (const auto &C : CS)
14055 if (C.Viable)
14056 ConsiderCandidate(C);
14057 // Finally, consider all candidates.
14058 if (!Result)
14059 for (const auto &C : CS)
14060 ConsiderCandidate(C);
14061
14062 if (!Result)
14063 return QualType();
14064 auto Value = *Result;
14065 if (Value.isNull() || Value->isUndeducedType())
14066 return QualType();
14067 return Value;
14068}
14069
14070/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14071/// the completed call expression. If overload resolution fails, emits
14072/// diagnostics and returns ExprError()
14075 SourceLocation LParenLoc,
14076 MultiExprArg Args,
14077 SourceLocation RParenLoc,
14078 Expr *ExecConfig,
14079 OverloadCandidateSet *CandidateSet,
14081 OverloadingResult OverloadResult,
14082 bool AllowTypoCorrection) {
14083 switch (OverloadResult) {
14084 case OR_Success: {
14085 FunctionDecl *FDecl = (*Best)->Function;
14086 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14087 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14088 return ExprError();
14089 ExprResult Res =
14090 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14091 if (Res.isInvalid())
14092 return ExprError();
14093 return SemaRef.BuildResolvedCallExpr(
14094 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14095 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14096 }
14097
14098 case OR_No_Viable_Function: {
14099 // Try to recover by looking for viable functions which the user might
14100 // have meant to call.
14101 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14102 Args, RParenLoc,
14103 CandidateSet->empty(),
14104 AllowTypoCorrection);
14105 if (Recovery.isInvalid() || Recovery.isUsable())
14106 return Recovery;
14107
14108 // If the user passes in a function that we can't take the address of, we
14109 // generally end up emitting really bad error messages. Here, we attempt to
14110 // emit better ones.
14111 for (const Expr *Arg : Args) {
14112 if (!Arg->getType()->isFunctionType())
14113 continue;
14114 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14115 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14116 if (FD &&
14117 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14118 Arg->getExprLoc()))
14119 return ExprError();
14120 }
14121 }
14122
14123 CandidateSet->NoteCandidates(
14125 Fn->getBeginLoc(),
14126 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14127 << ULE->getName() << Fn->getSourceRange()),
14128 SemaRef, OCD_AllCandidates, Args);
14129 break;
14130 }
14131
14132 case OR_Ambiguous:
14133 CandidateSet->NoteCandidates(
14135 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14136 << ULE->getName() << Fn->getSourceRange()),
14137 SemaRef, OCD_AmbiguousCandidates, Args);
14138 break;
14139
14140 case OR_Deleted: {
14141 CandidateSet->NoteCandidates(
14143 SemaRef.PDiag(diag::err_ovl_deleted_call)
14144 << ULE->getName() << Fn->getSourceRange()),
14145 SemaRef, OCD_AllCandidates, Args);
14146
14147 // We emitted an error for the unavailable/deleted function call but keep
14148 // the call in the AST.
14149 FunctionDecl *FDecl = (*Best)->Function;
14150 ExprResult Res =
14151 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14152 if (Res.isInvalid())
14153 return ExprError();
14154 return SemaRef.BuildResolvedCallExpr(
14155 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14156 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14157 }
14158 }
14159
14160 // Overload resolution failed, try to recover.
14161 SmallVector<Expr *, 8> SubExprs = {Fn};
14162 SubExprs.append(Args.begin(), Args.end());
14163 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14164 chooseRecoveryType(*CandidateSet, Best));
14165}
14166
14169 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14170 if (I->Viable &&
14171 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14172 I->Viable = false;
14173 I->FailureKind = ovl_fail_addr_not_available;
14174 }
14175 }
14176}
14177
14178/// BuildOverloadedCallExpr - Given the call expression that calls Fn
14179/// (which eventually refers to the declaration Func) and the call
14180/// arguments Args/NumArgs, attempt to resolve the function call down
14181/// to a specific function. If overload resolution succeeds, returns
14182/// the call expression produced by overload resolution.
14183/// Otherwise, emits diagnostics and returns ExprError.
14186 SourceLocation LParenLoc,
14187 MultiExprArg Args,
14188 SourceLocation RParenLoc,
14189 Expr *ExecConfig,
14190 bool AllowTypoCorrection,
14191 bool CalleesAddressIsTaken) {
14192 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14194 ExprResult result;
14195
14196 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14197 &result))
14198 return result;
14199
14200 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14201 // functions that aren't addressible are considered unviable.
14202 if (CalleesAddressIsTaken)
14203 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14204
14206 OverloadingResult OverloadResult =
14207 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14208
14209 // Model the case with a call to a templated function whose definition
14210 // encloses the call and whose return type contains a placeholder type as if
14211 // the UnresolvedLookupExpr was type-dependent.
14212 if (OverloadResult == OR_Success) {
14213 const FunctionDecl *FDecl = Best->Function;
14214 if (FDecl && FDecl->isTemplateInstantiation() &&
14215 FDecl->getReturnType()->isUndeducedType()) {
14216 if (const auto *TP =
14217 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14218 TP && TP->willHaveBody()) {
14219 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14220 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14221 }
14222 }
14223 }
14224
14225 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14226 ExecConfig, &CandidateSet, &Best,
14227 OverloadResult, AllowTypoCorrection);
14228}
14229
14230static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
14231 return Functions.size() > 1 ||
14232 (Functions.size() == 1 &&
14233 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
14234}
14235
14239 const UnresolvedSetImpl &Fns,
14240 bool PerformADL) {
14241 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14242 PerformADL, IsOverloaded(Fns),
14243 Fns.begin(), Fns.end());
14244}
14245
14247 CXXConversionDecl *Method,
14248 bool HadMultipleCandidates) {
14249 // Convert the expression to match the conversion function's implicit object
14250 // parameter.
14251 ExprResult Exp;
14252 if (Method->isExplicitObjectMemberFunction())
14253 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14254 else
14255 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14256 FoundDecl, Method);
14257 if (Exp.isInvalid())
14258 return true;
14259
14260 if (Method->getParent()->isLambda() &&
14262 // This is a lambda conversion to block pointer; check if the argument
14263 // was a LambdaExpr.
14264 Expr *SubE = E;
14265 auto *CE = dyn_cast<CastExpr>(SubE);
14266 if (CE && CE->getCastKind() == CK_NoOp)
14267 SubE = CE->getSubExpr();
14268 SubE = SubE->IgnoreParens();
14269 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14270 SubE = BE->getSubExpr();
14271 if (isa<LambdaExpr>(SubE)) {
14272 // For the conversion to block pointer on a lambda expression, we
14273 // construct a special BlockLiteral instead; this doesn't really make
14274 // a difference in ARC, but outside of ARC the resulting block literal
14275 // follows the normal lifetime rules for block literals instead of being
14276 // autoreleased.
14277 PushExpressionEvaluationContext(
14278 ExpressionEvaluationContext::PotentiallyEvaluated);
14279 ExprResult BlockExp = BuildBlockForLambdaConversion(
14280 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14281 PopExpressionEvaluationContext();
14282
14283 // FIXME: This note should be produced by a CodeSynthesisContext.
14284 if (BlockExp.isInvalid())
14285 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14286 return BlockExp;
14287 }
14288 }
14289 CallExpr *CE;
14290 QualType ResultType = Method->getReturnType();
14292 ResultType = ResultType.getNonLValueExprType(Context);
14293 if (Method->isExplicitObjectMemberFunction()) {
14294 ExprResult FnExpr =
14295 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14296 HadMultipleCandidates, E->getBeginLoc());
14297 if (FnExpr.isInvalid())
14298 return ExprError();
14299 Expr *ObjectParam = Exp.get();
14300 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14301 ResultType, VK, Exp.get()->getEndLoc(),
14302 CurFPFeatureOverrides());
14303 } else {
14304 MemberExpr *ME =
14305 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14307 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14308 HadMultipleCandidates, DeclarationNameInfo(),
14310
14311 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14312 Exp.get()->getEndLoc(),
14313 CurFPFeatureOverrides());
14314 }
14315
14316 if (CheckFunctionCall(Method, CE,
14317 Method->getType()->castAs<FunctionProtoType>()))
14318 return ExprError();
14319
14320 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14321}
14322
14323/// Create a unary operation that may resolve to an overloaded
14324/// operator.
14325///
14326/// \param OpLoc The location of the operator itself (e.g., '*').
14327///
14328/// \param Opc The UnaryOperatorKind that describes this operator.
14329///
14330/// \param Fns The set of non-member functions that will be
14331/// considered by overload resolution. The caller needs to build this
14332/// set based on the context using, e.g.,
14333/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14334/// set should not contain any member functions; those will be added
14335/// by CreateOverloadedUnaryOp().
14336///
14337/// \param Input The input argument.
14340 const UnresolvedSetImpl &Fns,
14341 Expr *Input, bool PerformADL) {
14343 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14345 // TODO: provide better source location info.
14346 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14347
14348 if (checkPlaceholderForOverload(*this, Input))
14349 return ExprError();
14350
14351 Expr *Args[2] = { Input, nullptr };
14352 unsigned NumArgs = 1;
14353
14354 // For post-increment and post-decrement, add the implicit '0' as
14355 // the second argument, so that we know this is a post-increment or
14356 // post-decrement.
14357 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14358 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14359 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14360 SourceLocation());
14361 NumArgs = 2;
14362 }
14363
14364 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14365
14366 if (Input->isTypeDependent()) {
14367 if (Fns.empty())
14368 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
14369 VK_PRValue, OK_Ordinary, OpLoc, false,
14370 CurFPFeatureOverrides());
14371
14372 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14373 ExprResult Fn = CreateUnresolvedLookupExpr(
14374 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14375 if (Fn.isInvalid())
14376 return ExprError();
14377 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14378 Context.DependentTy, VK_PRValue, OpLoc,
14379 CurFPFeatureOverrides());
14380 }
14381
14382 // Build an empty overload set.
14384
14385 // Add the candidates from the given function set.
14386 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14387
14388 // Add operator candidates that are member functions.
14389 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14390
14391 // Add candidates from ADL.
14392 if (PerformADL) {
14393 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14394 /*ExplicitTemplateArgs*/nullptr,
14395 CandidateSet);
14396 }
14397
14398 // Add builtin operator candidates.
14399 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14400
14401 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14402
14403 // Perform overload resolution.
14405 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14406 case OR_Success: {
14407 // We found a built-in operator or an overloaded operator.
14408 FunctionDecl *FnDecl = Best->Function;
14409
14410 if (FnDecl) {
14411 Expr *Base = nullptr;
14412 // We matched an overloaded operator. Build a call to that
14413 // operator.
14414
14415 // Convert the arguments.
14416 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14417 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14418
14419 ExprResult InputInit;
14420 if (Method->isExplicitObjectMemberFunction())
14421 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14422 else
14423 InputInit = PerformImplicitObjectArgumentInitialization(
14424 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14425 if (InputInit.isInvalid())
14426 return ExprError();
14427 Base = Input = InputInit.get();
14428 } else {
14429 // Convert the arguments.
14430 ExprResult InputInit
14431 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14432 Context,
14433 FnDecl->getParamDecl(0)),
14435 Input);
14436 if (InputInit.isInvalid())
14437 return ExprError();
14438 Input = InputInit.get();
14439 }
14440
14441 // Build the actual expression node.
14442 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14443 Base, HadMultipleCandidates,
14444 OpLoc);
14445 if (FnExpr.isInvalid())
14446 return ExprError();
14447
14448 // Determine the result type.
14449 QualType ResultTy = FnDecl->getReturnType();
14451 ResultTy = ResultTy.getNonLValueExprType(Context);
14452
14453 Args[0] = Input;
14455 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14456 CurFPFeatureOverrides(), Best->IsADLCandidate);
14457
14458 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14459 return ExprError();
14460
14461 if (CheckFunctionCall(FnDecl, TheCall,
14462 FnDecl->getType()->castAs<FunctionProtoType>()))
14463 return ExprError();
14464 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14465 } else {
14466 // We matched a built-in operator. Convert the arguments, then
14467 // break out so that we will build the appropriate built-in
14468 // operator node.
14469 ExprResult InputRes = PerformImplicitConversion(
14470 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14471 CCK_ForBuiltinOverloadedOp);
14472 if (InputRes.isInvalid())
14473 return ExprError();
14474 Input = InputRes.get();
14475 break;
14476 }
14477 }
14478
14480 // This is an erroneous use of an operator which can be overloaded by
14481 // a non-member function. Check for non-member operators which were
14482 // defined too late to be candidates.
14483 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14484 // FIXME: Recover by calling the found function.
14485 return ExprError();
14486
14487 // No viable function; fall through to handling this as a
14488 // built-in operator, which will produce an error message for us.
14489 break;
14490
14491 case OR_Ambiguous:
14492 CandidateSet.NoteCandidates(
14493 PartialDiagnosticAt(OpLoc,
14494 PDiag(diag::err_ovl_ambiguous_oper_unary)
14496 << Input->getType() << Input->getSourceRange()),
14497 *this, OCD_AmbiguousCandidates, ArgsArray,
14498 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14499 return ExprError();
14500
14501 case OR_Deleted:
14502 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14503 // object whose method was called. Later in NoteCandidates size of ArgsArray
14504 // is passed further and it eventually ends up compared to number of
14505 // function candidate parameters which never includes the object parameter,
14506 // so slice ArgsArray to make sure apples are compared to apples.
14507 CandidateSet.NoteCandidates(
14508 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14510 << Input->getSourceRange()),
14511 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14512 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14513 return ExprError();
14514 }
14515
14516 // Either we found no viable overloaded operator or we matched a
14517 // built-in operator. In either case, fall through to trying to
14518 // build a built-in operation.
14519 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14520}
14521
14522/// Perform lookup for an overloaded binary operator.
14525 const UnresolvedSetImpl &Fns,
14526 ArrayRef<Expr *> Args, bool PerformADL) {
14527 SourceLocation OpLoc = CandidateSet.getLocation();
14528
14529 OverloadedOperatorKind ExtraOp =
14532 : OO_None;
14533
14534 // Add the candidates from the given function set. This also adds the
14535 // rewritten candidates using these functions if necessary.
14536 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14537
14538 // Add operator candidates that are member functions.
14539 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14540 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14541 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14543
14544 // In C++20, also add any rewritten member candidates.
14545 if (ExtraOp) {
14546 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14547 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14548 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14549 CandidateSet,
14551 }
14552
14553 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14554 // performed for an assignment operator (nor for operator[] nor operator->,
14555 // which don't get here).
14556 if (Op != OO_Equal && PerformADL) {
14558 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14559 /*ExplicitTemplateArgs*/ nullptr,
14560 CandidateSet);
14561 if (ExtraOp) {
14562 DeclarationName ExtraOpName =
14563 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14564 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14565 /*ExplicitTemplateArgs*/ nullptr,
14566 CandidateSet);
14567 }
14568 }
14569
14570 // Add builtin operator candidates.
14571 //
14572 // FIXME: We don't add any rewritten candidates here. This is strictly
14573 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14574 // resulting in our selecting a rewritten builtin candidate. For example:
14575 //
14576 // enum class E { e };
14577 // bool operator!=(E, E) requires false;
14578 // bool k = E::e != E::e;
14579 //
14580 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14581 // it seems unreasonable to consider rewritten builtin candidates. A core
14582 // issue has been filed proposing to removed this requirement.
14583 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14584}
14585
14586/// Create a binary operation that may resolve to an overloaded
14587/// operator.
14588///
14589/// \param OpLoc The location of the operator itself (e.g., '+').
14590///
14591/// \param Opc The BinaryOperatorKind that describes this operator.
14592///
14593/// \param Fns The set of non-member functions that will be
14594/// considered by overload resolution. The caller needs to build this
14595/// set based on the context using, e.g.,
14596/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14597/// set should not contain any member functions; those will be added
14598/// by CreateOverloadedBinOp().
14599///
14600/// \param LHS Left-hand argument.
14601/// \param RHS Right-hand argument.
14602/// \param PerformADL Whether to consider operator candidates found by ADL.
14603/// \param AllowRewrittenCandidates Whether to consider candidates found by
14604/// C++20 operator rewrites.
14605/// \param DefaultedFn If we are synthesizing a defaulted operator function,
14606/// the function in question. Such a function is never a candidate in
14607/// our overload resolution. This also enables synthesizing a three-way
14608/// comparison from < and == as described in C++20 [class.spaceship]p1.
14611 const UnresolvedSetImpl &Fns, Expr *LHS,
14612 Expr *RHS, bool PerformADL,
14613 bool AllowRewrittenCandidates,
14614 FunctionDecl *DefaultedFn) {
14615 Expr *Args[2] = { LHS, RHS };
14616 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14617
14618 if (!getLangOpts().CPlusPlus20)
14619 AllowRewrittenCandidates = false;
14620
14622
14623 // If either side is type-dependent, create an appropriate dependent
14624 // expression.
14625 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14626 if (Fns.empty()) {
14627 // If there are no functions to store, just build a dependent
14628 // BinaryOperator or CompoundAssignment.
14631 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14632 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14633 Context.DependentTy);
14635 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14636 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14637 }
14638
14639 // FIXME: save results of ADL from here?
14640 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14641 // TODO: provide better source location info in DNLoc component.
14643 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14644 ExprResult Fn = CreateUnresolvedLookupExpr(
14645 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14646 if (Fn.isInvalid())
14647 return ExprError();
14648 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14649 Context.DependentTy, VK_PRValue, OpLoc,
14650 CurFPFeatureOverrides());
14651 }
14652
14653 // If this is the .* operator, which is not overloadable, just
14654 // create a built-in binary operator.
14655 if (Opc == BO_PtrMemD) {
14656 auto CheckPlaceholder = [&](Expr *&Arg) {
14657 ExprResult Res = CheckPlaceholderExpr(Arg);
14658 if (Res.isUsable())
14659 Arg = Res.get();
14660 return !Res.isUsable();
14661 };
14662
14663 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14664 // expression that contains placeholders (in either the LHS or RHS).
14665 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14666 return ExprError();
14667 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14668 }
14669
14670 // Always do placeholder-like conversions on the RHS.
14671 if (checkPlaceholderForOverload(*this, Args[1]))
14672 return ExprError();
14673
14674 // Do placeholder-like conversion on the LHS; note that we should
14675 // not get here with a PseudoObject LHS.
14676 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14677 if (checkPlaceholderForOverload(*this, Args[0]))
14678 return ExprError();
14679
14680 // If this is the assignment operator, we only perform overload resolution
14681 // if the left-hand side is a class or enumeration type. This is actually
14682 // a hack. The standard requires that we do overload resolution between the
14683 // various built-in candidates, but as DR507 points out, this can lead to
14684 // problems. So we do it this way, which pretty much follows what GCC does.
14685 // Note that we go the traditional code path for compound assignment forms.
14686 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14687 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14688
14689 // Build the overload set.
14692 Op, OpLoc, AllowRewrittenCandidates));
14693 if (DefaultedFn)
14694 CandidateSet.exclude(DefaultedFn);
14695 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14696
14697 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14698
14699 // Perform overload resolution.
14701 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14702 case OR_Success: {
14703 // We found a built-in operator or an overloaded operator.
14704 FunctionDecl *FnDecl = Best->Function;
14705
14706 bool IsReversed = Best->isReversed();
14707 if (IsReversed)
14708 std::swap(Args[0], Args[1]);
14709
14710 if (FnDecl) {
14711
14712 if (FnDecl->isInvalidDecl())
14713 return ExprError();
14714
14715 Expr *Base = nullptr;
14716 // We matched an overloaded operator. Build a call to that
14717 // operator.
14718
14719 OverloadedOperatorKind ChosenOp =
14721
14722 // C++2a [over.match.oper]p9:
14723 // If a rewritten operator== candidate is selected by overload
14724 // resolution for an operator@, its return type shall be cv bool
14725 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14726 !FnDecl->getReturnType()->isBooleanType()) {
14727 bool IsExtension =
14729 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14730 : diag::err_ovl_rewrite_equalequal_not_bool)
14731 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14732 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14733 Diag(FnDecl->getLocation(), diag::note_declared_at);
14734 if (!IsExtension)
14735 return ExprError();
14736 }
14737
14738 if (AllowRewrittenCandidates && !IsReversed &&
14739 CandidateSet.getRewriteInfo().isReversible()) {
14740 // We could have reversed this operator, but didn't. Check if some
14741 // reversed form was a viable candidate, and if so, if it had a
14742 // better conversion for either parameter. If so, this call is
14743 // formally ambiguous, and allowing it is an extension.
14745 for (OverloadCandidate &Cand : CandidateSet) {
14746 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14747 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14748 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14750 *this, OpLoc, Cand.Conversions[ArgIdx],
14751 Best->Conversions[ArgIdx]) ==
14753 AmbiguousWith.push_back(Cand.Function);
14754 break;
14755 }
14756 }
14757 }
14758 }
14759
14760 if (!AmbiguousWith.empty()) {
14761 bool AmbiguousWithSelf =
14762 AmbiguousWith.size() == 1 &&
14763 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14764 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14766 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14767 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14768 if (AmbiguousWithSelf) {
14769 Diag(FnDecl->getLocation(),
14770 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14771 // Mark member== const or provide matching != to disallow reversed
14772 // args. Eg.
14773 // struct S { bool operator==(const S&); };
14774 // S()==S();
14775 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14776 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14777 !MD->isConst() &&
14778 !MD->hasCXXExplicitFunctionObjectParameter() &&
14779 Context.hasSameUnqualifiedType(
14780 MD->getFunctionObjectParameterType(),
14781 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14782 Context.hasSameUnqualifiedType(
14783 MD->getFunctionObjectParameterType(),
14784 Args[0]->getType()) &&
14785 Context.hasSameUnqualifiedType(
14786 MD->getFunctionObjectParameterType(),
14787 Args[1]->getType()))
14788 Diag(FnDecl->getLocation(),
14789 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14790 } else {
14791 Diag(FnDecl->getLocation(),
14792 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14793 for (auto *F : AmbiguousWith)
14794 Diag(F->getLocation(),
14795 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14796 }
14797 }
14798 }
14799
14800 // Convert the arguments.
14801 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14802 // Best->Access is only meaningful for class members.
14803 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14804
14805 ExprResult Arg0, Arg1;
14806 unsigned ParamIdx = 0;
14807 if (Method->isExplicitObjectMemberFunction()) {
14808 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14809 ParamIdx = 1;
14810 } else {
14811 Arg0 = PerformImplicitObjectArgumentInitialization(
14812 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14813 }
14814 Arg1 = PerformCopyInitialization(
14816 Context, FnDecl->getParamDecl(ParamIdx)),
14817 SourceLocation(), Args[1]);
14818 if (Arg0.isInvalid() || Arg1.isInvalid())
14819 return ExprError();
14820
14821 Base = Args[0] = Arg0.getAs<Expr>();
14822 Args[1] = RHS = Arg1.getAs<Expr>();
14823 } else {
14824 // Convert the arguments.
14825 ExprResult Arg0 = PerformCopyInitialization(
14827 FnDecl->getParamDecl(0)),
14828 SourceLocation(), Args[0]);
14829 if (Arg0.isInvalid())
14830 return ExprError();
14831
14832 ExprResult Arg1 =
14833 PerformCopyInitialization(
14835 FnDecl->getParamDecl(1)),
14836 SourceLocation(), Args[1]);
14837 if (Arg1.isInvalid())
14838 return ExprError();
14839 Args[0] = LHS = Arg0.getAs<Expr>();
14840 Args[1] = RHS = Arg1.getAs<Expr>();
14841 }
14842
14843 // Build the actual expression node.
14844 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14845 Best->FoundDecl, Base,
14846 HadMultipleCandidates, OpLoc);
14847 if (FnExpr.isInvalid())
14848 return ExprError();
14849
14850 // Determine the result type.
14851 QualType ResultTy = FnDecl->getReturnType();
14853 ResultTy = ResultTy.getNonLValueExprType(Context);
14854
14855 CallExpr *TheCall;
14856 ArrayRef<const Expr *> ArgsArray(Args, 2);
14857 const Expr *ImplicitThis = nullptr;
14858
14859 // We always create a CXXOperatorCallExpr, even for explicit object
14860 // members; CodeGen should take care not to emit the this pointer.
14862 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14863 CurFPFeatureOverrides(), Best->IsADLCandidate);
14864
14865 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14866 Method && Method->isImplicitObjectMemberFunction()) {
14867 // Cut off the implicit 'this'.
14868 ImplicitThis = ArgsArray[0];
14869 ArgsArray = ArgsArray.slice(1);
14870 }
14871
14872 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14873 FnDecl))
14874 return ExprError();
14875
14876 // Check for a self move.
14877 if (Op == OO_Equal)
14878 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14879
14880 if (ImplicitThis) {
14881 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14882 QualType ThisTypeFromDecl = Context.getPointerType(
14883 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14884
14885 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14886 ThisTypeFromDecl);
14887 }
14888
14889 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14890 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14891 VariadicDoesNotApply);
14892
14893 ExprResult R = MaybeBindToTemporary(TheCall);
14894 if (R.isInvalid())
14895 return ExprError();
14896
14897 R = CheckForImmediateInvocation(R, FnDecl);
14898 if (R.isInvalid())
14899 return ExprError();
14900
14901 // For a rewritten candidate, we've already reversed the arguments
14902 // if needed. Perform the rest of the rewrite now.
14903 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14904 (Op == OO_Spaceship && IsReversed)) {
14905 if (Op == OO_ExclaimEqual) {
14906 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14907 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14908 } else {
14909 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14910 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14911 Expr *ZeroLiteral =
14912 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14913
14916 Ctx.Entity = FnDecl;
14917 pushCodeSynthesisContext(Ctx);
14918
14919 R = CreateOverloadedBinOp(
14920 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14921 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14922 /*AllowRewrittenCandidates=*/false);
14923
14924 popCodeSynthesisContext();
14925 }
14926 if (R.isInvalid())
14927 return ExprError();
14928 } else {
14929 assert(ChosenOp == Op && "unexpected operator name");
14930 }
14931
14932 // Make a note in the AST if we did any rewriting.
14933 if (Best->RewriteKind != CRK_None)
14934 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14935
14936 return R;
14937 } else {
14938 // We matched a built-in operator. Convert the arguments, then
14939 // break out so that we will build the appropriate built-in
14940 // operator node.
14941 ExprResult ArgsRes0 = PerformImplicitConversion(
14942 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14943 AA_Passing, CCK_ForBuiltinOverloadedOp);
14944 if (ArgsRes0.isInvalid())
14945 return ExprError();
14946 Args[0] = ArgsRes0.get();
14947
14948 ExprResult ArgsRes1 = PerformImplicitConversion(
14949 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14950 AA_Passing, CCK_ForBuiltinOverloadedOp);
14951 if (ArgsRes1.isInvalid())
14952 return ExprError();
14953 Args[1] = ArgsRes1.get();
14954 break;
14955 }
14956 }
14957
14958 case OR_No_Viable_Function: {
14959 // C++ [over.match.oper]p9:
14960 // If the operator is the operator , [...] and there are no
14961 // viable functions, then the operator is assumed to be the
14962 // built-in operator and interpreted according to clause 5.
14963 if (Opc == BO_Comma)
14964 break;
14965
14966 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14967 // compare result using '==' and '<'.
14968 if (DefaultedFn && Opc == BO_Cmp) {
14969 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14970 Args[1], DefaultedFn);
14971 if (E.isInvalid() || E.isUsable())
14972 return E;
14973 }
14974
14975 // For class as left operand for assignment or compound assignment
14976 // operator do not fall through to handling in built-in, but report that
14977 // no overloaded assignment operator found
14979 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14980 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14981 Args, OpLoc);
14982 DeferDiagsRAII DDR(*this,
14983 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14984 if (Args[0]->getType()->isRecordType() &&
14985 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14986 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14988 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14989 if (Args[0]->getType()->isIncompleteType()) {
14990 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14991 << Args[0]->getType()
14992 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14993 }
14994 } else {
14995 // This is an erroneous use of an operator which can be overloaded by
14996 // a non-member function. Check for non-member operators which were
14997 // defined too late to be candidates.
14998 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14999 // FIXME: Recover by calling the found function.
15000 return ExprError();
15001
15002 // No viable function; try to create a built-in operation, which will
15003 // produce an error. Then, show the non-viable candidates.
15004 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15005 }
15006 assert(Result.isInvalid() &&
15007 "C++ binary operator overloading is missing candidates!");
15008 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15009 return Result;
15010 }
15011
15012 case OR_Ambiguous:
15013 CandidateSet.NoteCandidates(
15014 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15016 << Args[0]->getType()
15017 << Args[1]->getType()
15018 << Args[0]->getSourceRange()
15019 << Args[1]->getSourceRange()),
15021 OpLoc);
15022 return ExprError();
15023
15024 case OR_Deleted:
15025 if (isImplicitlyDeleted(Best->Function)) {
15026 FunctionDecl *DeletedFD = Best->Function;
15027 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15028 if (DFK.isSpecialMember()) {
15029 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15030 << Args[0]->getType() << DFK.asSpecialMember();
15031 } else {
15032 assert(DFK.isComparison());
15033 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15034 << Args[0]->getType() << DeletedFD;
15035 }
15036
15037 // The user probably meant to call this special member. Just
15038 // explain why it's deleted.
15039 NoteDeletedFunction(DeletedFD);
15040 return ExprError();
15041 }
15042 CandidateSet.NoteCandidates(
15044 OpLoc, PDiag(diag::err_ovl_deleted_oper)
15045 << getOperatorSpelling(Best->Function->getDeclName()
15046 .getCXXOverloadedOperator())
15047 << Args[0]->getSourceRange()
15048 << Args[1]->getSourceRange()),
15050 OpLoc);
15051 return ExprError();
15052 }
15053
15054 // We matched a built-in operator; build it.
15055 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15056}
15057
15059 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15060 FunctionDecl *DefaultedFn) {
15061 const ComparisonCategoryInfo *Info =
15062 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15063 // If we're not producing a known comparison category type, we can't
15064 // synthesize a three-way comparison. Let the caller diagnose this.
15065 if (!Info)
15066 return ExprResult((Expr*)nullptr);
15067
15068 // If we ever want to perform this synthesis more generally, we will need to
15069 // apply the temporary materialization conversion to the operands.
15070 assert(LHS->isGLValue() && RHS->isGLValue() &&
15071 "cannot use prvalue expressions more than once");
15072 Expr *OrigLHS = LHS;
15073 Expr *OrigRHS = RHS;
15074
15075 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15076 // each of them multiple times below.
15077 LHS = new (Context)
15078 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15079 LHS->getObjectKind(), LHS);
15080 RHS = new (Context)
15081 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15082 RHS->getObjectKind(), RHS);
15083
15084 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15085 DefaultedFn);
15086 if (Eq.isInvalid())
15087 return ExprError();
15088
15089 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15090 true, DefaultedFn);
15091 if (Less.isInvalid())
15092 return ExprError();
15093
15095 if (Info->isPartial()) {
15096 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15097 DefaultedFn);
15098 if (Greater.isInvalid())
15099 return ExprError();
15100 }
15101
15102 // Form the list of comparisons we're going to perform.
15103 struct Comparison {
15104 ExprResult Cmp;
15106 } Comparisons[4] =
15112 };
15113
15114 int I = Info->isPartial() ? 3 : 2;
15115
15116 // Combine the comparisons with suitable conditional expressions.
15118 for (; I >= 0; --I) {
15119 // Build a reference to the comparison category constant.
15120 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15121 // FIXME: Missing a constant for a comparison category. Diagnose this?
15122 if (!VI)
15123 return ExprResult((Expr*)nullptr);
15124 ExprResult ThisResult =
15125 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15126 if (ThisResult.isInvalid())
15127 return ExprError();
15128
15129 // Build a conditional unless this is the final case.
15130 if (Result.get()) {
15131 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15132 ThisResult.get(), Result.get());
15133 if (Result.isInvalid())
15134 return ExprError();
15135 } else {
15136 Result = ThisResult;
15137 }
15138 }
15139
15140 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15141 // bind the OpaqueValueExprs before they're (repeatedly) used.
15142 Expr *SyntacticForm = BinaryOperator::Create(
15143 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15144 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15145 CurFPFeatureOverrides());
15146 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15147 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15148}
15149
15151 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15152 MultiExprArg Args, SourceLocation LParenLoc) {
15153
15154 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15155 unsigned NumParams = Proto->getNumParams();
15156 unsigned NumArgsSlots =
15157 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15158 // Build the full argument list for the method call (the implicit object
15159 // parameter is placed at the beginning of the list).
15160 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15161 bool IsError = false;
15162 // Initialize the implicit object parameter.
15163 // Check the argument types.
15164 for (unsigned i = 0; i != NumParams; i++) {
15165 Expr *Arg;
15166 if (i < Args.size()) {
15167 Arg = Args[i];
15168 ExprResult InputInit =
15170 S.Context, Method->getParamDecl(i)),
15171 SourceLocation(), Arg);
15172 IsError |= InputInit.isInvalid();
15173 Arg = InputInit.getAs<Expr>();
15174 } else {
15175 ExprResult DefArg =
15176 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15177 if (DefArg.isInvalid()) {
15178 IsError = true;
15179 break;
15180 }
15181 Arg = DefArg.getAs<Expr>();
15182 }
15183
15184 MethodArgs.push_back(Arg);
15185 }
15186 return IsError;
15187}
15188
15190 SourceLocation RLoc,
15191 Expr *Base,
15192 MultiExprArg ArgExpr) {
15194 Args.push_back(Base);
15195 for (auto *e : ArgExpr) {
15196 Args.push_back(e);
15197 }
15198 DeclarationName OpName =
15199 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15200
15201 SourceRange Range = ArgExpr.empty()
15202 ? SourceRange{}
15203 : SourceRange(ArgExpr.front()->getBeginLoc(),
15204 ArgExpr.back()->getEndLoc());
15205
15206 // If either side is type-dependent, create an appropriate dependent
15207 // expression.
15209
15210 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15211 // CHECKME: no 'operator' keyword?
15212 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15213 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15214 ExprResult Fn = CreateUnresolvedLookupExpr(
15215 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15216 if (Fn.isInvalid())
15217 return ExprError();
15218 // Can't add any actual overloads yet
15219
15220 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15221 Context.DependentTy, VK_PRValue, RLoc,
15222 CurFPFeatureOverrides());
15223 }
15224
15225 // Handle placeholders
15226 UnbridgedCastsSet UnbridgedCasts;
15227 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15228 return ExprError();
15229 }
15230 // Build an empty overload set.
15232
15233 // Subscript can only be overloaded as a member function.
15234
15235 // Add operator candidates that are member functions.
15236 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15237
15238 // Add builtin operator candidates.
15239 if (Args.size() == 2)
15240 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15241
15242 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15243
15244 // Perform overload resolution.
15246 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15247 case OR_Success: {
15248 // We found a built-in operator or an overloaded operator.
15249 FunctionDecl *FnDecl = Best->Function;
15250
15251 if (FnDecl) {
15252 // We matched an overloaded operator. Build a call to that
15253 // operator.
15254
15255 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15256
15257 // Convert the arguments.
15258 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15259 SmallVector<Expr *, 2> MethodArgs;
15260
15261 // Initialize the object parameter.
15262 if (Method->isExplicitObjectMemberFunction()) {
15263 ExprResult Res =
15264 InitializeExplicitObjectArgument(*this, Args[0], Method);
15265 if (Res.isInvalid())
15266 return ExprError();
15267 Args[0] = Res.get();
15268 ArgExpr = Args;
15269 } else {
15270 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15271 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15272 if (Arg0.isInvalid())
15273 return ExprError();
15274
15275 MethodArgs.push_back(Arg0.get());
15276 }
15277
15279 *this, MethodArgs, Method, ArgExpr, LLoc);
15280 if (IsError)
15281 return ExprError();
15282
15283 // Build the actual expression node.
15284 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15285 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15287 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15288 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15289 if (FnExpr.isInvalid())
15290 return ExprError();
15291
15292 // Determine the result type
15293 QualType ResultTy = FnDecl->getReturnType();
15295 ResultTy = ResultTy.getNonLValueExprType(Context);
15296
15298 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15299 CurFPFeatureOverrides());
15300
15301 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15302 return ExprError();
15303
15304 if (CheckFunctionCall(Method, TheCall,
15305 Method->getType()->castAs<FunctionProtoType>()))
15306 return ExprError();
15307
15308 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15309 FnDecl);
15310 } else {
15311 // We matched a built-in operator. Convert the arguments, then
15312 // break out so that we will build the appropriate built-in
15313 // operator node.
15314 ExprResult ArgsRes0 = PerformImplicitConversion(
15315 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15316 AA_Passing, CCK_ForBuiltinOverloadedOp);
15317 if (ArgsRes0.isInvalid())
15318 return ExprError();
15319 Args[0] = ArgsRes0.get();
15320
15321 ExprResult ArgsRes1 = PerformImplicitConversion(
15322 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15323 AA_Passing, CCK_ForBuiltinOverloadedOp);
15324 if (ArgsRes1.isInvalid())
15325 return ExprError();
15326 Args[1] = ArgsRes1.get();
15327
15328 break;
15329 }
15330 }
15331
15332 case OR_No_Viable_Function: {
15334 CandidateSet.empty()
15335 ? (PDiag(diag::err_ovl_no_oper)
15336 << Args[0]->getType() << /*subscript*/ 0
15337 << Args[0]->getSourceRange() << Range)
15338 : (PDiag(diag::err_ovl_no_viable_subscript)
15339 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15340 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15341 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15342 return ExprError();
15343 }
15344
15345 case OR_Ambiguous:
15346 if (Args.size() == 2) {
15347 CandidateSet.NoteCandidates(
15349 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15350 << "[]" << Args[0]->getType() << Args[1]->getType()
15351 << Args[0]->getSourceRange() << Range),
15352 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15353 } else {
15354 CandidateSet.NoteCandidates(
15356 PDiag(diag::err_ovl_ambiguous_subscript_call)
15357 << Args[0]->getType()
15358 << Args[0]->getSourceRange() << Range),
15359 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15360 }
15361 return ExprError();
15362
15363 case OR_Deleted:
15364 CandidateSet.NoteCandidates(
15365 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
15366 << "[]" << Args[0]->getSourceRange()
15367 << Range),
15368 *this, OCD_AllCandidates, Args, "[]", LLoc);
15369 return ExprError();
15370 }
15371
15372 // We matched a built-in operator; build it.
15373 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15374}
15375
15376/// BuildCallToMemberFunction - Build a call to a member
15377/// function. MemExpr is the expression that refers to the member
15378/// function (and includes the object parameter), Args/NumArgs are the
15379/// arguments to the function call (not including the object
15380/// parameter). The caller needs to validate that the member
15381/// expression refers to a non-static member function or an overloaded
15382/// member function.
15384 SourceLocation LParenLoc,
15385 MultiExprArg Args,
15386 SourceLocation RParenLoc,
15387 Expr *ExecConfig, bool IsExecConfig,
15388 bool AllowRecovery) {
15389 assert(MemExprE->getType() == Context.BoundMemberTy ||
15390 MemExprE->getType() == Context.OverloadTy);
15391
15392 // Dig out the member expression. This holds both the object
15393 // argument and the member function we're referring to.
15394 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15395
15396 // Determine whether this is a call to a pointer-to-member function.
15397 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15398 assert(op->getType() == Context.BoundMemberTy);
15399 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15400
15401 QualType fnType =
15402 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15403
15404 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15405 QualType resultType = proto->getCallResultType(Context);
15407
15408 // Check that the object type isn't more qualified than the
15409 // member function we're calling.
15410 Qualifiers funcQuals = proto->getMethodQuals();
15411
15412 QualType objectType = op->getLHS()->getType();
15413 if (op->getOpcode() == BO_PtrMemI)
15414 objectType = objectType->castAs<PointerType>()->getPointeeType();
15415 Qualifiers objectQuals = objectType.getQualifiers();
15416
15417 Qualifiers difference = objectQuals - funcQuals;
15418 difference.removeObjCGCAttr();
15419 difference.removeAddressSpace();
15420 if (difference) {
15421 std::string qualsString = difference.getAsString();
15422 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15423 << fnType.getUnqualifiedType()
15424 << qualsString
15425 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15426 }
15427
15429 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15430 CurFPFeatureOverrides(), proto->getNumParams());
15431
15432 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15433 call, nullptr))
15434 return ExprError();
15435
15436 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15437 return ExprError();
15438
15439 if (CheckOtherCall(call, proto))
15440 return ExprError();
15441
15442 return MaybeBindToTemporary(call);
15443 }
15444
15445 // We only try to build a recovery expr at this level if we can preserve
15446 // the return type, otherwise we return ExprError() and let the caller
15447 // recover.
15448 auto BuildRecoveryExpr = [&](QualType Type) {
15449 if (!AllowRecovery)
15450 return ExprError();
15451 std::vector<Expr *> SubExprs = {MemExprE};
15452 llvm::append_range(SubExprs, Args);
15453 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15454 Type);
15455 };
15456 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15457 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15458 RParenLoc, CurFPFeatureOverrides());
15459
15460 UnbridgedCastsSet UnbridgedCasts;
15461 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15462 return ExprError();
15463
15464 MemberExpr *MemExpr;
15465 CXXMethodDecl *Method = nullptr;
15466 bool HadMultipleCandidates = false;
15467 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15468 NestedNameSpecifier *Qualifier = nullptr;
15469 if (isa<MemberExpr>(NakedMemExpr)) {
15470 MemExpr = cast<MemberExpr>(NakedMemExpr);
15471 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15472 FoundDecl = MemExpr->getFoundDecl();
15473 Qualifier = MemExpr->getQualifier();
15474 UnbridgedCasts.restore();
15475 } else {
15476 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15477 Qualifier = UnresExpr->getQualifier();
15478
15479 QualType ObjectType = UnresExpr->getBaseType();
15480 Expr::Classification ObjectClassification
15482 : UnresExpr->getBase()->Classify(Context);
15483
15484 // Add overload candidates
15485 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15487
15488 // FIXME: avoid copy.
15489 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15490 if (UnresExpr->hasExplicitTemplateArgs()) {
15491 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15492 TemplateArgs = &TemplateArgsBuffer;
15493 }
15494
15496 E = UnresExpr->decls_end(); I != E; ++I) {
15497
15498 QualType ExplicitObjectType = ObjectType;
15499
15500 NamedDecl *Func = *I;
15501 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15502 if (isa<UsingShadowDecl>(Func))
15503 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15504
15505 bool HasExplicitParameter = false;
15506 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15507 M && M->hasCXXExplicitFunctionObjectParameter())
15508 HasExplicitParameter = true;
15509 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15510 M &&
15511 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15512 HasExplicitParameter = true;
15513
15514 if (HasExplicitParameter)
15515 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15516
15517 // Microsoft supports direct constructor calls.
15518 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15519 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15520 CandidateSet,
15521 /*SuppressUserConversions*/ false);
15522 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15523 // If explicit template arguments were provided, we can't call a
15524 // non-template member function.
15525 if (TemplateArgs)
15526 continue;
15527
15528 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15529 ObjectClassification, Args, CandidateSet,
15530 /*SuppressUserConversions=*/false);
15531 } else {
15532 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15533 I.getPair(), ActingDC, TemplateArgs,
15534 ExplicitObjectType, ObjectClassification,
15535 Args, CandidateSet,
15536 /*SuppressUserConversions=*/false);
15537 }
15538 }
15539
15540 HadMultipleCandidates = (CandidateSet.size() > 1);
15541
15542 DeclarationName DeclName = UnresExpr->getMemberName();
15543
15544 UnbridgedCasts.restore();
15545
15547 bool Succeeded = false;
15548 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15549 Best)) {
15550 case OR_Success:
15551 Method = cast<CXXMethodDecl>(Best->Function);
15552 FoundDecl = Best->FoundDecl;
15553 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15554 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15555 break;
15556 // If FoundDecl is different from Method (such as if one is a template
15557 // and the other a specialization), make sure DiagnoseUseOfDecl is
15558 // called on both.
15559 // FIXME: This would be more comprehensively addressed by modifying
15560 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15561 // being used.
15562 if (Method != FoundDecl.getDecl() &&
15563 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15564 break;
15565 Succeeded = true;
15566 break;
15567
15569 CandidateSet.NoteCandidates(
15571 UnresExpr->getMemberLoc(),
15572 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15573 << DeclName << MemExprE->getSourceRange()),
15574 *this, OCD_AllCandidates, Args);
15575 break;
15576 case OR_Ambiguous:
15577 CandidateSet.NoteCandidates(
15578 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15579 PDiag(diag::err_ovl_ambiguous_member_call)
15580 << DeclName << MemExprE->getSourceRange()),
15581 *this, OCD_AmbiguousCandidates, Args);
15582 break;
15583 case OR_Deleted:
15584 CandidateSet.NoteCandidates(
15585 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15586 PDiag(diag::err_ovl_deleted_member_call)
15587 << DeclName << MemExprE->getSourceRange()),
15588 *this, OCD_AllCandidates, Args);
15589 break;
15590 }
15591 // Overload resolution fails, try to recover.
15592 if (!Succeeded)
15593 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15594
15595 ExprResult Res =
15596 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15597 if (Res.isInvalid())
15598 return ExprError();
15599 MemExprE = Res.get();
15600
15601 // If overload resolution picked a static member
15602 // build a non-member call based on that function.
15603 if (Method->isStatic()) {
15604 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15605 ExecConfig, IsExecConfig);
15606 }
15607
15608 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15609 }
15610
15611 QualType ResultType = Method->getReturnType();
15613 ResultType = ResultType.getNonLValueExprType(Context);
15614
15615 assert(Method && "Member call to something that isn't a method?");
15616 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15617
15618 CallExpr *TheCall = nullptr;
15620 if (Method->isExplicitObjectMemberFunction()) {
15621 PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15622 NewArgs);
15623 // Build the actual expression node.
15624 ExprResult FnExpr =
15625 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15626 HadMultipleCandidates, MemExpr->getExprLoc());
15627 if (FnExpr.isInvalid())
15628 return ExprError();
15629
15630 TheCall =
15631 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15632 CurFPFeatureOverrides(), Proto->getNumParams());
15633 } else {
15634 // Convert the object argument (for a non-static member function call).
15635 // We only need to do this if there was actually an overload; otherwise
15636 // it was done at lookup.
15637 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15638 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15639 if (ObjectArg.isInvalid())
15640 return ExprError();
15641 MemExpr->setBase(ObjectArg.get());
15642 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15643 RParenLoc, CurFPFeatureOverrides(),
15644 Proto->getNumParams());
15645 }
15646
15647 // Check for a valid return type.
15648 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15649 TheCall, Method))
15650 return BuildRecoveryExpr(ResultType);
15651
15652 // Convert the rest of the arguments
15653 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15654 RParenLoc))
15655 return BuildRecoveryExpr(ResultType);
15656
15657 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15658
15659 if (CheckFunctionCall(Method, TheCall, Proto))
15660 return ExprError();
15661
15662 // In the case the method to call was not selected by the overloading
15663 // resolution process, we still need to handle the enable_if attribute. Do
15664 // that here, so it will not hide previous -- and more relevant -- errors.
15665 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15666 if (const EnableIfAttr *Attr =
15667 CheckEnableIf(Method, LParenLoc, Args, true)) {
15668 Diag(MemE->getMemberLoc(),
15669 diag::err_ovl_no_viable_member_function_in_call)
15670 << Method << Method->getSourceRange();
15671 Diag(Method->getLocation(),
15672 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15673 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15674 return ExprError();
15675 }
15676 }
15677
15678 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15679 TheCall->getDirectCallee()->isPureVirtual()) {
15680 const FunctionDecl *MD = TheCall->getDirectCallee();
15681
15682 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15683 MemExpr->performsVirtualDispatch(getLangOpts())) {
15684 Diag(MemExpr->getBeginLoc(),
15685 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15686 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15687 << MD->getParent();
15688
15689 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15690 if (getLangOpts().AppleKext)
15691 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15692 << MD->getParent() << MD->getDeclName();
15693 }
15694 }
15695
15696 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15697 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15698 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15699 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15700 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15701 MemExpr->getMemberLoc());
15702 }
15703
15704 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15705 TheCall->getDirectCallee());
15706}
15707
15708/// BuildCallToObjectOfClassType - Build a call to an object of class
15709/// type (C++ [over.call.object]), which can end up invoking an
15710/// overloaded function call operator (@c operator()) or performing a
15711/// user-defined conversion on the object argument.
15714 SourceLocation LParenLoc,
15715 MultiExprArg Args,
15716 SourceLocation RParenLoc) {
15717 if (checkPlaceholderForOverload(*this, Obj))
15718 return ExprError();
15719 ExprResult Object = Obj;
15720
15721 UnbridgedCastsSet UnbridgedCasts;
15722 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15723 return ExprError();
15724
15725 assert(Object.get()->getType()->isRecordType() &&
15726 "Requires object type argument");
15727
15728 // C++ [over.call.object]p1:
15729 // If the primary-expression E in the function call syntax
15730 // evaluates to a class object of type "cv T", then the set of
15731 // candidate functions includes at least the function call
15732 // operators of T. The function call operators of T are obtained by
15733 // ordinary lookup of the name operator() in the context of
15734 // (E).operator().
15735 OverloadCandidateSet CandidateSet(LParenLoc,
15737 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15738
15739 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15740 diag::err_incomplete_object_call, Object.get()))
15741 return true;
15742
15743 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15744 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15745 LookupQualifiedName(R, Record->getDecl());
15746 R.suppressAccessDiagnostics();
15747
15748 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15749 Oper != OperEnd; ++Oper) {
15750 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15751 Object.get()->Classify(Context), Args, CandidateSet,
15752 /*SuppressUserConversion=*/false);
15753 }
15754
15755 // When calling a lambda, both the call operator, and
15756 // the conversion operator to function pointer
15757 // are considered. But when constraint checking
15758 // on the call operator fails, it will also fail on the
15759 // conversion operator as the constraints are always the same.
15760 // As the user probably does not intend to perform a surrogate call,
15761 // we filter them out to produce better error diagnostics, ie to avoid
15762 // showing 2 failed overloads instead of one.
15763 bool IgnoreSurrogateFunctions = false;
15764 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15765 const OverloadCandidate &Candidate = *CandidateSet.begin();
15766 if (!Candidate.Viable &&
15768 IgnoreSurrogateFunctions = true;
15769 }
15770
15771 // C++ [over.call.object]p2:
15772 // In addition, for each (non-explicit in C++0x) conversion function
15773 // declared in T of the form
15774 //
15775 // operator conversion-type-id () cv-qualifier;
15776 //
15777 // where cv-qualifier is the same cv-qualification as, or a
15778 // greater cv-qualification than, cv, and where conversion-type-id
15779 // denotes the type "pointer to function of (P1,...,Pn) returning
15780 // R", or the type "reference to pointer to function of
15781 // (P1,...,Pn) returning R", or the type "reference to function
15782 // of (P1,...,Pn) returning R", a surrogate call function [...]
15783 // is also considered as a candidate function. Similarly,
15784 // surrogate call functions are added to the set of candidate
15785 // functions for each conversion function declared in an
15786 // accessible base class provided the function is not hidden
15787 // within T by another intervening declaration.
15788 const auto &Conversions =
15789 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15790 for (auto I = Conversions.begin(), E = Conversions.end();
15791 !IgnoreSurrogateFunctions && I != E; ++I) {
15792 NamedDecl *D = *I;
15793 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15794 if (isa<UsingShadowDecl>(D))
15795 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15796
15797 // Skip over templated conversion functions; they aren't
15798 // surrogates.
15799 if (isa<FunctionTemplateDecl>(D))
15800 continue;
15801
15802 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15803 if (!Conv->isExplicit()) {
15804 // Strip the reference type (if any) and then the pointer type (if
15805 // any) to get down to what might be a function type.
15806 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15807 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15808 ConvType = ConvPtrType->getPointeeType();
15809
15810 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15811 {
15812 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15813 Object.get(), Args, CandidateSet);
15814 }
15815 }
15816 }
15817
15818 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15819
15820 // Perform overload resolution.
15822 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15823 Best)) {
15824 case OR_Success:
15825 // Overload resolution succeeded; we'll build the appropriate call
15826 // below.
15827 break;
15828
15829 case OR_No_Viable_Function: {
15831 CandidateSet.empty()
15832 ? (PDiag(diag::err_ovl_no_oper)
15833 << Object.get()->getType() << /*call*/ 1
15834 << Object.get()->getSourceRange())
15835 : (PDiag(diag::err_ovl_no_viable_object_call)
15836 << Object.get()->getType() << Object.get()->getSourceRange());
15837 CandidateSet.NoteCandidates(
15838 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15839 OCD_AllCandidates, Args);
15840 break;
15841 }
15842 case OR_Ambiguous:
15843 if (!R.isAmbiguous())
15844 CandidateSet.NoteCandidates(
15845 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15846 PDiag(diag::err_ovl_ambiguous_object_call)
15847 << Object.get()->getType()
15848 << Object.get()->getSourceRange()),
15849 *this, OCD_AmbiguousCandidates, Args);
15850 break;
15851
15852 case OR_Deleted:
15853 CandidateSet.NoteCandidates(
15854 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15855 PDiag(diag::err_ovl_deleted_object_call)
15856 << Object.get()->getType()
15857 << Object.get()->getSourceRange()),
15858 *this, OCD_AllCandidates, Args);
15859 break;
15860 }
15861
15862 if (Best == CandidateSet.end())
15863 return true;
15864
15865 UnbridgedCasts.restore();
15866
15867 if (Best->Function == nullptr) {
15868 // Since there is no function declaration, this is one of the
15869 // surrogate candidates. Dig out the conversion function.
15870 CXXConversionDecl *Conv
15871 = cast<CXXConversionDecl>(
15872 Best->Conversions[0].UserDefined.ConversionFunction);
15873
15874 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15875 Best->FoundDecl);
15876 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15877 return ExprError();
15878 assert(Conv == Best->FoundDecl.getDecl() &&
15879 "Found Decl & conversion-to-functionptr should be same, right?!");
15880 // We selected one of the surrogate functions that converts the
15881 // object parameter to a function pointer. Perform the conversion
15882 // on the object argument, then let BuildCallExpr finish the job.
15883
15884 // Create an implicit member expr to refer to the conversion operator.
15885 // and then call it.
15886 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15887 Conv, HadMultipleCandidates);
15888 if (Call.isInvalid())
15889 return ExprError();
15890 // Record usage of conversion in an implicit cast.
15892 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15893 nullptr, VK_PRValue, CurFPFeatureOverrides());
15894
15895 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15896 }
15897
15898 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15899
15900 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15901 // that calls this method, using Object for the implicit object
15902 // parameter and passing along the remaining arguments.
15903 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15904
15905 // An error diagnostic has already been printed when parsing the declaration.
15906 if (Method->isInvalidDecl())
15907 return ExprError();
15908
15909 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15910 unsigned NumParams = Proto->getNumParams();
15911
15912 DeclarationNameInfo OpLocInfo(
15913 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15914 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15915 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15916 Obj, HadMultipleCandidates,
15917 OpLocInfo.getLoc(),
15918 OpLocInfo.getInfo());
15919 if (NewFn.isInvalid())
15920 return true;
15921
15922 SmallVector<Expr *, 8> MethodArgs;
15923 MethodArgs.reserve(NumParams + 1);
15924
15925 bool IsError = false;
15926
15927 // Initialize the object parameter.
15929 if (Method->isExplicitObjectMemberFunction()) {
15930 // FIXME: we should do that during the definition of the lambda when we can.
15931 DiagnoseInvalidExplicitObjectParameterInLambda(Method);
15932 PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15933 } else {
15934 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15935 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15936 if (ObjRes.isInvalid())
15937 IsError = true;
15938 else
15939 Object = ObjRes;
15940 MethodArgs.push_back(Object.get());
15941 }
15942
15944 *this, MethodArgs, Method, Args, LParenLoc);
15945
15946 // If this is a variadic call, handle args passed through "...".
15947 if (Proto->isVariadic()) {
15948 // Promote the arguments (C99 6.5.2.2p7).
15949 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15950 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15951 nullptr);
15952 IsError |= Arg.isInvalid();
15953 MethodArgs.push_back(Arg.get());
15954 }
15955 }
15956
15957 if (IsError)
15958 return true;
15959
15960 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15961
15962 // Once we've built TheCall, all of the expressions are properly owned.
15963 QualType ResultTy = Method->getReturnType();
15965 ResultTy = ResultTy.getNonLValueExprType(Context);
15966
15968 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15969 CurFPFeatureOverrides());
15970
15971 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15972 return true;
15973
15974 if (CheckFunctionCall(Method, TheCall, Proto))
15975 return true;
15976
15977 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15978}
15979
15980/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15981/// (if one exists), where @c Base is an expression of class type and
15982/// @c Member is the name of the member we're trying to find.
15985 bool *NoArrowOperatorFound) {
15986 assert(Base->getType()->isRecordType() &&
15987 "left-hand side must have class type");
15988
15990 return ExprError();
15991
15992 SourceLocation Loc = Base->getExprLoc();
15993
15994 // C++ [over.ref]p1:
15995 //
15996 // [...] An expression x->m is interpreted as (x.operator->())->m
15997 // for a class object x of type T if T::operator->() exists and if
15998 // the operator is selected as the best match function by the
15999 // overload resolution mechanism (13.3).
16000 DeclarationName OpName =
16001 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16003
16004 if (RequireCompleteType(Loc, Base->getType(),
16005 diag::err_typecheck_incomplete_tag, Base))
16006 return ExprError();
16007
16008 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16009 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16011
16012 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16013 Oper != OperEnd; ++Oper) {
16014 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16015 std::nullopt, CandidateSet,
16016 /*SuppressUserConversion=*/false);
16017 }
16018
16019 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16020
16021 // Perform overload resolution.
16023 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16024 case OR_Success:
16025 // Overload resolution succeeded; we'll build the call below.
16026 break;
16027
16028 case OR_No_Viable_Function: {
16029 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16030 if (CandidateSet.empty()) {
16031 QualType BaseType = Base->getType();
16032 if (NoArrowOperatorFound) {
16033 // Report this specific error to the caller instead of emitting a
16034 // diagnostic, as requested.
16035 *NoArrowOperatorFound = true;
16036 return ExprError();
16037 }
16038 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16039 << BaseType << Base->getSourceRange();
16040 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16041 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16042 << FixItHint::CreateReplacement(OpLoc, ".");
16043 }
16044 } else
16045 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16046 << "operator->" << Base->getSourceRange();
16047 CandidateSet.NoteCandidates(*this, Base, Cands);
16048 return ExprError();
16049 }
16050 case OR_Ambiguous:
16051 if (!R.isAmbiguous())
16052 CandidateSet.NoteCandidates(
16053 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16054 << "->" << Base->getType()
16055 << Base->getSourceRange()),
16057 return ExprError();
16058
16059 case OR_Deleted:
16060 CandidateSet.NoteCandidates(
16061 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16062 << "->" << Base->getSourceRange()),
16063 *this, OCD_AllCandidates, Base);
16064 return ExprError();
16065 }
16066
16067 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16068
16069 // Convert the object parameter.
16070 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16071
16072 if (Method->isExplicitObjectMemberFunction()) {
16073 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16074 if (R.isInvalid())
16075 return ExprError();
16076 Base = R.get();
16077 } else {
16078 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16079 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16080 if (BaseResult.isInvalid())
16081 return ExprError();
16082 Base = BaseResult.get();
16083 }
16084
16085 // Build the operator call.
16086 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16087 Base, HadMultipleCandidates, OpLoc);
16088 if (FnExpr.isInvalid())
16089 return ExprError();
16090
16091 QualType ResultTy = Method->getReturnType();
16093 ResultTy = ResultTy.getNonLValueExprType(Context);
16094
16095 CallExpr *TheCall =
16096 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16097 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16098
16099 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16100 return ExprError();
16101
16102 if (CheckFunctionCall(Method, TheCall,
16103 Method->getType()->castAs<FunctionProtoType>()))
16104 return ExprError();
16105
16106 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16107}
16108
16109/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
16110/// a literal operator described by the provided lookup results.
16112 DeclarationNameInfo &SuffixInfo,
16113 ArrayRef<Expr*> Args,
16114 SourceLocation LitEndLoc,
16115 TemplateArgumentListInfo *TemplateArgs) {
16116 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16117
16118 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16120 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16121 TemplateArgs);
16122
16123 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16124
16125 // Perform overload resolution. This will usually be trivial, but might need
16126 // to perform substitutions for a literal operator template.
16128 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16129 case OR_Success:
16130 case OR_Deleted:
16131 break;
16132
16134 CandidateSet.NoteCandidates(
16135 PartialDiagnosticAt(UDSuffixLoc,
16136 PDiag(diag::err_ovl_no_viable_function_in_call)
16137 << R.getLookupName()),
16138 *this, OCD_AllCandidates, Args);
16139 return ExprError();
16140
16141 case OR_Ambiguous:
16142 CandidateSet.NoteCandidates(
16143 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16144 << R.getLookupName()),
16145 *this, OCD_AmbiguousCandidates, Args);
16146 return ExprError();
16147 }
16148
16149 FunctionDecl *FD = Best->Function;
16150 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16151 nullptr, HadMultipleCandidates,
16152 SuffixInfo.getLoc(),
16153 SuffixInfo.getInfo());
16154 if (Fn.isInvalid())
16155 return true;
16156
16157 // Check the argument types. This should almost always be a no-op, except
16158 // that array-to-pointer decay is applied to string literals.
16159 Expr *ConvArgs[2];
16160 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16161 ExprResult InputInit = PerformCopyInitialization(
16163 SourceLocation(), Args[ArgIdx]);
16164 if (InputInit.isInvalid())
16165 return true;
16166 ConvArgs[ArgIdx] = InputInit.get();
16167 }
16168
16169 QualType ResultTy = FD->getReturnType();
16171 ResultTy = ResultTy.getNonLValueExprType(Context);
16172
16174 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16175 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16176
16177 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16178 return ExprError();
16179
16180 if (CheckFunctionCall(FD, UDL, nullptr))
16181 return ExprError();
16182
16183 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16184}
16185
16186/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16187/// given LookupResult is non-empty, it is assumed to describe a member which
16188/// will be invoked. Otherwise, the function will be found via argument
16189/// dependent lookup.
16190/// CallExpr is set to a valid expression and FRS_Success returned on success,
16191/// otherwise CallExpr is set to ExprError() and some non-success value
16192/// is returned.
16195 SourceLocation RangeLoc,
16196 const DeclarationNameInfo &NameInfo,
16197 LookupResult &MemberLookup,
16198 OverloadCandidateSet *CandidateSet,
16199 Expr *Range, ExprResult *CallExpr) {
16200 Scope *S = nullptr;
16201
16203 if (!MemberLookup.empty()) {
16204 ExprResult MemberRef =
16205 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16206 /*IsPtr=*/false, CXXScopeSpec(),
16207 /*TemplateKWLoc=*/SourceLocation(),
16208 /*FirstQualifierInScope=*/nullptr,
16209 MemberLookup,
16210 /*TemplateArgs=*/nullptr, S);
16211 if (MemberRef.isInvalid()) {
16212 *CallExpr = ExprError();
16213 return FRS_DiagnosticIssued;
16214 }
16215 *CallExpr =
16216 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16217 if (CallExpr->isInvalid()) {
16218 *CallExpr = ExprError();
16219 return FRS_DiagnosticIssued;
16220 }
16221 } else {
16222 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16224 NameInfo, UnresolvedSet<0>());
16225 if (FnR.isInvalid())
16226 return FRS_DiagnosticIssued;
16227 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16228
16229 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16230 CandidateSet, CallExpr);
16231 if (CandidateSet->empty() || CandidateSetError) {
16232 *CallExpr = ExprError();
16233 return FRS_NoViableFunction;
16234 }
16236 OverloadingResult OverloadResult =
16237 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16238
16239 if (OverloadResult == OR_No_Viable_Function) {
16240 *CallExpr = ExprError();
16241 return FRS_NoViableFunction;
16242 }
16243 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16244 Loc, nullptr, CandidateSet, &Best,
16245 OverloadResult,
16246 /*AllowTypoCorrection=*/false);
16247 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16248 *CallExpr = ExprError();
16249 return FRS_DiagnosticIssued;
16250 }
16251 }
16252 return FRS_Success;
16253}
16254
16255
16256/// FixOverloadedFunctionReference - E is an expression that refers to
16257/// a C++ overloaded function (possibly with some parentheses and
16258/// perhaps a '&' around it). We have resolved the overloaded function
16259/// to the function declaration Fn, so patch up the expression E to
16260/// refer (possibly indirectly) to Fn. Returns the new expr.
16262 FunctionDecl *Fn) {
16263 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16264 ExprResult SubExpr =
16265 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16266 if (SubExpr.isInvalid())
16267 return ExprError();
16268 if (SubExpr.get() == PE->getSubExpr())
16269 return PE;
16270
16271 return new (Context)
16272 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16273 }
16274
16275 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16276 ExprResult SubExpr =
16277 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16278 if (SubExpr.isInvalid())
16279 return ExprError();
16280 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16281 SubExpr.get()->getType()) &&
16282 "Implicit cast type cannot be determined from overload");
16283 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16284 if (SubExpr.get() == ICE->getSubExpr())
16285 return ICE;
16286
16287 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16288 SubExpr.get(), nullptr, ICE->getValueKind(),
16289 CurFPFeatureOverrides());
16290 }
16291
16292 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16293 if (!GSE->isResultDependent()) {
16294 ExprResult SubExpr =
16295 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16296 if (SubExpr.isInvalid())
16297 return ExprError();
16298 if (SubExpr.get() == GSE->getResultExpr())
16299 return GSE;
16300
16301 // Replace the resulting type information before rebuilding the generic
16302 // selection expression.
16303 ArrayRef<Expr *> A = GSE->getAssocExprs();
16304 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16305 unsigned ResultIdx = GSE->getResultIndex();
16306 AssocExprs[ResultIdx] = SubExpr.get();
16307
16308 if (GSE->isExprPredicate())
16310 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16311 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16312 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16313 ResultIdx);
16315 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16316 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16317 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16318 ResultIdx);
16319 }
16320 // Rather than fall through to the unreachable, return the original generic
16321 // selection expression.
16322 return GSE;
16323 }
16324
16325 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16326 assert(UnOp->getOpcode() == UO_AddrOf &&
16327 "Can only take the address of an overloaded function");
16328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16329 if (Method->isStatic()) {
16330 // Do nothing: static member functions aren't any different
16331 // from non-member functions.
16332 } else {
16333 // Fix the subexpression, which really has to be an
16334 // UnresolvedLookupExpr holding an overloaded member function
16335 // or template.
16336 ExprResult SubExpr =
16337 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16338 if (SubExpr.isInvalid())
16339 return ExprError();
16340 if (SubExpr.get() == UnOp->getSubExpr())
16341 return UnOp;
16342
16343 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16344 SubExpr.get(), Method))
16345 return ExprError();
16346
16347 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16348 "fixed to something other than a decl ref");
16349 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16350 "fixed to a member ref with no nested name qualifier");
16351
16352 // We have taken the address of a pointer to member
16353 // function. Perform the computation here so that we get the
16354 // appropriate pointer to member type.
16355 QualType ClassType
16356 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16357 QualType MemPtrType
16358 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16359 // Under the MS ABI, lock down the inheritance model now.
16360 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16361 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16362
16363 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16364 MemPtrType, VK_PRValue, OK_Ordinary,
16365 UnOp->getOperatorLoc(), false,
16366 CurFPFeatureOverrides());
16367 }
16368 }
16369 ExprResult SubExpr =
16370 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16371 if (SubExpr.isInvalid())
16372 return ExprError();
16373 if (SubExpr.get() == UnOp->getSubExpr())
16374 return UnOp;
16375
16376 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16377 SubExpr.get());
16378 }
16379
16380 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16381 // FIXME: avoid copy.
16382 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16383 if (ULE->hasExplicitTemplateArgs()) {
16384 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16385 TemplateArgs = &TemplateArgsBuffer;
16386 }
16387
16388 QualType Type = Fn->getType();
16389 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16390
16391 // FIXME: Duplicated from BuildDeclarationNameExpr.
16392 if (unsigned BID = Fn->getBuiltinID()) {
16393 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16394 Type = Context.BuiltinFnTy;
16395 ValueKind = VK_PRValue;
16396 }
16397 }
16398
16399 DeclRefExpr *DRE = BuildDeclRefExpr(
16400 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16401 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16402 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16403 return DRE;
16404 }
16405
16406 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16407 // FIXME: avoid copy.
16408 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16409 if (MemExpr->hasExplicitTemplateArgs()) {
16410 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16411 TemplateArgs = &TemplateArgsBuffer;
16412 }
16413
16414 Expr *Base;
16415
16416 // If we're filling in a static method where we used to have an
16417 // implicit member access, rewrite to a simple decl ref.
16418 if (MemExpr->isImplicitAccess()) {
16419 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16420 DeclRefExpr *DRE = BuildDeclRefExpr(
16421 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16422 MemExpr->getQualifierLoc(), Found.getDecl(),
16423 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16424 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16425 return DRE;
16426 } else {
16427 SourceLocation Loc = MemExpr->getMemberLoc();
16428 if (MemExpr->getQualifier())
16429 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16430 Base =
16431 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16432 }
16433 } else
16434 Base = MemExpr->getBase();
16435
16436 ExprValueKind valueKind;
16437 QualType type;
16438 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16439 valueKind = VK_LValue;
16440 type = Fn->getType();
16441 } else {
16442 valueKind = VK_PRValue;
16443 type = Context.BoundMemberTy;
16444 }
16445
16446 return BuildMemberExpr(
16447 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16448 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16449 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16450 type, valueKind, OK_Ordinary, TemplateArgs);
16451 }
16452
16453 llvm_unreachable("Invalid reference to overloaded function");
16454}
16455
16457 DeclAccessPair Found,
16458 FunctionDecl *Fn) {
16459 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16460}
16461
16462bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16464 if (!PartialOverloading || !Function)
16465 return true;
16466 if (Function->isVariadic())
16467 return false;
16468 if (const auto *Proto =
16469 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16470 if (Proto->isTemplateVariadic())
16471 return false;
16472 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16473 if (const auto *Proto =
16474 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16475 if (Proto->isTemplateVariadic())
16476 return false;
16477 return true;
16478}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3259
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:142
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:28
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static std::string getName(const CallEvent &Call)
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5698
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs)
General arity mismatch diagnosis over a candidate in a candidate set.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static bool IsOverloaded(const UnresolvedSetImpl &Functions)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs)
Additional arity mismatch diagnosis specific to a function overload candidates.
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch)
Defines the SourceManager interface.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
__device__ __2f16 b
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:864
iterator end()
Definition: Lookup.h:888
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:880
iterator begin()
Definition: Lookup.h:887
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:885
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:397
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:942
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2742
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
Definition: ASTContext.h:1095
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1095
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:643
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1098
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2549
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
CanQualType DoubleTy
Definition: ASTContext.h:1098
CanQualType LongDoubleTy
Definition: ASTContext.h:1098
CanQualType Char16Ty
Definition: ASTContext.h:1093
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1114
CanQualType NullPtrTy
Definition: ASTContext.h:1113
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1575
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:641
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
bool canBindObjCObjectType(QualType To, QualType From)
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1098
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2246
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1087
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:753
CanQualType Float128Ty
Definition: ASTContext.h:1098
CanQualType UnsignedLongTy
Definition: ASTContext.h:1096
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1272
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1114
CanQualType CharTy
Definition: ASTContext.h:1088
CanQualType IntTy
Definition: ASTContext.h:1095
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2141
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CanQualType SignedCharTy
Definition: ASTContext.h:1095
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1114
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2048
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2315
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1097
CanQualType BuiltinFnTy
Definition: ASTContext.h:1115
CanQualType VoidTy
Definition: ASTContext.h:1086
CanQualType UnsignedCharTy
Definition: ASTContext.h:1096
CanQualType UnsignedIntTy
Definition: ASTContext.h:1096
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1281
CanQualType UnknownAnyTy
Definition: ASTContext.h:1114
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1097
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1096
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1553
CanQualType ShortTy
Definition: ASTContext.h:1095
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
CanQualType Char32Ty
Definition: ASTContext.h:1094
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2136
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1095
CanQualType WCharTy
Definition: ASTContext.h:1089
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1092
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3147
QualType getElementType() const
Definition: Type.h:3159
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6732
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3834
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2167
StringRef getOpcodeStr() const
Definition: Expr.h:3899
bool isCompoundAssignmentOp() const
Definition: Expr.h:3977
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4767
Pointer to a block type.
Definition: Type.h:2978
This class is used for builtin types like 'int'.
Definition: Type.h:2740
Kind getKind() const
Definition: Type.h:2782
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2528
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2855
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2891
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2895
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:626
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2453
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2207
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2574
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2229
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2179
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2563
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2486
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2214
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2203
bool isStatic() const
Definition: DeclCXX.cpp:2185
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:562
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1021
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1832
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1593
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2819
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1474
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2989
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3141
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1488
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isAtLeastAsQualifiedAs(CanQual< T > Other) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
bool isVolatileQualified() const
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition: Type.h:2845
QualType getElementType() const
Definition: Type.h:2855
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4789
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3186
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2076
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2201
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1785
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1939
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2069
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition: Expr.h:1447
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:239
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:235
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
T * getAttr() const
Definition: DeclBase.h:578
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1117
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isInvalidDecl() const
Definition: DeclBase.h:593
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:564
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getDeclContext()
Definition: DeclBase.h:453
AccessSpecifier getAccess() const
Definition: DeclBase.h:512
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:574
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:569
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:582
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:746
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:731
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:722
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3832
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4037
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5118
EnumDecl * getDecl() const
Definition: Type.h:5125
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1892
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1916
const Expr * getExpr() const
Definition: DeclCXX.h:1901
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2143
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
static Classification makeSimpleLValue()
Create a simple, modifiably lvalue.
Definition: Expr.h:388
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3050
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3041
bool isPRValue() const
Definition: Expr.h:278
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3265
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4065
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3904
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
Represents difference between two FPOptions values.
Definition: LangOptions.h:870
Represents a member of a struct/union/class.
Definition: Decl.h:3025
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
Represents a function declaration or definition.
Definition: Decl.h:1959
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2574
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2674
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3678
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4007
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3597
param_iterator param_end()
Definition: Decl.h:2664
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3501
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3696
QualType getReturnType() const
Definition: Decl.h:2722
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2651
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3541
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4078
unsigned getMinRequiredExplicitArguments() const
Returns the minimum number of non-object arguments needed to call this function.
Definition: Decl.cpp:3705
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4127
param_iterator param_begin()
Definition: Decl.h:2663
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4204
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2477
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4143
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3279
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4071
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3700
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2407
bool isDeletedAsWritten() const
Definition: Decl.h:2481
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3271
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3537
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2322
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4362
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3944
bool isConsteval() const
Definition: Decl.h:2419
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2739
void getAssociatedConstraints(SmallVectorImpl< const Expr * > &AC) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2636
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3979
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3657
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3854
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2570
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
unsigned getNumParams() const
Definition: Type.h:4432
Qualifiers getMethodQuals() const
Definition: Type.h:4573
QualType getParamType(unsigned i) const
Definition: Type.h:4434
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4555
ArrayRef< QualType > param_types() const
Definition: Type.h:4587
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3910
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3984
bool getNoReturn() const
Definition: Type.h:3958
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3799
ExtInfo getExtInfo() const
Definition: Type.h:4128
CallingConv getCallConv() const
Definition: Type.h:4127
QualType getReturnType() const
Definition: Type.h:4116
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4140
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4456
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3649
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2060
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:540
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:591
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:688
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:595
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition: Overload.h:739
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:599
bool hasInitializerListContainerType() const
Definition: Overload.h:721
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:652
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:728
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:603
QualType getInitializerListContainerType() const
Definition: Overload.h:731
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:4841
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4948
unsigned getNumInits() const
Definition: Expr.h:4871
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2452
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4887
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2470
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:957
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3053
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:582
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:485
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:600
DeclClass * getAsSingle() const
Definition: Lookup.h:553
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:472
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:359
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:483
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:659
bool isAmbiguous() const
Definition: Lookup.h:321
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:273
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:636
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:351
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:629
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:263
iterator end() const
Definition: Lookup.h:356
iterator begin() const
Definition: Lookup.h:355
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3182
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3261
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3275
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3396
Expr * getBase() const
Definition: Expr.h:3255
void setBase(Expr *E)
Definition: Expr.h:3254
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3289
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1785
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3373
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3265
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3089
QualType getPointeeType() const
Definition: Type.h:3105
const Type * getClass() const
Definition: Type.h:3119
Describes a module or submodule.
Definition: Module.h:105
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6495
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
unsigned param_size() const
Definition: DeclObjC.h:347
bool isVariadic() const
Definition: DeclObjC.h:431
Represents a pointer to an Objective C object.
Definition: Type.h:6551
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:6640
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6609
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6563
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:6603
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1736
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:6615
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:977
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1134
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1161
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions=std::nullopt)
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1175
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1127
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:998
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:993
@ CSK_Normal
Normal lookup.
Definition: Overload.h:981
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:988
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1150
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition: Overload.h:1142
SourceLocation getLocation() const
Definition: Overload.h:1125
CandidateSetKind getKind() const
Definition: Overload.h:1126
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2966
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3081
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3117
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3026
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3078
decls_iterator decls_begin() const
Definition: ExprCXX.h:3058
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3069
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3091
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3087
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3137
decls_iterator decls_end() const
Definition: ExprCXX.h:3061
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3075
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2129
Represents a parameter to a function.
Definition: Decl.h:1749
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2938
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
QualType getPointeeType() const
Definition: Type.h:2908
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4861
A (possibly-)qualified type.
Definition: Type.h:737
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6985
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:6979
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3403
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1017
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7083
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6902
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7102
QualType getCanonicalType() const
Definition: Type.h:6954
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:889
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7073
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6974
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7022
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6948
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1124
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6934
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6842
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6849
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4180
bool hasAtomic() const
Definition: Type.h:641
bool hasRestrict() const
Definition: Type.h:640
QualifiersAndAtomic withVolatile()
Definition: Type.h:653
QualifiersAndAtomic withAtomic()
Definition: Type.h:660
bool hasVolatile() const
Definition: Type.h:638
The collection of all-type qualifiers we support.
Definition: Type.h:147
unsigned getCVRQualifiers() const
Definition: Type.h:295
GC getObjCGCAttr() const
Definition: Type.h:326
bool hasOnlyConst() const
Definition: Type.h:265
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
void removeObjCLifetime()
Definition: Type.h:358
bool hasConst() const
Definition: Type.h:264
void addRestrict()
Definition: Type.h:287
bool hasUnaligned() const
Definition: Type.h:318
bool hasRestrict() const
Definition: Type.h:284
void removeObjCGCAttr()
Definition: Type.h:330
void removeUnaligned()
Definition: Type.h:322
void removeAddressSpace()
Definition: Type.h:403
void addConst()
Definition: Type.h:267
void setAddressSpace(LangAS space)
Definition: Type.h:398
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:495
bool hasVolatile() const
Definition: Type.h:274
bool hasObjCGCAttr() const
Definition: Type.h:325
ObjCLifetime getObjCLifetime() const
Definition: Type.h:352
Qualifiers withoutObjCLifetime() const
Definition: Type.h:340
bool empty() const
Definition: Type.h:440
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:532
LangAS getAddressSpace() const
Definition: Type.h:378
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:553
void addVolatile()
Definition: Type.h:277
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:355
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3071
Represents a struct/union/class.
Definition: Decl.h:4133
field_range fields() const
Definition: Decl.h:4339
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
RecordDecl * getDecl() const
Definition: Type.h:5102
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3009
QualType getPointeeType() const
Definition: Type.h:3027
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:8305
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4851
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:4875
RAII class to control scope of DeferDiags.
Definition: Sema.h:8159
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9755
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9785
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2469
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:8175
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7607
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:7619
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7615
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:166
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
@ CFP_Never
Definition: Sema.h:13194
@ CFP_SameSide
Definition: Sema.h:13199
@ CFP_WrongSide
Definition: Sema.h:13195
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition: Sema.h:8388
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8391
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8397
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8395
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
void EraseUnwantedCUDAMatches(const FunctionDecl *Caller, SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:308
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1556
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1489
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CCK_ImplicitConversion)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: Sema.h:13219
ASTContext & Context
Definition: Sema.h:1030
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:498
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ASTContext & getASTContext() const
Definition: Sema.h:501
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ForRangeStatus
Definition: Sema.h:8605
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AllowedExplicit
Definition: Sema.h:8201
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:947
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9516
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
const LangOptions & getLangOpts() const
Definition: Sema.h:494
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:7195
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:636
const LangOptions & LangOpts
Definition: Sema.h:1028
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:7463
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:225
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:10562
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:645
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3423
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11968
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8522
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6309
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6348
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6327
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6311
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6344
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20762
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21731
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10722
AssignmentAction
Definition: Sema.h:5379
@ AA_Converting
Definition: Sema.h:5383
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:6256
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:8337
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:8383
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:224
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:360
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11943
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3329
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:8275
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8280
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:8281
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:8279
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:8278
CUDAFunctionTarget
Definition: Sema.h:3833
@ CFT_InvalidTarget
Definition: Sema.h:3838
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
OverloadKind
Definition: Sema.h:8177
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:1033
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2407
DiagnosticsEngine & Diags
Definition: Sema.h:1032
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10642
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:302
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21957
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:4270
@ CXXCopyConstructor
Definition: Sema.h:4272
@ CXXMoveConstructor
Definition: Sema.h:4273
@ CXXDefaultConstructor
Definition: Sema.h:4271
@ CXXMoveAssignment
Definition: Sema.h:4275
@ CXXCopyAssignment
Definition: Sema.h:4274
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:10627
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE=nullptr)
Builds an expression which might be an implicit member expression.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6967
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:264
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:354
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:352
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:324
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:275
QualType getFromType() const
Definition: Overload.h:367
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:269
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:329
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:306
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:291
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:351
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:301
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:334
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:285
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:296
ImplicitConversionKind Element
Element - Between the second and third conversion a vector or matrix element conversion may occur.
Definition: Overload.h:281
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:356
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition: Overload.h:344
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition: Overload.h:316
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:320
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:311
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
void setAllToTypes(QualType T)
Definition: Overload.h:361
QualType getToType(unsigned Idx) const
Definition: Overload.h:371
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:631
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:684
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:669
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1291
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
Represents a template argument.
Definition: TemplateBase.h:61
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
Definition: TemplateName.h:219
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5632
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3381
The base class of the type hierarchy.
Definition: Type.h:1606
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2170
bool isBlockPointerType() const
Definition: Type.h:7162
bool isVoidType() const
Definition: Type.h:7443
bool isBooleanType() const
Definition: Type.h:7567
bool isObjCBuiltinType() const
Definition: Type.h:7333
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2104
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1836
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:686
bool isIncompleteArrayType() const
Definition: Type.h:7228
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2083
bool isFloat16Type() const
Definition: Type.h:7452
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:627
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2008
bool isRValueReferenceType() const
Definition: Type.h:7174
bool isConstantArrayType() const
Definition: Type.h:7224
bool isArrayType() const
Definition: Type.h:7220
bool isCharType() const
Definition: Type.cpp:2026
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:7504
bool isArithmeticType() const
Definition: Type.cpp:2218
bool isPointerType() const
Definition: Type.h:7154
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7479
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2409
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
bool isReferenceType() const
Definition: Type.h:7166
bool isEnumeralType() const
Definition: Type.h:7248
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1995
bool isObjCQualifiedIdType() const
Definition: Type.h:7303
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7554
bool isExtVectorType() const
Definition: Type.h:7260
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2062
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7290
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2428
bool isLValueReferenceType() const
Definition: Type.h:7170
bool isBitIntType() const
Definition: Type.h:7378
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2275
bool isAnyComplexType() const
Definition: Type.h:7252
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7492
bool isHalfType() const
Definition: Type.h:7447
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7425
bool isQueueT() const
Definition: Type.h:7359
bool isMemberPointerType() const
Definition: Type.h:7202
bool isObjCIdType() const
Definition: Type.h:7315
bool isMatrixType() const
Definition: Type.h:7270
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4778
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7573
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2175
bool isEventT() const
Definition: Type.h:7351
bool isBFloat16Type() const
Definition: Type.h:7460
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2299
bool isFunctionType() const
Definition: Type.h:7150
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isVectorType() const
Definition: Type.h:7256
bool isObjCClassType() const
Definition: Type.h:7321
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2203
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2423
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2133
bool isAnyPointerType() const
Definition: Type.h:7158
TypeClass getTypeClass() const
Definition: Type.h:2074
bool isSamplerT() const
Definition: Type.h:7347
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isNullPtrType() const
Definition: Type.h:7472
bool isRecordType() const
Definition: Type.h:7244
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2182
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1409
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4824
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1385
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3163
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:3242
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3231
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:373
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3905
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4013
QualType getBaseType() const
Definition: ExprCXX.h:3987
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:3997
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:3978
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4023
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4017
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
unsigned size() const
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:637
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:900
QualType getType() const
Definition: Decl.h:717
Represents a GCC generic vector type.
Definition: Type.h:3512
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:33
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:60
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:217
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus20
Definition: LangStandard.h:58
@ CPlusPlus
Definition: LangStandard.h:54
@ CPlusPlus14
Definition: LangStandard.h:56
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:771
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:799
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:808
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:791
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:795
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition: Overload.h:836
@ ovl_fail_too_few_arguments
Definition: Overload.h:773
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:815
@ ovl_fail_too_many_arguments
Definition: Overload.h:772
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:823
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:832
@ ovl_fail_bad_conversion
Definition: Overload.h:774
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:804
@ ovl_fail_bad_deduction
Definition: Overload.h:775
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:819
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:828
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:812
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:780
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1555
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1558
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1561
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:209
@ ICR_Conversion
Conversion.
Definition: Overload.h:217
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:229
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:220
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:223
@ ICR_Promotion
Promotion.
Definition: Overload.h:214
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:211
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:233
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition: Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition: Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition: Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition: Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition: Overload.h:94
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:202
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition: Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition: Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition: Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition: Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition: Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition: Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:240
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:242
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:248
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:256
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:245
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:252
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:367
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1238
@ None
The alignment was not explicit in code.
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ EST_None
no exception specification
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:21
#define false
Definition: stdbool.h:22
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:440
ConversionSet::const_iterator const_iterator
Definition: Overload.h:476
ConversionSet & conversions()
Definition: Overload.h:459
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:467
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:442
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:525
QualType getFromType() const
Definition: Overload.h:524
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
std::optional< unsigned > getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:4278
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4286
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1003
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition: Overload.h:1016
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1052
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1025
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1042
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:845
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:900
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:942
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:930
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:888
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:859
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:897
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:855
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:850
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:874
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:904
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:871
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:921
unsigned getNumParams() const
Definition: Overload.h:955
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:912
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:908
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:868
DeductionFailureInfo DeductionFailure
Definition: Overload.h:915
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:883
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:863
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:926
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:10051
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:10139
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:10168
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8405
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6610
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition: Overload.h:395
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:407
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:429
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:420
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:424
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:415
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:434
void dump() const
dump - Print this user-defined conversion sequence to standard error.