clang 20.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaCUDA.h"
34#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include <algorithm>
44#include <cassert>
45#include <cstddef>
46#include <cstdlib>
47#include <optional>
48
49using namespace clang;
50using namespace sema;
51
53
55 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
56 return P->hasAttr<PassObjectSizeAttr>();
57 });
58}
59
60/// A convenience routine for creating a decayed reference to a function.
62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
65 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
66 return ExprError();
67 // If FoundDecl is different from Fn (such as if one is a template
68 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // called on both.
70 // FIXME: This would be more comprehensively addressed by modifying
71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 // being used.
73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
74 return ExprError();
75 DeclRefExpr *DRE = new (S.Context)
76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
77 if (HadMultipleCandidates)
78 DRE->setHadMultipleCandidates(true);
79
81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 DRE->setType(Fn->getType());
85 }
86 }
87 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
88 CK_FunctionToPointerDecay);
89}
90
91static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
92 bool InOverloadResolution,
94 bool CStyle,
95 bool AllowObjCWritebackConversion);
96
98 QualType &ToType,
99 bool InOverloadResolution,
101 bool CStyle);
103IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 OverloadCandidateSet& Conversions,
106 AllowedExplicit AllowExplicit,
107 bool AllowObjCConversionOnExplicit);
108
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
113
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
123
124/// GetConversionRank - Retrieve the implicit conversion rank
125/// corresponding to the given implicit conversion kind.
127 static const ImplicitConversionRank Rank[] = {
154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
173 ImplicitConversionKind Dimension) {
175 if (Rank == ICR_HLSL_Scalar_Widening) {
176 if (Base == ICR_Promotion)
178 if (Base == ICR_Conversion)
180 }
181 if (Rank == ICR_HLSL_Dimension_Reduction) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 return Rank;
188}
189
190/// GetImplicitConversionName - Return the name of this kind of
191/// implicit conversion.
193 static const char *const Name[] = {
194 "No conversion",
195 "Lvalue-to-rvalue",
196 "Array-to-pointer",
197 "Function-to-pointer",
198 "Function pointer conversion",
199 "Qualification",
200 "Integral promotion",
201 "Floating point promotion",
202 "Complex promotion",
203 "Integral conversion",
204 "Floating conversion",
205 "Complex conversion",
206 "Floating-integral conversion",
207 "Pointer conversion",
208 "Pointer-to-member conversion",
209 "Boolean conversion",
210 "Compatible-types conversion",
211 "Derived-to-base conversion",
212 "Vector conversion",
213 "SVE Vector conversion",
214 "RVV Vector conversion",
215 "Vector splat",
216 "Complex-real conversion",
217 "Block Pointer conversion",
218 "Transparent Union Conversion",
219 "Writeback conversion",
220 "OpenCL Zero Event Conversion",
221 "OpenCL Zero Queue Conversion",
222 "C specific type conversion",
223 "Incompatible pointer conversion",
224 "Fixed point conversion",
225 "HLSL vector truncation",
226 "Non-decaying array conversion",
227 "HLSL vector splat",
228 };
229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
230 return Name[Kind];
231}
232
233/// StandardConversionSequence - Set the standard conversion
234/// sequence to the identity conversion.
242 ReferenceBinding = false;
243 DirectBinding = false;
244 IsLvalueReference = true;
245 BindsToFunctionLvalue = false;
246 BindsToRvalue = false;
249 CopyConstructor = nullptr;
250}
251
252/// getRank - Retrieve the rank of this standard conversion sequence
253/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
254/// implicit conversions.
257 if (GetConversionRank(First) > Rank)
258 Rank = GetConversionRank(First);
259 if (GetConversionRank(Second) > Rank)
261 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
263 if (GetConversionRank(Third) > Rank)
264 Rank = GetConversionRank(Third);
265 return Rank;
266}
267
268/// isPointerConversionToBool - Determines whether this conversion is
269/// a conversion of a pointer or pointer-to-member to bool. This is
270/// used as part of the ranking of standard conversion sequences
271/// (C++ 13.3.3.2p4).
273 // Note that FromType has not necessarily been transformed by the
274 // array-to-pointer or function-to-pointer implicit conversions, so
275 // check for their presence as well as checking whether FromType is
276 // a pointer.
277 if (getToType(1)->isBooleanType() &&
278 (getFromType()->isPointerType() ||
279 getFromType()->isMemberPointerType() ||
280 getFromType()->isObjCObjectPointerType() ||
281 getFromType()->isBlockPointerType() ||
283 return true;
284
285 return false;
286}
287
288/// isPointerConversionToVoidPointer - Determines whether this
289/// conversion is a conversion of a pointer to a void pointer. This is
290/// used as part of the ranking of standard conversion sequences (C++
291/// 13.3.3.2p4).
292bool
295 QualType FromType = getFromType();
296 QualType ToType = getToType(1);
297
298 // Note that FromType has not necessarily been transformed by the
299 // array-to-pointer implicit conversion, so check for its presence
300 // and redo the conversion to get a pointer.
302 FromType = Context.getArrayDecayedType(FromType);
303
304 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
305 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
306 return ToPtrType->getPointeeType()->isVoidType();
307
308 return false;
309}
310
311/// Skip any implicit casts which could be either part of a narrowing conversion
312/// or after one in an implicit conversion.
314 const Expr *Converted) {
315 // We can have cleanups wrapping the converted expression; these need to be
316 // preserved so that destructors run if necessary.
317 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
318 Expr *Inner =
319 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
320 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
321 EWC->getObjects());
322 }
323
324 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
325 switch (ICE->getCastKind()) {
326 case CK_NoOp:
327 case CK_IntegralCast:
328 case CK_IntegralToBoolean:
329 case CK_IntegralToFloating:
330 case CK_BooleanToSignedIntegral:
331 case CK_FloatingToIntegral:
332 case CK_FloatingToBoolean:
333 case CK_FloatingCast:
334 Converted = ICE->getSubExpr();
335 continue;
336
337 default:
338 return Converted;
339 }
340 }
341
342 return Converted;
343}
344
345/// Check if this standard conversion sequence represents a narrowing
346/// conversion, according to C++11 [dcl.init.list]p7.
347///
348/// \param Ctx The AST context.
349/// \param Converted The result of applying this standard conversion sequence.
350/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
351/// value of the expression prior to the narrowing conversion.
352/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
353/// type of the expression prior to the narrowing conversion.
354/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
355/// from floating point types to integral types should be ignored.
357 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
358 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
359 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
360 "narrowing check outside C++");
361
362 // C++11 [dcl.init.list]p7:
363 // A narrowing conversion is an implicit conversion ...
364 QualType FromType = getToType(0);
365 QualType ToType = getToType(1);
366
367 // A conversion to an enumeration type is narrowing if the conversion to
368 // the underlying type is narrowing. This only arises for expressions of
369 // the form 'Enum{init}'.
370 if (auto *ET = ToType->getAs<EnumType>())
371 ToType = ET->getDecl()->getIntegerType();
372
373 switch (Second) {
374 // 'bool' is an integral type; dispatch to the right place to handle it.
376 if (FromType->isRealFloatingType())
377 goto FloatingIntegralConversion;
379 goto IntegralConversion;
380 // -- from a pointer type or pointer-to-member type to bool, or
381 return NK_Type_Narrowing;
382
383 // -- from a floating-point type to an integer type, or
384 //
385 // -- from an integer type or unscoped enumeration type to a floating-point
386 // type, except where the source is a constant expression and the actual
387 // value after conversion will fit into the target type and will produce
388 // the original value when converted back to the original type, or
390 FloatingIntegralConversion:
391 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
392 return NK_Type_Narrowing;
393 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
394 ToType->isRealFloatingType()) {
395 if (IgnoreFloatToIntegralConversion)
396 return NK_Not_Narrowing;
397 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
398 assert(Initializer && "Unknown conversion expression");
399
400 // If it's value-dependent, we can't tell whether it's narrowing.
401 if (Initializer->isValueDependent())
403
404 if (std::optional<llvm::APSInt> IntConstantValue =
405 Initializer->getIntegerConstantExpr(Ctx)) {
406 // Convert the integer to the floating type.
407 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
408 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
409 llvm::APFloat::rmNearestTiesToEven);
410 // And back.
411 llvm::APSInt ConvertedValue = *IntConstantValue;
412 bool ignored;
413 Result.convertToInteger(ConvertedValue,
414 llvm::APFloat::rmTowardZero, &ignored);
415 // If the resulting value is different, this was a narrowing conversion.
416 if (*IntConstantValue != ConvertedValue) {
417 ConstantValue = APValue(*IntConstantValue);
418 ConstantType = Initializer->getType();
420 }
421 } else {
422 // Variables are always narrowings.
424 }
425 }
426 return NK_Not_Narrowing;
427
428 // -- from long double to double or float, or from double to float, except
429 // where the source is a constant expression and the actual value after
430 // conversion is within the range of values that can be represented (even
431 // if it cannot be represented exactly), or
433 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
434 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
435 // FromType is larger than ToType.
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
437
438 // If it's value-dependent, we can't tell whether it's narrowing.
439 if (Initializer->isValueDependent())
441
443 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
444 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
445 // Constant!
446 if (Ctx.getLangOpts().C23)
447 ConstantValue = R.Val;
448 assert(ConstantValue.isFloat());
449 llvm::APFloat FloatVal = ConstantValue.getFloat();
450 // Convert the source value into the target type.
451 bool ignored;
452 llvm::APFloat Converted = FloatVal;
453 llvm::APFloat::opStatus ConvertStatus =
454 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
455 llvm::APFloat::rmNearestTiesToEven, &ignored);
456 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
457 llvm::APFloat::rmNearestTiesToEven, &ignored);
458 if (Ctx.getLangOpts().C23) {
459 if (FloatVal.isNaN() && Converted.isNaN() &&
460 !FloatVal.isSignaling() && !Converted.isSignaling()) {
461 // Quiet NaNs are considered the same value, regardless of
462 // payloads.
463 return NK_Not_Narrowing;
464 }
465 // For normal values, check exact equality.
466 if (!Converted.bitwiseIsEqual(FloatVal)) {
467 ConstantType = Initializer->getType();
469 }
470 } else {
471 // If there was no overflow, the source value is within the range of
472 // values that can be represented.
473 if (ConvertStatus & llvm::APFloat::opOverflow) {
474 ConstantType = Initializer->getType();
476 }
477 }
478 } else {
480 }
481 }
482 return NK_Not_Narrowing;
483
484 // -- from an integer type or unscoped enumeration type to an integer type
485 // that cannot represent all the values of the original type, except where
486 // (CWG2627) -- the source is a bit-field whose width w is less than that
487 // of its type (or, for an enumeration type, its underlying type) and the
488 // target type can represent all the values of a hypothetical extended
489 // integer type with width w and with the same signedness as the original
490 // type or
491 // -- the source is a constant expression and the actual value after
492 // conversion will fit into the target type and will produce the original
493 // value when converted back to the original type.
495 IntegralConversion: {
496 assert(FromType->isIntegralOrUnscopedEnumerationType());
497 assert(ToType->isIntegralOrUnscopedEnumerationType());
498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
499 unsigned FromWidth = Ctx.getIntWidth(FromType);
500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
501 const unsigned ToWidth = Ctx.getIntWidth(ToType);
502
503 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
504 bool ToSigned, unsigned ToWidth) {
505 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
506 !(FromSigned && !ToSigned);
507 };
508
509 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
510 return NK_Not_Narrowing;
511
512 // Not all values of FromType can be represented in ToType.
513 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
514
515 bool DependentBitField = false;
516 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
517 if (BitField->getBitWidth()->isValueDependent())
518 DependentBitField = true;
519 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
520 BitFieldWidth < FromWidth) {
521 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
522 return NK_Not_Narrowing;
523
524 // The initializer will be truncated to the bit-field width
525 FromWidth = BitFieldWidth;
526 }
527 }
528
529 // If it's value-dependent, we can't tell whether it's narrowing.
530 if (Initializer->isValueDependent())
532
533 std::optional<llvm::APSInt> OptInitializerValue =
534 Initializer->getIntegerConstantExpr(Ctx);
535 if (!OptInitializerValue) {
536 // If the bit-field width was dependent, it might end up being small
537 // enough to fit in the target type (unless the target type is unsigned
538 // and the source type is signed, in which case it will never fit)
539 if (DependentBitField && !(FromSigned && !ToSigned))
541
542 // Otherwise, such a conversion is always narrowing
544 }
545 llvm::APSInt &InitializerValue = *OptInitializerValue;
546 bool Narrowing = false;
547 if (FromWidth < ToWidth) {
548 // Negative -> unsigned is narrowing. Otherwise, more bits is never
549 // narrowing.
550 if (InitializerValue.isSigned() && InitializerValue.isNegative())
551 Narrowing = true;
552 } else {
553 // Add a bit to the InitializerValue so we don't have to worry about
554 // signed vs. unsigned comparisons.
555 InitializerValue =
556 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
557 // Convert the initializer to and from the target width and signed-ness.
558 llvm::APSInt ConvertedValue = InitializerValue;
559 ConvertedValue = ConvertedValue.trunc(ToWidth);
560 ConvertedValue.setIsSigned(ToSigned);
561 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
562 ConvertedValue.setIsSigned(InitializerValue.isSigned());
563 // If the result is different, this was a narrowing conversion.
564 if (ConvertedValue != InitializerValue)
565 Narrowing = true;
566 }
567 if (Narrowing) {
568 ConstantType = Initializer->getType();
569 ConstantValue = APValue(InitializerValue);
571 }
572
573 return NK_Not_Narrowing;
574 }
575 case ICK_Complex_Real:
576 if (FromType->isComplexType() && !ToType->isComplexType())
577 return NK_Type_Narrowing;
578 return NK_Not_Narrowing;
579
581 if (Ctx.getLangOpts().C23) {
582 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
584 if (Initializer->EvaluateAsRValue(R, Ctx)) {
585 ConstantValue = R.Val;
586 assert(ConstantValue.isFloat());
587 llvm::APFloat FloatVal = ConstantValue.getFloat();
588 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
589 // value, the unqualified versions of the type of the initializer and
590 // the corresponding real type of the object declared shall be
591 // compatible.
592 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
593 ConstantType = Initializer->getType();
595 }
596 }
597 }
598 return NK_Not_Narrowing;
599 default:
600 // Other kinds of conversions are not narrowings.
601 return NK_Not_Narrowing;
602 }
603}
604
605/// dump - Print this standard conversion sequence to standard
606/// error. Useful for debugging overloading issues.
607LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
608 raw_ostream &OS = llvm::errs();
609 bool PrintedSomething = false;
610 if (First != ICK_Identity) {
612 PrintedSomething = true;
613 }
614
615 if (Second != ICK_Identity) {
616 if (PrintedSomething) {
617 OS << " -> ";
618 }
620
621 if (CopyConstructor) {
622 OS << " (by copy constructor)";
623 } else if (DirectBinding) {
624 OS << " (direct reference binding)";
625 } else if (ReferenceBinding) {
626 OS << " (reference binding)";
627 }
628 PrintedSomething = true;
629 }
630
631 if (Third != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636 PrintedSomething = true;
637 }
638
639 if (!PrintedSomething) {
640 OS << "No conversions required";
641 }
642}
643
644/// dump - Print this user-defined conversion sequence to standard
645/// error. Useful for debugging overloading issues.
647 raw_ostream &OS = llvm::errs();
648 if (Before.First || Before.Second || Before.Third) {
649 Before.dump();
650 OS << " -> ";
651 }
653 OS << '\'' << *ConversionFunction << '\'';
654 else
655 OS << "aggregate initialization";
656 if (After.First || After.Second || After.Third) {
657 OS << " -> ";
658 After.dump();
659 }
660}
661
662/// dump - Print this implicit conversion sequence to standard
663/// error. Useful for debugging overloading issues.
665 raw_ostream &OS = llvm::errs();
667 OS << "Worst list element conversion: ";
668 switch (ConversionKind) {
670 OS << "Standard conversion: ";
671 Standard.dump();
672 break;
674 OS << "User-defined conversion: ";
676 break;
678 OS << "Ellipsis conversion";
679 break;
681 OS << "Ambiguous conversion";
682 break;
683 case BadConversion:
684 OS << "Bad conversion";
685 break;
686 }
687
688 OS << "\n";
689}
690
692 new (&conversions()) ConversionSet();
693}
694
696 conversions().~ConversionSet();
697}
698
699void
704}
705
706namespace {
707 // Structure used by DeductionFailureInfo to store
708 // template argument information.
709 struct DFIArguments {
710 TemplateArgument FirstArg;
711 TemplateArgument SecondArg;
712 };
713 // Structure used by DeductionFailureInfo to store
714 // template parameter and template argument information.
715 struct DFIParamWithArguments : DFIArguments {
716 TemplateParameter Param;
717 };
718 // Structure used by DeductionFailureInfo to store template argument
719 // information and the index of the problematic call argument.
720 struct DFIDeducedMismatchArgs : DFIArguments {
721 TemplateArgumentList *TemplateArgs;
722 unsigned CallArgIndex;
723 };
724 // Structure used by DeductionFailureInfo to store information about
725 // unsatisfied constraints.
726 struct CNSInfo {
727 TemplateArgumentList *TemplateArgs;
728 ConstraintSatisfaction Satisfaction;
729 };
730}
731
732/// Convert from Sema's representation of template deduction information
733/// to the form used in overload-candidate information.
737 TemplateDeductionInfo &Info) {
739 Result.Result = static_cast<unsigned>(TDK);
740 Result.HasDiagnostic = false;
741 switch (TDK) {
748 Result.Data = nullptr;
749 break;
750
753 Result.Data = Info.Param.getOpaqueValue();
754 break;
755
758 // FIXME: Should allocate from normal heap so that we can free this later.
759 auto *Saved = new (Context) DFIDeducedMismatchArgs;
760 Saved->FirstArg = Info.FirstArg;
761 Saved->SecondArg = Info.SecondArg;
762 Saved->TemplateArgs = Info.takeSugared();
763 Saved->CallArgIndex = Info.CallArgIndex;
764 Result.Data = Saved;
765 break;
766 }
767
769 // FIXME: Should allocate from normal heap so that we can free this later.
770 DFIArguments *Saved = new (Context) DFIArguments;
771 Saved->FirstArg = Info.FirstArg;
772 Saved->SecondArg = Info.SecondArg;
773 Result.Data = Saved;
774 break;
775 }
776
778 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
781 // FIXME: Should allocate from normal heap so that we can free this later.
782 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
783 Saved->Param = Info.Param;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Result.Data = Saved;
787 break;
788 }
789
791 Result.Data = Info.takeSugared();
792 if (Info.hasSFINAEDiagnostic()) {
796 Result.HasDiagnostic = true;
797 }
798 break;
799
801 CNSInfo *Saved = new (Context) CNSInfo;
802 Saved->TemplateArgs = Info.takeSugared();
803 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
804 Result.Data = Saved;
805 break;
806 }
807
811 llvm_unreachable("not a deduction failure");
812 }
813
814 return Result;
815}
816
818 switch (static_cast<TemplateDeductionResult>(Result)) {
828 break;
829
836 // FIXME: Destroy the data?
837 Data = nullptr;
838 break;
839
841 // FIXME: Destroy the template argument list?
842 Data = nullptr;
844 Diag->~PartialDiagnosticAt();
845 HasDiagnostic = false;
846 }
847 break;
848
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
858 // Unhandled
861 break;
862 }
863}
864
866 if (HasDiagnostic)
867 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
868 return nullptr;
869}
870
872 switch (static_cast<TemplateDeductionResult>(Result)) {
885 return TemplateParameter();
886
889 return TemplateParameter::getFromOpaqueValue(Data);
890
894 return static_cast<DFIParamWithArguments*>(Data)->Param;
895
896 // Unhandled
899 break;
900 }
901
902 return TemplateParameter();
903}
904
906 switch (static_cast<TemplateDeductionResult>(Result)) {
920 return nullptr;
921
924 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
925
927 return static_cast<TemplateArgumentList*>(Data);
928
930 return static_cast<CNSInfo*>(Data)->TemplateArgs;
931
932 // Unhandled
935 break;
936 }
937
938 return nullptr;
939}
940
942 switch (static_cast<TemplateDeductionResult>(Result)) {
954 return nullptr;
955
962 return &static_cast<DFIArguments*>(Data)->FirstArg;
963
964 // Unhandled
967 break;
968 }
969
970 return nullptr;
971}
972
974 switch (static_cast<TemplateDeductionResult>(Result)) {
987 return nullptr;
988
994 return &static_cast<DFIArguments*>(Data)->SecondArg;
995
996 // Unhandled
999 break;
1000 }
1001
1002 return nullptr;
1003}
1004
1005std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1006 switch (static_cast<TemplateDeductionResult>(Result)) {
1009 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1010
1011 default:
1012 return std::nullopt;
1013 }
1014}
1015
1017 const FunctionDecl *Y) {
1018 if (!X || !Y)
1019 return false;
1020 if (X->getNumParams() != Y->getNumParams())
1021 return false;
1022 // FIXME: when do rewritten comparison operators
1023 // with explicit object parameters correspond?
1024 // https://cplusplus.github.io/CWG/issues/2797.html
1025 for (unsigned I = 0; I < X->getNumParams(); ++I)
1026 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1027 Y->getParamDecl(I)->getType()))
1028 return false;
1029 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1030 auto *FTY = Y->getDescribedFunctionTemplate();
1031 if (!FTY)
1032 return false;
1033 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1034 FTY->getTemplateParameters()))
1035 return false;
1036 }
1037 return true;
1038}
1039
1041 Expr *FirstOperand, FunctionDecl *EqFD) {
1042 assert(EqFD->getOverloadedOperator() ==
1043 OverloadedOperatorKind::OO_EqualEqual);
1044 // C++2a [over.match.oper]p4:
1045 // A non-template function or function template F named operator== is a
1046 // rewrite target with first operand o unless a search for the name operator!=
1047 // in the scope S from the instantiation context of the operator expression
1048 // finds a function or function template that would correspond
1049 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1050 // scope of the class type of o if F is a class member, and the namespace
1051 // scope of which F is a member otherwise. A function template specialization
1052 // named operator== is a rewrite target if its function template is a rewrite
1053 // target.
1055 OverloadedOperatorKind::OO_ExclaimEqual);
1056 if (isa<CXXMethodDecl>(EqFD)) {
1057 // If F is a class member, search scope is class type of first operand.
1058 QualType RHS = FirstOperand->getType();
1059 auto *RHSRec = RHS->getAs<RecordType>();
1060 if (!RHSRec)
1061 return true;
1062 LookupResult Members(S, NotEqOp, OpLoc,
1064 S.LookupQualifiedName(Members, RHSRec->getDecl());
1065 Members.suppressAccessDiagnostics();
1066 for (NamedDecl *Op : Members)
1067 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1068 return false;
1069 return true;
1070 }
1071 // Otherwise the search scope is the namespace scope of which F is a member.
1072 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1073 auto *NotEqFD = Op->getAsFunction();
1074 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1075 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1076 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1078 cast<Decl>(Op->getLexicalDeclContext())))
1079 return false;
1080 }
1081 return true;
1082}
1083
1087 return false;
1088 return Op == OO_EqualEqual || Op == OO_Spaceship;
1089}
1090
1092 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1093 auto Op = FD->getOverloadedOperator();
1094 if (!allowsReversed(Op))
1095 return false;
1096 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1097 assert(OriginalArgs.size() == 2);
1099 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1100 return false;
1101 }
1102 // Don't bother adding a reversed candidate that can never be a better
1103 // match than the non-reversed version.
1104 return FD->getNumNonObjectParams() != 2 ||
1106 FD->getParamDecl(1)->getType()) ||
1107 FD->hasAttr<EnableIfAttr>();
1108}
1109
1110void OverloadCandidateSet::destroyCandidates() {
1111 for (iterator i = begin(), e = end(); i != e; ++i) {
1112 for (auto &C : i->Conversions)
1113 C.~ImplicitConversionSequence();
1114 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1115 i->DeductionFailure.Destroy();
1116 }
1117}
1118
1120 destroyCandidates();
1121 SlabAllocator.Reset();
1122 NumInlineBytesUsed = 0;
1123 Candidates.clear();
1124 Functions.clear();
1125 Kind = CSK;
1126}
1127
1128namespace {
1129 class UnbridgedCastsSet {
1130 struct Entry {
1131 Expr **Addr;
1132 Expr *Saved;
1133 };
1134 SmallVector<Entry, 2> Entries;
1135
1136 public:
1137 void save(Sema &S, Expr *&E) {
1138 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1139 Entry entry = { &E, E };
1140 Entries.push_back(entry);
1142 }
1143
1144 void restore() {
1146 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1147 *i->Addr = i->Saved;
1148 }
1149 };
1150}
1151
1152/// checkPlaceholderForOverload - Do any interesting placeholder-like
1153/// preprocessing on the given expression.
1154///
1155/// \param unbridgedCasts a collection to which to add unbridged casts;
1156/// without this, they will be immediately diagnosed as errors
1157///
1158/// Return true on unrecoverable error.
1159static bool
1161 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1162 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1163 // We can't handle overloaded expressions here because overload
1164 // resolution might reasonably tweak them.
1165 if (placeholder->getKind() == BuiltinType::Overload) return false;
1166
1167 // If the context potentially accepts unbridged ARC casts, strip
1168 // the unbridged cast and add it to the collection for later restoration.
1169 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1170 unbridgedCasts) {
1171 unbridgedCasts->save(S, E);
1172 return false;
1173 }
1174
1175 // Go ahead and check everything else.
1176 ExprResult result = S.CheckPlaceholderExpr(E);
1177 if (result.isInvalid())
1178 return true;
1179
1180 E = result.get();
1181 return false;
1182 }
1183
1184 // Nothing to do.
1185 return false;
1186}
1187
1188/// checkArgPlaceholdersForOverload - Check a set of call operands for
1189/// placeholders.
1191 UnbridgedCastsSet &unbridged) {
1192 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1193 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1194 return true;
1195
1196 return false;
1197}
1198
1201 NamedDecl *&Match, bool NewIsUsingDecl) {
1202 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1203 I != E; ++I) {
1204 NamedDecl *OldD = *I;
1205
1206 bool OldIsUsingDecl = false;
1207 if (isa<UsingShadowDecl>(OldD)) {
1208 OldIsUsingDecl = true;
1209
1210 // We can always introduce two using declarations into the same
1211 // context, even if they have identical signatures.
1212 if (NewIsUsingDecl) continue;
1213
1214 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1215 }
1216
1217 // A using-declaration does not conflict with another declaration
1218 // if one of them is hidden.
1219 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1220 continue;
1221
1222 // If either declaration was introduced by a using declaration,
1223 // we'll need to use slightly different rules for matching.
1224 // Essentially, these rules are the normal rules, except that
1225 // function templates hide function templates with different
1226 // return types or template parameter lists.
1227 bool UseMemberUsingDeclRules =
1228 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1229 !New->getFriendObjectKind();
1230
1231 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1232 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1233 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1234 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1235 continue;
1236 }
1237
1238 if (!isa<FunctionTemplateDecl>(OldD) &&
1239 !shouldLinkPossiblyHiddenDecl(*I, New))
1240 continue;
1241
1242 Match = *I;
1243 return Ovl_Match;
1244 }
1245
1246 // Builtins that have custom typechecking or have a reference should
1247 // not be overloadable or redeclarable.
1248 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1249 Match = *I;
1250 return Ovl_NonFunction;
1251 }
1252 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1253 // We can overload with these, which can show up when doing
1254 // redeclaration checks for UsingDecls.
1255 assert(Old.getLookupKind() == LookupUsingDeclName);
1256 } else if (isa<TagDecl>(OldD)) {
1257 // We can always overload with tags by hiding them.
1258 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1259 // Optimistically assume that an unresolved using decl will
1260 // overload; if it doesn't, we'll have to diagnose during
1261 // template instantiation.
1262 //
1263 // Exception: if the scope is dependent and this is not a class
1264 // member, the using declaration can only introduce an enumerator.
1265 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1266 Match = *I;
1267 return Ovl_NonFunction;
1268 }
1269 } else {
1270 // (C++ 13p1):
1271 // Only function declarations can be overloaded; object and type
1272 // declarations cannot be overloaded.
1273 Match = *I;
1274 return Ovl_NonFunction;
1275 }
1276 }
1277
1278 // C++ [temp.friend]p1:
1279 // For a friend function declaration that is not a template declaration:
1280 // -- if the name of the friend is a qualified or unqualified template-id,
1281 // [...], otherwise
1282 // -- if the name of the friend is a qualified-id and a matching
1283 // non-template function is found in the specified class or namespace,
1284 // the friend declaration refers to that function, otherwise,
1285 // -- if the name of the friend is a qualified-id and a matching function
1286 // template is found in the specified class or namespace, the friend
1287 // declaration refers to the deduced specialization of that function
1288 // template, otherwise
1289 // -- the name shall be an unqualified-id [...]
1290 // If we get here for a qualified friend declaration, we've just reached the
1291 // third bullet. If the type of the friend is dependent, skip this lookup
1292 // until instantiation.
1293 if (New->getFriendObjectKind() && New->getQualifier() &&
1296 !New->getType()->isDependentType()) {
1297 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1298 TemplateSpecResult.addAllDecls(Old);
1299 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1300 /*QualifiedFriend*/true)) {
1301 New->setInvalidDecl();
1302 return Ovl_Overload;
1303 }
1304
1305 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1306 return Ovl_Match;
1307 }
1308
1309 return Ovl_Overload;
1310}
1311
1312template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1313 assert(D && "function decl should not be null");
1314 if (auto *A = D->getAttr<AttrT>())
1315 return !A->isImplicit();
1316 return false;
1317}
1318
1319static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1320 FunctionDecl *Old,
1321 bool UseMemberUsingDeclRules,
1322 bool ConsiderCudaAttrs,
1323 bool UseOverrideRules = false) {
1324 // C++ [basic.start.main]p2: This function shall not be overloaded.
1325 if (New->isMain())
1326 return false;
1327
1328 // MSVCRT user defined entry points cannot be overloaded.
1329 if (New->isMSVCRTEntryPoint())
1330 return false;
1331
1332 NamedDecl *OldDecl = Old;
1333 NamedDecl *NewDecl = New;
1336
1337 // C++ [temp.fct]p2:
1338 // A function template can be overloaded with other function templates
1339 // and with normal (non-template) functions.
1340 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1341 return true;
1342
1343 // Is the function New an overload of the function Old?
1344 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1345 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1346
1347 // Compare the signatures (C++ 1.3.10) of the two functions to
1348 // determine whether they are overloads. If we find any mismatch
1349 // in the signature, they are overloads.
1350
1351 // If either of these functions is a K&R-style function (no
1352 // prototype), then we consider them to have matching signatures.
1353 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1354 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1355 return false;
1356
1357 const auto *OldType = cast<FunctionProtoType>(OldQType);
1358 const auto *NewType = cast<FunctionProtoType>(NewQType);
1359
1360 // The signature of a function includes the types of its
1361 // parameters (C++ 1.3.10), which includes the presence or absence
1362 // of the ellipsis; see C++ DR 357).
1363 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1364 return true;
1365
1366 // For member-like friends, the enclosing class is part of the signature.
1367 if ((New->isMemberLikeConstrainedFriend() ||
1370 return true;
1371
1372 // Compare the parameter lists.
1373 // This can only be done once we have establish that friend functions
1374 // inhabit the same context, otherwise we might tried to instantiate
1375 // references to non-instantiated entities during constraint substitution.
1376 // GH78101.
1377 if (NewTemplate) {
1378 OldDecl = OldTemplate;
1379 NewDecl = NewTemplate;
1380 // C++ [temp.over.link]p4:
1381 // The signature of a function template consists of its function
1382 // signature, its return type and its template parameter list. The names
1383 // of the template parameters are significant only for establishing the
1384 // relationship between the template parameters and the rest of the
1385 // signature.
1386 //
1387 // We check the return type and template parameter lists for function
1388 // templates first; the remaining checks follow.
1389 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1390 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1391 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1392 bool SameReturnType = SemaRef.Context.hasSameType(
1394 // FIXME(GH58571): Match template parameter list even for non-constrained
1395 // template heads. This currently ensures that the code prior to C++20 is
1396 // not newly broken.
1397 bool ConstraintsInTemplateHead =
1400 // C++ [namespace.udecl]p11:
1401 // The set of declarations named by a using-declarator that inhabits a
1402 // class C does not include member functions and member function
1403 // templates of a base class that "correspond" to (and thus would
1404 // conflict with) a declaration of a function or function template in
1405 // C.
1406 // Comparing return types is not required for the "correspond" check to
1407 // decide whether a member introduced by a shadow declaration is hidden.
1408 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1409 !SameTemplateParameterList)
1410 return true;
1411 if (!UseMemberUsingDeclRules &&
1412 (!SameTemplateParameterList || !SameReturnType))
1413 return true;
1414 }
1415
1416 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1417 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1418
1419 int OldParamsOffset = 0;
1420 int NewParamsOffset = 0;
1421
1422 // When determining if a method is an overload from a base class, act as if
1423 // the implicit object parameter are of the same type.
1424
1425 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1427 auto ThisType = M->getFunctionObjectParameterReferenceType();
1428 if (ThisType.isConstQualified())
1429 Q.removeConst();
1430 return Q;
1431 }
1432
1433 // We do not allow overloading based off of '__restrict'.
1434 Q.removeRestrict();
1435
1436 // We may not have applied the implicit const for a constexpr member
1437 // function yet (because we haven't yet resolved whether this is a static
1438 // or non-static member function). Add it now, on the assumption that this
1439 // is a redeclaration of OldMethod.
1440 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1441 (M->isConstexpr() || M->isConsteval()) &&
1442 !isa<CXXConstructorDecl>(NewMethod))
1443 Q.addConst();
1444 return Q;
1445 };
1446
1447 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1448 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1449 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1450
1451 if (OldMethod->isExplicitObjectMemberFunction()) {
1452 BS.Quals.removeVolatile();
1453 DS.Quals.removeVolatile();
1454 }
1455
1456 return BS.Quals == DS.Quals;
1457 };
1458
1459 auto CompareType = [&](QualType Base, QualType D) {
1460 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1461 auto DS = D.getNonReferenceType().getCanonicalType().split();
1462
1463 if (!AreQualifiersEqual(BS, DS))
1464 return false;
1465
1466 if (OldMethod->isImplicitObjectMemberFunction() &&
1467 OldMethod->getParent() != NewMethod->getParent()) {
1468 QualType ParentType =
1469 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1470 .getCanonicalType();
1471 if (ParentType.getTypePtr() != BS.Ty)
1472 return false;
1473 BS.Ty = DS.Ty;
1474 }
1475
1476 // FIXME: should we ignore some type attributes here?
1477 if (BS.Ty != DS.Ty)
1478 return false;
1479
1480 if (Base->isLValueReferenceType())
1481 return D->isLValueReferenceType();
1482 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1483 };
1484
1485 // If the function is a class member, its signature includes the
1486 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1487 auto DiagnoseInconsistentRefQualifiers = [&]() {
1488 if (SemaRef.LangOpts.CPlusPlus23)
1489 return false;
1490 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1491 return false;
1492 if (OldMethod->isExplicitObjectMemberFunction() ||
1493 NewMethod->isExplicitObjectMemberFunction())
1494 return false;
1495 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1496 NewMethod->getRefQualifier() == RQ_None)) {
1497 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1498 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1499 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1500 return true;
1501 }
1502 return false;
1503 };
1504
1505 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1506 OldParamsOffset++;
1507 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1508 NewParamsOffset++;
1509
1510 if (OldType->getNumParams() - OldParamsOffset !=
1511 NewType->getNumParams() - NewParamsOffset ||
1513 {OldType->param_type_begin() + OldParamsOffset,
1514 OldType->param_type_end()},
1515 {NewType->param_type_begin() + NewParamsOffset,
1516 NewType->param_type_end()},
1517 nullptr)) {
1518 return true;
1519 }
1520
1521 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1522 !NewMethod->isStatic()) {
1523 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1524 const CXXMethodDecl *New) {
1525 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1526 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1527
1528 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1529 return F->getRefQualifier() == RQ_None &&
1530 !F->isExplicitObjectMemberFunction();
1531 };
1532
1533 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1534 CompareType(OldObjectType.getNonReferenceType(),
1535 NewObjectType.getNonReferenceType()))
1536 return true;
1537 return CompareType(OldObjectType, NewObjectType);
1538 }(OldMethod, NewMethod);
1539
1540 if (!HaveCorrespondingObjectParameters) {
1541 if (DiagnoseInconsistentRefQualifiers())
1542 return true;
1543 // CWG2554
1544 // and, if at least one is an explicit object member function, ignoring
1545 // object parameters
1546 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1547 !OldMethod->isExplicitObjectMemberFunction()))
1548 return true;
1549 }
1550 }
1551
1552 if (!UseOverrideRules &&
1554 Expr *NewRC = New->getTrailingRequiresClause(),
1555 *OldRC = Old->getTrailingRequiresClause();
1556 if ((NewRC != nullptr) != (OldRC != nullptr))
1557 return true;
1558 if (NewRC &&
1559 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1560 return true;
1561 }
1562
1563 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1564 NewMethod->isImplicitObjectMemberFunction()) {
1565 if (DiagnoseInconsistentRefQualifiers())
1566 return true;
1567 }
1568
1569 // Though pass_object_size is placed on parameters and takes an argument, we
1570 // consider it to be a function-level modifier for the sake of function
1571 // identity. Either the function has one or more parameters with
1572 // pass_object_size or it doesn't.
1575 return true;
1576
1577 // enable_if attributes are an order-sensitive part of the signature.
1579 NewI = New->specific_attr_begin<EnableIfAttr>(),
1580 NewE = New->specific_attr_end<EnableIfAttr>(),
1581 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1582 OldE = Old->specific_attr_end<EnableIfAttr>();
1583 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1584 if (NewI == NewE || OldI == OldE)
1585 return true;
1586 llvm::FoldingSetNodeID NewID, OldID;
1587 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1588 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1589 if (NewID != OldID)
1590 return true;
1591 }
1592
1593 // At this point, it is known that the two functions have the same signature.
1594 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1595 // Don't allow overloading of destructors. (In theory we could, but it
1596 // would be a giant change to clang.)
1597 if (!isa<CXXDestructorDecl>(New)) {
1598 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1599 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1600 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1601 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1602 "Unexpected invalid target.");
1603
1604 // Allow overloading of functions with same signature and different CUDA
1605 // target attributes.
1606 if (NewTarget != OldTarget) {
1607 // Special case: non-constexpr function is allowed to override
1608 // constexpr virtual function
1609 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1610 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1611 !hasExplicitAttr<CUDAHostAttr>(Old) &&
1612 !hasExplicitAttr<CUDADeviceAttr>(Old) &&
1613 !hasExplicitAttr<CUDAHostAttr>(New) &&
1614 !hasExplicitAttr<CUDADeviceAttr>(New)) {
1615 return false;
1616 }
1617 return true;
1618 }
1619 }
1620 }
1621 }
1622
1623 // The signatures match; this is not an overload.
1624 return false;
1625}
1626
1628 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1629 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1630 ConsiderCudaAttrs);
1631}
1632
1634 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1635 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1636 /*UseMemberUsingDeclRules=*/false,
1637 /*ConsiderCudaAttrs=*/true,
1638 /*UseOverrideRules=*/true);
1639}
1640
1641/// Tries a user-defined conversion from From to ToType.
1642///
1643/// Produces an implicit conversion sequence for when a standard conversion
1644/// is not an option. See TryImplicitConversion for more information.
1647 bool SuppressUserConversions,
1648 AllowedExplicit AllowExplicit,
1649 bool InOverloadResolution,
1650 bool CStyle,
1651 bool AllowObjCWritebackConversion,
1652 bool AllowObjCConversionOnExplicit) {
1654
1655 if (SuppressUserConversions) {
1656 // We're not in the case above, so there is no conversion that
1657 // we can perform.
1659 return ICS;
1660 }
1661
1662 // Attempt user-defined conversion.
1663 OverloadCandidateSet Conversions(From->getExprLoc(),
1665 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1666 Conversions, AllowExplicit,
1667 AllowObjCConversionOnExplicit)) {
1668 case OR_Success:
1669 case OR_Deleted:
1670 ICS.setUserDefined();
1671 // C++ [over.ics.user]p4:
1672 // A conversion of an expression of class type to the same class
1673 // type is given Exact Match rank, and a conversion of an
1674 // expression of class type to a base class of that type is
1675 // given Conversion rank, in spite of the fact that a copy
1676 // constructor (i.e., a user-defined conversion function) is
1677 // called for those cases.
1678 if (CXXConstructorDecl *Constructor
1679 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1680 QualType FromType;
1681 SourceLocation FromLoc;
1682 // C++11 [over.ics.list]p6, per DR2137:
1683 // C++17 [over.ics.list]p6:
1684 // If C is not an initializer-list constructor and the initializer list
1685 // has a single element of type cv U, where U is X or a class derived
1686 // from X, the implicit conversion sequence has Exact Match rank if U is
1687 // X, or Conversion rank if U is derived from X.
1688 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1689 InitList && InitList->getNumInits() == 1 &&
1690 !S.isInitListConstructor(Constructor)) {
1691 const Expr *SingleInit = InitList->getInit(0);
1692 FromType = SingleInit->getType();
1693 FromLoc = SingleInit->getBeginLoc();
1694 } else {
1695 FromType = From->getType();
1696 FromLoc = From->getBeginLoc();
1697 }
1698 QualType FromCanon =
1700 QualType ToCanon
1702 if ((FromCanon == ToCanon ||
1703 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1704 // Turn this into a "standard" conversion sequence, so that it
1705 // gets ranked with standard conversion sequences.
1707 ICS.setStandard();
1709 ICS.Standard.setFromType(FromType);
1710 ICS.Standard.setAllToTypes(ToType);
1711 ICS.Standard.CopyConstructor = Constructor;
1713 if (ToCanon != FromCanon)
1715 }
1716 }
1717 break;
1718
1719 case OR_Ambiguous:
1720 ICS.setAmbiguous();
1721 ICS.Ambiguous.setFromType(From->getType());
1722 ICS.Ambiguous.setToType(ToType);
1723 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1724 Cand != Conversions.end(); ++Cand)
1725 if (Cand->Best)
1726 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1727 break;
1728
1729 // Fall through.
1732 break;
1733 }
1734
1735 return ICS;
1736}
1737
1738/// TryImplicitConversion - Attempt to perform an implicit conversion
1739/// from the given expression (Expr) to the given type (ToType). This
1740/// function returns an implicit conversion sequence that can be used
1741/// to perform the initialization. Given
1742///
1743/// void f(float f);
1744/// void g(int i) { f(i); }
1745///
1746/// this routine would produce an implicit conversion sequence to
1747/// describe the initialization of f from i, which will be a standard
1748/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1749/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1750//
1751/// Note that this routine only determines how the conversion can be
1752/// performed; it does not actually perform the conversion. As such,
1753/// it will not produce any diagnostics if no conversion is available,
1754/// but will instead return an implicit conversion sequence of kind
1755/// "BadConversion".
1756///
1757/// If @p SuppressUserConversions, then user-defined conversions are
1758/// not permitted.
1759/// If @p AllowExplicit, then explicit user-defined conversions are
1760/// permitted.
1761///
1762/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1763/// writeback conversion, which allows __autoreleasing id* parameters to
1764/// be initialized with __strong id* or __weak id* arguments.
1767 bool SuppressUserConversions,
1768 AllowedExplicit AllowExplicit,
1769 bool InOverloadResolution,
1770 bool CStyle,
1771 bool AllowObjCWritebackConversion,
1772 bool AllowObjCConversionOnExplicit) {
1774 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1775 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1776 ICS.setStandard();
1777 return ICS;
1778 }
1779
1780 if (!S.getLangOpts().CPlusPlus) {
1782 return ICS;
1783 }
1784
1785 // C++ [over.ics.user]p4:
1786 // A conversion of an expression of class type to the same class
1787 // type is given Exact Match rank, and a conversion of an
1788 // expression of class type to a base class of that type is
1789 // given Conversion rank, in spite of the fact that a copy/move
1790 // constructor (i.e., a user-defined conversion function) is
1791 // called for those cases.
1792 QualType FromType = From->getType();
1793 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1794 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1795 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1796 ICS.setStandard();
1798 ICS.Standard.setFromType(FromType);
1799 ICS.Standard.setAllToTypes(ToType);
1800
1801 // We don't actually check at this point whether there is a valid
1802 // copy/move constructor, since overloading just assumes that it
1803 // exists. When we actually perform initialization, we'll find the
1804 // appropriate constructor to copy the returned object, if needed.
1805 ICS.Standard.CopyConstructor = nullptr;
1806
1807 // Determine whether this is considered a derived-to-base conversion.
1808 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1810
1811 return ICS;
1812 }
1813
1814 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1815 FromType->isHLSLAttributedResourceType()) {
1816 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1817 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1818 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1819 FromResType->getWrappedType()) &&
1820 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1821 FromResType->getContainedType()) &&
1822 ToResType->getAttrs() == FromResType->getAttrs()) {
1823 ICS.setStandard();
1825 ICS.Standard.setFromType(FromType);
1826 ICS.Standard.setAllToTypes(ToType);
1827 return ICS;
1828 }
1829 }
1830
1831 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1832 AllowExplicit, InOverloadResolution, CStyle,
1833 AllowObjCWritebackConversion,
1834 AllowObjCConversionOnExplicit);
1835}
1836
1839 bool SuppressUserConversions,
1840 AllowedExplicit AllowExplicit,
1841 bool InOverloadResolution,
1842 bool CStyle,
1843 bool AllowObjCWritebackConversion) {
1844 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1845 AllowExplicit, InOverloadResolution, CStyle,
1846 AllowObjCWritebackConversion,
1847 /*AllowObjCConversionOnExplicit=*/false);
1848}
1849
1851 AssignmentAction Action,
1852 bool AllowExplicit) {
1853 if (checkPlaceholderForOverload(*this, From))
1854 return ExprError();
1855
1856 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1857 bool AllowObjCWritebackConversion =
1858 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1859 Action == AssignmentAction::Sending);
1860 if (getLangOpts().ObjC)
1861 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1862 From->getType(), From);
1864 *this, From, ToType,
1865 /*SuppressUserConversions=*/false,
1866 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1867 /*InOverloadResolution=*/false,
1868 /*CStyle=*/false, AllowObjCWritebackConversion,
1869 /*AllowObjCConversionOnExplicit=*/false);
1870 return PerformImplicitConversion(From, ToType, ICS, Action);
1871}
1872
1874 QualType &ResultTy) {
1875 if (Context.hasSameUnqualifiedType(FromType, ToType))
1876 return false;
1877
1878 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1879 // or F(t noexcept) -> F(t)
1880 // where F adds one of the following at most once:
1881 // - a pointer
1882 // - a member pointer
1883 // - a block pointer
1884 // Changes here need matching changes in FindCompositePointerType.
1885 CanQualType CanTo = Context.getCanonicalType(ToType);
1886 CanQualType CanFrom = Context.getCanonicalType(FromType);
1887 Type::TypeClass TyClass = CanTo->getTypeClass();
1888 if (TyClass != CanFrom->getTypeClass()) return false;
1889 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1890 if (TyClass == Type::Pointer) {
1891 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1892 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1893 } else if (TyClass == Type::BlockPointer) {
1894 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1895 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1896 } else if (TyClass == Type::MemberPointer) {
1897 auto ToMPT = CanTo.castAs<MemberPointerType>();
1898 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1899 // A function pointer conversion cannot change the class of the function.
1900 if (ToMPT->getClass() != FromMPT->getClass())
1901 return false;
1902 CanTo = ToMPT->getPointeeType();
1903 CanFrom = FromMPT->getPointeeType();
1904 } else {
1905 return false;
1906 }
1907
1908 TyClass = CanTo->getTypeClass();
1909 if (TyClass != CanFrom->getTypeClass()) return false;
1910 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1911 return false;
1912 }
1913
1914 const auto *FromFn = cast<FunctionType>(CanFrom);
1915 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1916
1917 const auto *ToFn = cast<FunctionType>(CanTo);
1918 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1919
1920 bool Changed = false;
1921
1922 // Drop 'noreturn' if not present in target type.
1923 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1924 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1925 Changed = true;
1926 }
1927
1928 // Drop 'noexcept' if not present in target type.
1929 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1930 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1931 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1932 FromFn = cast<FunctionType>(
1933 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1934 EST_None)
1935 .getTypePtr());
1936 Changed = true;
1937 }
1938
1939 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1940 // only if the ExtParameterInfo lists of the two function prototypes can be
1941 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1943 bool CanUseToFPT, CanUseFromFPT;
1944 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1945 CanUseFromFPT, NewParamInfos) &&
1946 CanUseToFPT && !CanUseFromFPT) {
1947 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1948 ExtInfo.ExtParameterInfos =
1949 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1950 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1951 FromFPT->getParamTypes(), ExtInfo);
1952 FromFn = QT->getAs<FunctionType>();
1953 Changed = true;
1954 }
1955
1956 // For C, when called from checkPointerTypesForAssignment,
1957 // we need to not alter FromFn, or else even an innocuous cast
1958 // like dropping effects will fail. In C++ however we do want to
1959 // alter FromFn (because of the way PerformImplicitConversion works).
1960 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1961 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1962
1963 // Transparently add/drop effects; here we are concerned with
1964 // language rules/canonicalization. Adding/dropping effects is a warning.
1965 const auto FromFX = FromFPT->getFunctionEffects();
1966 const auto ToFX = ToFPT->getFunctionEffects();
1967 if (FromFX != ToFX) {
1968 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1969 ExtInfo.FunctionEffects = ToFX;
1970 QualType QT = Context.getFunctionType(
1971 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1972 FromFn = QT->getAs<FunctionType>();
1973 Changed = true;
1974 }
1975 }
1976 }
1977
1978 if (!Changed)
1979 return false;
1980
1981 assert(QualType(FromFn, 0).isCanonical());
1982 if (QualType(FromFn, 0) != CanTo) return false;
1983
1984 ResultTy = ToType;
1985 return true;
1986}
1987
1988/// Determine whether the conversion from FromType to ToType is a valid
1989/// floating point conversion.
1990///
1991static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1992 QualType ToType) {
1993 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1994 return false;
1995 // FIXME: disable conversions between long double, __ibm128 and __float128
1996 // if their representation is different until there is back end support
1997 // We of course allow this conversion if long double is really double.
1998
1999 // Conversions between bfloat16 and float16 are currently not supported.
2000 if ((FromType->isBFloat16Type() &&
2001 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2002 (ToType->isBFloat16Type() &&
2003 (FromType->isFloat16Type() || FromType->isHalfType())))
2004 return false;
2005
2006 // Conversions between IEEE-quad and IBM-extended semantics are not
2007 // permitted.
2008 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2009 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2010 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2011 &ToSem == &llvm::APFloat::IEEEquad()) ||
2012 (&FromSem == &llvm::APFloat::IEEEquad() &&
2013 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2014 return false;
2015 return true;
2016}
2017
2018static bool IsVectorElementConversion(Sema &S, QualType FromType,
2019 QualType ToType,
2020 ImplicitConversionKind &ICK, Expr *From) {
2021 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2022 return true;
2023
2024 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2026 return true;
2027 }
2028
2029 if (IsFloatingPointConversion(S, FromType, ToType)) {
2031 return true;
2032 }
2033
2034 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2036 return true;
2037 }
2038
2039 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2041 ToType->isRealFloatingType())) {
2043 return true;
2044 }
2045
2046 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2048 return true;
2049 }
2050
2051 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2052 ToType->isIntegralType(S.Context)) {
2054 return true;
2055 }
2056
2057 return false;
2058}
2059
2060/// Determine whether the conversion from FromType to ToType is a valid
2061/// vector conversion.
2062///
2063/// \param ICK Will be set to the vector conversion kind, if this is a vector
2064/// conversion.
2065static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2067 ImplicitConversionKind &ElConv, Expr *From,
2068 bool InOverloadResolution, bool CStyle) {
2069 // We need at least one of these types to be a vector type to have a vector
2070 // conversion.
2071 if (!ToType->isVectorType() && !FromType->isVectorType())
2072 return false;
2073
2074 // Identical types require no conversions.
2075 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2076 return false;
2077
2078 // HLSL allows implicit truncation of vector types.
2079 if (S.getLangOpts().HLSL) {
2080 auto *ToExtType = ToType->getAs<ExtVectorType>();
2081 auto *FromExtType = FromType->getAs<ExtVectorType>();
2082
2083 // If both arguments are vectors, handle possible vector truncation and
2084 // element conversion.
2085 if (ToExtType && FromExtType) {
2086 unsigned FromElts = FromExtType->getNumElements();
2087 unsigned ToElts = ToExtType->getNumElements();
2088 if (FromElts < ToElts)
2089 return false;
2090 if (FromElts == ToElts)
2091 ElConv = ICK_Identity;
2092 else
2094
2095 QualType FromElTy = FromExtType->getElementType();
2096 QualType ToElTy = ToExtType->getElementType();
2097 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2098 return true;
2099 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2100 }
2101 if (FromExtType && !ToExtType) {
2103 QualType FromElTy = FromExtType->getElementType();
2104 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2105 return true;
2106 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2107 }
2108 // Fallthrough for the case where ToType is a vector and FromType is not.
2109 }
2110
2111 // There are no conversions between extended vector types, only identity.
2112 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2113 if (FromType->getAs<ExtVectorType>()) {
2114 // There are no conversions between extended vector types other than the
2115 // identity conversion.
2116 return false;
2117 }
2118
2119 // Vector splat from any arithmetic type to a vector.
2120 if (FromType->isArithmeticType()) {
2121 if (S.getLangOpts().HLSL) {
2122 ElConv = ICK_HLSL_Vector_Splat;
2123 QualType ToElTy = ToExtType->getElementType();
2124 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2125 }
2126 ICK = ICK_Vector_Splat;
2127 return true;
2128 }
2129 }
2130
2131 if (ToType->isSVESizelessBuiltinType() ||
2132 FromType->isSVESizelessBuiltinType())
2133 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2134 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2136 return true;
2137 }
2138
2139 if (ToType->isRVVSizelessBuiltinType() ||
2140 FromType->isRVVSizelessBuiltinType())
2141 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2142 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2144 return true;
2145 }
2146
2147 // We can perform the conversion between vector types in the following cases:
2148 // 1)vector types are equivalent AltiVec and GCC vector types
2149 // 2)lax vector conversions are permitted and the vector types are of the
2150 // same size
2151 // 3)the destination type does not have the ARM MVE strict-polymorphism
2152 // attribute, which inhibits lax vector conversion for overload resolution
2153 // only
2154 if (ToType->isVectorType() && FromType->isVectorType()) {
2155 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2156 (S.isLaxVectorConversion(FromType, ToType) &&
2157 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2158 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2159 S.isLaxVectorConversion(FromType, ToType) &&
2160 S.anyAltivecTypes(FromType, ToType) &&
2161 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2162 !InOverloadResolution && !CStyle) {
2163 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2164 << FromType << ToType;
2165 }
2167 return true;
2168 }
2169 }
2170
2171 return false;
2172}
2173
2174static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2175 bool InOverloadResolution,
2177 bool CStyle);
2178
2179/// IsStandardConversion - Determines whether there is a standard
2180/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2181/// expression From to the type ToType. Standard conversion sequences
2182/// only consider non-class types; for conversions that involve class
2183/// types, use TryImplicitConversion. If a conversion exists, SCS will
2184/// contain the standard conversion sequence required to perform this
2185/// conversion and this routine will return true. Otherwise, this
2186/// routine will return false and the value of SCS is unspecified.
2187static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2188 bool InOverloadResolution,
2190 bool CStyle,
2191 bool AllowObjCWritebackConversion) {
2192 QualType FromType = From->getType();
2193
2194 // Standard conversions (C++ [conv])
2196 SCS.IncompatibleObjC = false;
2197 SCS.setFromType(FromType);
2198 SCS.CopyConstructor = nullptr;
2199
2200 // There are no standard conversions for class types in C++, so
2201 // abort early. When overloading in C, however, we do permit them.
2202 if (S.getLangOpts().CPlusPlus &&
2203 (FromType->isRecordType() || ToType->isRecordType()))
2204 return false;
2205
2206 // The first conversion can be an lvalue-to-rvalue conversion,
2207 // array-to-pointer conversion, or function-to-pointer conversion
2208 // (C++ 4p1).
2209
2210 if (FromType == S.Context.OverloadTy) {
2211 DeclAccessPair AccessPair;
2212 if (FunctionDecl *Fn
2213 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2214 AccessPair)) {
2215 // We were able to resolve the address of the overloaded function,
2216 // so we can convert to the type of that function.
2217 FromType = Fn->getType();
2218 SCS.setFromType(FromType);
2219
2220 // we can sometimes resolve &foo<int> regardless of ToType, so check
2221 // if the type matches (identity) or we are converting to bool
2223 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2224 QualType resultTy;
2225 // if the function type matches except for [[noreturn]], it's ok
2226 if (!S.IsFunctionConversion(FromType,
2227 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2228 // otherwise, only a boolean conversion is standard
2229 if (!ToType->isBooleanType())
2230 return false;
2231 }
2232
2233 // Check if the "from" expression is taking the address of an overloaded
2234 // function and recompute the FromType accordingly. Take advantage of the
2235 // fact that non-static member functions *must* have such an address-of
2236 // expression.
2237 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2238 if (Method && !Method->isStatic() &&
2239 !Method->isExplicitObjectMemberFunction()) {
2240 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2241 "Non-unary operator on non-static member address");
2242 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2243 == UO_AddrOf &&
2244 "Non-address-of operator on non-static member address");
2245 const Type *ClassType
2247 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2248 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2249 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2250 UO_AddrOf &&
2251 "Non-address-of operator for overloaded function expression");
2252 FromType = S.Context.getPointerType(FromType);
2253 }
2254 } else {
2255 return false;
2256 }
2257 }
2258
2259 bool argIsLValue = From->isGLValue();
2260 // To handle conversion from ArrayParameterType to ConstantArrayType
2261 // this block must be above the one below because Array parameters
2262 // do not decay and when handling HLSLOutArgExprs and
2263 // the From expression is an LValue.
2264 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2265 ToType->isConstantArrayType()) {
2266 // HLSL constant array parameters do not decay, so if the argument is a
2267 // constant array and the parameter is an ArrayParameterType we have special
2268 // handling here.
2269 if (ToType->isArrayParameterType()) {
2270 FromType = S.Context.getArrayParameterType(FromType);
2272 } else if (FromType->isArrayParameterType()) {
2273 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2274 FromType = APT->getConstantArrayType(S.Context);
2276 } else {
2277 SCS.First = ICK_Identity;
2278 }
2279
2280 if (S.Context.getCanonicalType(FromType) !=
2281 S.Context.getCanonicalType(ToType))
2282 return false;
2283
2284 SCS.setAllToTypes(ToType);
2285 return true;
2286 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2287 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2288 // Lvalue-to-rvalue conversion (C++11 4.1):
2289 // A glvalue (3.10) of a non-function, non-array type T can
2290 // be converted to a prvalue.
2291
2293
2294 // C11 6.3.2.1p2:
2295 // ... if the lvalue has atomic type, the value has the non-atomic version
2296 // of the type of the lvalue ...
2297 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2298 FromType = Atomic->getValueType();
2299
2300 // If T is a non-class type, the type of the rvalue is the
2301 // cv-unqualified version of T. Otherwise, the type of the rvalue
2302 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2303 // just strip the qualifiers because they don't matter.
2304 FromType = FromType.getUnqualifiedType();
2305 } else if (FromType->isArrayType()) {
2306 // Array-to-pointer conversion (C++ 4.2)
2308
2309 // An lvalue or rvalue of type "array of N T" or "array of unknown
2310 // bound of T" can be converted to an rvalue of type "pointer to
2311 // T" (C++ 4.2p1).
2312 FromType = S.Context.getArrayDecayedType(FromType);
2313
2314 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2315 // This conversion is deprecated in C++03 (D.4)
2317
2318 // For the purpose of ranking in overload resolution
2319 // (13.3.3.1.1), this conversion is considered an
2320 // array-to-pointer conversion followed by a qualification
2321 // conversion (4.4). (C++ 4.2p2)
2322 SCS.Second = ICK_Identity;
2325 SCS.setAllToTypes(FromType);
2326 return true;
2327 }
2328 } else if (FromType->isFunctionType() && argIsLValue) {
2329 // Function-to-pointer conversion (C++ 4.3).
2331
2332 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2333 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2335 return false;
2336
2337 // An lvalue of function type T can be converted to an rvalue of
2338 // type "pointer to T." The result is a pointer to the
2339 // function. (C++ 4.3p1).
2340 FromType = S.Context.getPointerType(FromType);
2341 } else {
2342 // We don't require any conversions for the first step.
2343 SCS.First = ICK_Identity;
2344 }
2345 SCS.setToType(0, FromType);
2346
2347 // The second conversion can be an integral promotion, floating
2348 // point promotion, integral conversion, floating point conversion,
2349 // floating-integral conversion, pointer conversion,
2350 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2351 // For overloading in C, this can also be a "compatible-type"
2352 // conversion.
2353 bool IncompatibleObjC = false;
2355 ImplicitConversionKind DimensionICK = ICK_Identity;
2356 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2357 // The unqualified versions of the types are the same: there's no
2358 // conversion to do.
2359 SCS.Second = ICK_Identity;
2360 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2361 // Integral promotion (C++ 4.5).
2363 FromType = ToType.getUnqualifiedType();
2364 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2365 // Floating point promotion (C++ 4.6).
2367 FromType = ToType.getUnqualifiedType();
2368 } else if (S.IsComplexPromotion(FromType, ToType)) {
2369 // Complex promotion (Clang extension)
2371 FromType = ToType.getUnqualifiedType();
2372 } else if (ToType->isBooleanType() &&
2373 (FromType->isArithmeticType() ||
2374 FromType->isAnyPointerType() ||
2375 FromType->isBlockPointerType() ||
2376 FromType->isMemberPointerType())) {
2377 // Boolean conversions (C++ 4.12).
2379 FromType = S.Context.BoolTy;
2380 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2381 ToType->isIntegralType(S.Context)) {
2382 // Integral conversions (C++ 4.7).
2384 FromType = ToType.getUnqualifiedType();
2385 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2386 // Complex conversions (C99 6.3.1.6)
2388 FromType = ToType.getUnqualifiedType();
2389 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2390 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2391 // Complex-real conversions (C99 6.3.1.7)
2393 FromType = ToType.getUnqualifiedType();
2394 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2395 // Floating point conversions (C++ 4.8).
2397 FromType = ToType.getUnqualifiedType();
2398 } else if ((FromType->isRealFloatingType() &&
2399 ToType->isIntegralType(S.Context)) ||
2401 ToType->isRealFloatingType())) {
2402
2403 // Floating-integral conversions (C++ 4.9).
2405 FromType = ToType.getUnqualifiedType();
2406 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2408 } else if (AllowObjCWritebackConversion &&
2409 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2411 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2412 FromType, IncompatibleObjC)) {
2413 // Pointer conversions (C++ 4.10).
2415 SCS.IncompatibleObjC = IncompatibleObjC;
2416 FromType = FromType.getUnqualifiedType();
2417 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2418 InOverloadResolution, FromType)) {
2419 // Pointer to member conversions (4.11).
2421 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2422 From, InOverloadResolution, CStyle)) {
2423 SCS.Second = SecondICK;
2424 SCS.Dimension = DimensionICK;
2425 FromType = ToType.getUnqualifiedType();
2426 } else if (!S.getLangOpts().CPlusPlus &&
2427 S.Context.typesAreCompatible(ToType, FromType)) {
2428 // Compatible conversions (Clang extension for C function overloading)
2430 FromType = ToType.getUnqualifiedType();
2432 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2434 FromType = ToType;
2435 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2436 CStyle)) {
2437 // tryAtomicConversion has updated the standard conversion sequence
2438 // appropriately.
2439 return true;
2440 } else if (ToType->isEventT() &&
2442 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2444 FromType = ToType;
2445 } else if (ToType->isQueueT() &&
2447 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2449 FromType = ToType;
2450 } else if (ToType->isSamplerT() &&
2453 FromType = ToType;
2454 } else if ((ToType->isFixedPointType() &&
2455 FromType->isConvertibleToFixedPointType()) ||
2456 (FromType->isFixedPointType() &&
2457 ToType->isConvertibleToFixedPointType())) {
2459 FromType = ToType;
2460 } else {
2461 // No second conversion required.
2462 SCS.Second = ICK_Identity;
2463 }
2464 SCS.setToType(1, FromType);
2465
2466 // The third conversion can be a function pointer conversion or a
2467 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2468 bool ObjCLifetimeConversion;
2469 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2470 // Function pointer conversions (removing 'noexcept') including removal of
2471 // 'noreturn' (Clang extension).
2473 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2474 ObjCLifetimeConversion)) {
2476 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2477 FromType = ToType;
2478 } else {
2479 // No conversion required
2480 SCS.Third = ICK_Identity;
2481 }
2482
2483 // C++ [over.best.ics]p6:
2484 // [...] Any difference in top-level cv-qualification is
2485 // subsumed by the initialization itself and does not constitute
2486 // a conversion. [...]
2487 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2488 QualType CanonTo = S.Context.getCanonicalType(ToType);
2489 if (CanonFrom.getLocalUnqualifiedType()
2490 == CanonTo.getLocalUnqualifiedType() &&
2491 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2492 FromType = ToType;
2493 CanonFrom = CanonTo;
2494 }
2495
2496 SCS.setToType(2, FromType);
2497
2498 if (CanonFrom == CanonTo)
2499 return true;
2500
2501 // If we have not converted the argument type to the parameter type,
2502 // this is a bad conversion sequence, unless we're resolving an overload in C.
2503 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2504 return false;
2505
2506 ExprResult ER = ExprResult{From};
2509 /*Diagnose=*/false,
2510 /*DiagnoseCFAudited=*/false,
2511 /*ConvertRHS=*/false);
2512 ImplicitConversionKind SecondConv;
2513 switch (Conv) {
2514 case Sema::Compatible:
2515 SecondConv = ICK_C_Only_Conversion;
2516 break;
2517 // For our purposes, discarding qualifiers is just as bad as using an
2518 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2519 // qualifiers, as well.
2524 break;
2525 default:
2526 return false;
2527 }
2528
2529 // First can only be an lvalue conversion, so we pretend that this was the
2530 // second conversion. First should already be valid from earlier in the
2531 // function.
2532 SCS.Second = SecondConv;
2533 SCS.setToType(1, ToType);
2534
2535 // Third is Identity, because Second should rank us worse than any other
2536 // conversion. This could also be ICK_Qualification, but it's simpler to just
2537 // lump everything in with the second conversion, and we don't gain anything
2538 // from making this ICK_Qualification.
2539 SCS.Third = ICK_Identity;
2540 SCS.setToType(2, ToType);
2541 return true;
2542}
2543
2544static bool
2546 QualType &ToType,
2547 bool InOverloadResolution,
2549 bool CStyle) {
2550
2551 const RecordType *UT = ToType->getAsUnionType();
2552 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2553 return false;
2554 // The field to initialize within the transparent union.
2555 RecordDecl *UD = UT->getDecl();
2556 // It's compatible if the expression matches any of the fields.
2557 for (const auto *it : UD->fields()) {
2558 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2559 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2560 ToType = it->getType();
2561 return true;
2562 }
2563 }
2564 return false;
2565}
2566
2567bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2568 const BuiltinType *To = ToType->getAs<BuiltinType>();
2569 // All integers are built-in.
2570 if (!To) {
2571 return false;
2572 }
2573
2574 // An rvalue of type char, signed char, unsigned char, short int, or
2575 // unsigned short int can be converted to an rvalue of type int if
2576 // int can represent all the values of the source type; otherwise,
2577 // the source rvalue can be converted to an rvalue of type unsigned
2578 // int (C++ 4.5p1).
2579 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2580 !FromType->isEnumeralType()) {
2581 if ( // We can promote any signed, promotable integer type to an int
2582 (FromType->isSignedIntegerType() ||
2583 // We can promote any unsigned integer type whose size is
2584 // less than int to an int.
2585 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2586 return To->getKind() == BuiltinType::Int;
2587 }
2588
2589 return To->getKind() == BuiltinType::UInt;
2590 }
2591
2592 // C++11 [conv.prom]p3:
2593 // A prvalue of an unscoped enumeration type whose underlying type is not
2594 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2595 // following types that can represent all the values of the enumeration
2596 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2597 // unsigned int, long int, unsigned long int, long long int, or unsigned
2598 // long long int. If none of the types in that list can represent all the
2599 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2600 // type can be converted to an rvalue a prvalue of the extended integer type
2601 // with lowest integer conversion rank (4.13) greater than the rank of long
2602 // long in which all the values of the enumeration can be represented. If
2603 // there are two such extended types, the signed one is chosen.
2604 // C++11 [conv.prom]p4:
2605 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2606 // can be converted to a prvalue of its underlying type. Moreover, if
2607 // integral promotion can be applied to its underlying type, a prvalue of an
2608 // unscoped enumeration type whose underlying type is fixed can also be
2609 // converted to a prvalue of the promoted underlying type.
2610 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2611 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2612 // provided for a scoped enumeration.
2613 if (FromEnumType->getDecl()->isScoped())
2614 return false;
2615
2616 // We can perform an integral promotion to the underlying type of the enum,
2617 // even if that's not the promoted type. Note that the check for promoting
2618 // the underlying type is based on the type alone, and does not consider
2619 // the bitfield-ness of the actual source expression.
2620 if (FromEnumType->getDecl()->isFixed()) {
2621 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2622 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2623 IsIntegralPromotion(nullptr, Underlying, ToType);
2624 }
2625
2626 // We have already pre-calculated the promotion type, so this is trivial.
2627 if (ToType->isIntegerType() &&
2628 isCompleteType(From->getBeginLoc(), FromType))
2629 return Context.hasSameUnqualifiedType(
2630 ToType, FromEnumType->getDecl()->getPromotionType());
2631
2632 // C++ [conv.prom]p5:
2633 // If the bit-field has an enumerated type, it is treated as any other
2634 // value of that type for promotion purposes.
2635 //
2636 // ... so do not fall through into the bit-field checks below in C++.
2637 if (getLangOpts().CPlusPlus)
2638 return false;
2639 }
2640
2641 // C++0x [conv.prom]p2:
2642 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2643 // to an rvalue a prvalue of the first of the following types that can
2644 // represent all the values of its underlying type: int, unsigned int,
2645 // long int, unsigned long int, long long int, or unsigned long long int.
2646 // If none of the types in that list can represent all the values of its
2647 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2648 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2649 // type.
2650 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2651 ToType->isIntegerType()) {
2652 // Determine whether the type we're converting from is signed or
2653 // unsigned.
2654 bool FromIsSigned = FromType->isSignedIntegerType();
2655 uint64_t FromSize = Context.getTypeSize(FromType);
2656
2657 // The types we'll try to promote to, in the appropriate
2658 // order. Try each of these types.
2659 QualType PromoteTypes[6] = {
2660 Context.IntTy, Context.UnsignedIntTy,
2661 Context.LongTy, Context.UnsignedLongTy ,
2662 Context.LongLongTy, Context.UnsignedLongLongTy
2663 };
2664 for (int Idx = 0; Idx < 6; ++Idx) {
2665 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2666 if (FromSize < ToSize ||
2667 (FromSize == ToSize &&
2668 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2669 // We found the type that we can promote to. If this is the
2670 // type we wanted, we have a promotion. Otherwise, no
2671 // promotion.
2672 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2673 }
2674 }
2675 }
2676
2677 // An rvalue for an integral bit-field (9.6) can be converted to an
2678 // rvalue of type int if int can represent all the values of the
2679 // bit-field; otherwise, it can be converted to unsigned int if
2680 // unsigned int can represent all the values of the bit-field. If
2681 // the bit-field is larger yet, no integral promotion applies to
2682 // it. If the bit-field has an enumerated type, it is treated as any
2683 // other value of that type for promotion purposes (C++ 4.5p3).
2684 // FIXME: We should delay checking of bit-fields until we actually perform the
2685 // conversion.
2686 //
2687 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2688 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2689 // bit-fields and those whose underlying type is larger than int) for GCC
2690 // compatibility.
2691 if (From) {
2692 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2693 std::optional<llvm::APSInt> BitWidth;
2694 if (FromType->isIntegralType(Context) &&
2695 (BitWidth =
2696 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2697 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2698 ToSize = Context.getTypeSize(ToType);
2699
2700 // Are we promoting to an int from a bitfield that fits in an int?
2701 if (*BitWidth < ToSize ||
2702 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2703 return To->getKind() == BuiltinType::Int;
2704 }
2705
2706 // Are we promoting to an unsigned int from an unsigned bitfield
2707 // that fits into an unsigned int?
2708 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2709 return To->getKind() == BuiltinType::UInt;
2710 }
2711
2712 return false;
2713 }
2714 }
2715 }
2716
2717 // An rvalue of type bool can be converted to an rvalue of type int,
2718 // with false becoming zero and true becoming one (C++ 4.5p4).
2719 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2720 return true;
2721 }
2722
2723 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2724 // integral type.
2725 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2726 ToType->isIntegerType())
2727 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2728
2729 return false;
2730}
2731
2733 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2734 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2735 /// An rvalue of type float can be converted to an rvalue of type
2736 /// double. (C++ 4.6p1).
2737 if (FromBuiltin->getKind() == BuiltinType::Float &&
2738 ToBuiltin->getKind() == BuiltinType::Double)
2739 return true;
2740
2741 // C99 6.3.1.5p1:
2742 // When a float is promoted to double or long double, or a
2743 // double is promoted to long double [...].
2744 if (!getLangOpts().CPlusPlus &&
2745 (FromBuiltin->getKind() == BuiltinType::Float ||
2746 FromBuiltin->getKind() == BuiltinType::Double) &&
2747 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2748 ToBuiltin->getKind() == BuiltinType::Float128 ||
2749 ToBuiltin->getKind() == BuiltinType::Ibm128))
2750 return true;
2751
2752 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2753 // or not native half types are enabled.
2754 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2755 (ToBuiltin->getKind() == BuiltinType::Float ||
2756 ToBuiltin->getKind() == BuiltinType::Double))
2757 return true;
2758
2759 // Half can be promoted to float.
2760 if (!getLangOpts().NativeHalfType &&
2761 FromBuiltin->getKind() == BuiltinType::Half &&
2762 ToBuiltin->getKind() == BuiltinType::Float)
2763 return true;
2764 }
2765
2766 return false;
2767}
2768
2770 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2771 if (!FromComplex)
2772 return false;
2773
2774 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2775 if (!ToComplex)
2776 return false;
2777
2778 return IsFloatingPointPromotion(FromComplex->getElementType(),
2779 ToComplex->getElementType()) ||
2780 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2781 ToComplex->getElementType());
2782}
2783
2784/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2785/// the pointer type FromPtr to a pointer to type ToPointee, with the
2786/// same type qualifiers as FromPtr has on its pointee type. ToType,
2787/// if non-empty, will be a pointer to ToType that may or may not have
2788/// the right set of qualifiers on its pointee.
2789///
2790static QualType
2792 QualType ToPointee, QualType ToType,
2793 ASTContext &Context,
2794 bool StripObjCLifetime = false) {
2795 assert((FromPtr->getTypeClass() == Type::Pointer ||
2796 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2797 "Invalid similarly-qualified pointer type");
2798
2799 /// Conversions to 'id' subsume cv-qualifier conversions.
2800 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2801 return ToType.getUnqualifiedType();
2802
2803 QualType CanonFromPointee
2804 = Context.getCanonicalType(FromPtr->getPointeeType());
2805 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2806 Qualifiers Quals = CanonFromPointee.getQualifiers();
2807
2808 if (StripObjCLifetime)
2809 Quals.removeObjCLifetime();
2810
2811 // Exact qualifier match -> return the pointer type we're converting to.
2812 if (CanonToPointee.getLocalQualifiers() == Quals) {
2813 // ToType is exactly what we need. Return it.
2814 if (!ToType.isNull())
2815 return ToType.getUnqualifiedType();
2816
2817 // Build a pointer to ToPointee. It has the right qualifiers
2818 // already.
2819 if (isa<ObjCObjectPointerType>(ToType))
2820 return Context.getObjCObjectPointerType(ToPointee);
2821 return Context.getPointerType(ToPointee);
2822 }
2823
2824 // Just build a canonical type that has the right qualifiers.
2825 QualType QualifiedCanonToPointee
2826 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2827
2828 if (isa<ObjCObjectPointerType>(ToType))
2829 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2830 return Context.getPointerType(QualifiedCanonToPointee);
2831}
2832
2834 bool InOverloadResolution,
2835 ASTContext &Context) {
2836 // Handle value-dependent integral null pointer constants correctly.
2837 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2838 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2840 return !InOverloadResolution;
2841
2842 return Expr->isNullPointerConstant(Context,
2843 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2845}
2846
2848 bool InOverloadResolution,
2849 QualType& ConvertedType,
2850 bool &IncompatibleObjC) {
2851 IncompatibleObjC = false;
2852 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2853 IncompatibleObjC))
2854 return true;
2855
2856 // Conversion from a null pointer constant to any Objective-C pointer type.
2857 if (ToType->isObjCObjectPointerType() &&
2858 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2859 ConvertedType = ToType;
2860 return true;
2861 }
2862
2863 // Blocks: Block pointers can be converted to void*.
2864 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2865 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2866 ConvertedType = ToType;
2867 return true;
2868 }
2869 // Blocks: A null pointer constant can be converted to a block
2870 // pointer type.
2871 if (ToType->isBlockPointerType() &&
2872 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2873 ConvertedType = ToType;
2874 return true;
2875 }
2876
2877 // If the left-hand-side is nullptr_t, the right side can be a null
2878 // pointer constant.
2879 if (ToType->isNullPtrType() &&
2880 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2881 ConvertedType = ToType;
2882 return true;
2883 }
2884
2885 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2886 if (!ToTypePtr)
2887 return false;
2888
2889 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2890 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2891 ConvertedType = ToType;
2892 return true;
2893 }
2894
2895 // Beyond this point, both types need to be pointers
2896 // , including objective-c pointers.
2897 QualType ToPointeeType = ToTypePtr->getPointeeType();
2898 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2899 !getLangOpts().ObjCAutoRefCount) {
2900 ConvertedType = BuildSimilarlyQualifiedPointerType(
2901 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2902 Context);
2903 return true;
2904 }
2905 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2906 if (!FromTypePtr)
2907 return false;
2908
2909 QualType FromPointeeType = FromTypePtr->getPointeeType();
2910
2911 // If the unqualified pointee types are the same, this can't be a
2912 // pointer conversion, so don't do all of the work below.
2913 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2914 return false;
2915
2916 // An rvalue of type "pointer to cv T," where T is an object type,
2917 // can be converted to an rvalue of type "pointer to cv void" (C++
2918 // 4.10p2).
2919 if (FromPointeeType->isIncompleteOrObjectType() &&
2920 ToPointeeType->isVoidType()) {
2921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2922 ToPointeeType,
2923 ToType, Context,
2924 /*StripObjCLifetime=*/true);
2925 return true;
2926 }
2927
2928 // MSVC allows implicit function to void* type conversion.
2929 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2930 ToPointeeType->isVoidType()) {
2931 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2932 ToPointeeType,
2933 ToType, Context);
2934 return true;
2935 }
2936
2937 // When we're overloading in C, we allow a special kind of pointer
2938 // conversion for compatible-but-not-identical pointee types.
2939 if (!getLangOpts().CPlusPlus &&
2940 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2941 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2942 ToPointeeType,
2943 ToType, Context);
2944 return true;
2945 }
2946
2947 // C++ [conv.ptr]p3:
2948 //
2949 // An rvalue of type "pointer to cv D," where D is a class type,
2950 // can be converted to an rvalue of type "pointer to cv B," where
2951 // B is a base class (clause 10) of D. If B is an inaccessible
2952 // (clause 11) or ambiguous (10.2) base class of D, a program that
2953 // necessitates this conversion is ill-formed. The result of the
2954 // conversion is a pointer to the base class sub-object of the
2955 // derived class object. The null pointer value is converted to
2956 // the null pointer value of the destination type.
2957 //
2958 // Note that we do not check for ambiguity or inaccessibility
2959 // here. That is handled by CheckPointerConversion.
2960 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2961 ToPointeeType->isRecordType() &&
2962 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2963 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2964 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2965 ToPointeeType,
2966 ToType, Context);
2967 return true;
2968 }
2969
2970 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2971 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2972 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2973 ToPointeeType,
2974 ToType, Context);
2975 return true;
2976 }
2977
2978 return false;
2979}
2980
2981/// Adopt the given qualifiers for the given type.
2983 Qualifiers TQs = T.getQualifiers();
2984
2985 // Check whether qualifiers already match.
2986 if (TQs == Qs)
2987 return T;
2988
2989 if (Qs.compatiblyIncludes(TQs, Context))
2990 return Context.getQualifiedType(T, Qs);
2991
2992 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2993}
2994
2996 QualType& ConvertedType,
2997 bool &IncompatibleObjC) {
2998 if (!getLangOpts().ObjC)
2999 return false;
3000
3001 // The set of qualifiers on the type we're converting from.
3002 Qualifiers FromQualifiers = FromType.getQualifiers();
3003
3004 // First, we handle all conversions on ObjC object pointer types.
3005 const ObjCObjectPointerType* ToObjCPtr =
3006 ToType->getAs<ObjCObjectPointerType>();
3007 const ObjCObjectPointerType *FromObjCPtr =
3008 FromType->getAs<ObjCObjectPointerType>();
3009
3010 if (ToObjCPtr && FromObjCPtr) {
3011 // If the pointee types are the same (ignoring qualifications),
3012 // then this is not a pointer conversion.
3013 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3014 FromObjCPtr->getPointeeType()))
3015 return false;
3016
3017 // Conversion between Objective-C pointers.
3018 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3019 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3020 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3021 if (getLangOpts().CPlusPlus && LHS && RHS &&
3023 FromObjCPtr->getPointeeType(), getASTContext()))
3024 return false;
3025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3026 ToObjCPtr->getPointeeType(),
3027 ToType, Context);
3028 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3029 return true;
3030 }
3031
3032 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3033 // Okay: this is some kind of implicit downcast of Objective-C
3034 // interfaces, which is permitted. However, we're going to
3035 // complain about it.
3036 IncompatibleObjC = true;
3037 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3038 ToObjCPtr->getPointeeType(),
3039 ToType, Context);
3040 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3041 return true;
3042 }
3043 }
3044 // Beyond this point, both types need to be C pointers or block pointers.
3045 QualType ToPointeeType;
3046 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3047 ToPointeeType = ToCPtr->getPointeeType();
3048 else if (const BlockPointerType *ToBlockPtr =
3049 ToType->getAs<BlockPointerType>()) {
3050 // Objective C++: We're able to convert from a pointer to any object
3051 // to a block pointer type.
3052 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3053 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3054 return true;
3055 }
3056 ToPointeeType = ToBlockPtr->getPointeeType();
3057 }
3058 else if (FromType->getAs<BlockPointerType>() &&
3059 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3060 // Objective C++: We're able to convert from a block pointer type to a
3061 // pointer to any object.
3062 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3063 return true;
3064 }
3065 else
3066 return false;
3067
3068 QualType FromPointeeType;
3069 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3070 FromPointeeType = FromCPtr->getPointeeType();
3071 else if (const BlockPointerType *FromBlockPtr =
3072 FromType->getAs<BlockPointerType>())
3073 FromPointeeType = FromBlockPtr->getPointeeType();
3074 else
3075 return false;
3076
3077 // If we have pointers to pointers, recursively check whether this
3078 // is an Objective-C conversion.
3079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3081 IncompatibleObjC)) {
3082 // We always complain about this conversion.
3083 IncompatibleObjC = true;
3084 ConvertedType = Context.getPointerType(ConvertedType);
3085 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3086 return true;
3087 }
3088 // Allow conversion of pointee being objective-c pointer to another one;
3089 // as in I* to id.
3090 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3091 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3092 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3093 IncompatibleObjC)) {
3094
3095 ConvertedType = Context.getPointerType(ConvertedType);
3096 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3097 return true;
3098 }
3099
3100 // If we have pointers to functions or blocks, check whether the only
3101 // differences in the argument and result types are in Objective-C
3102 // pointer conversions. If so, we permit the conversion (but
3103 // complain about it).
3104 const FunctionProtoType *FromFunctionType
3105 = FromPointeeType->getAs<FunctionProtoType>();
3106 const FunctionProtoType *ToFunctionType
3107 = ToPointeeType->getAs<FunctionProtoType>();
3108 if (FromFunctionType && ToFunctionType) {
3109 // If the function types are exactly the same, this isn't an
3110 // Objective-C pointer conversion.
3111 if (Context.getCanonicalType(FromPointeeType)
3112 == Context.getCanonicalType(ToPointeeType))
3113 return false;
3114
3115 // Perform the quick checks that will tell us whether these
3116 // function types are obviously different.
3117 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3118 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3119 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3120 return false;
3121
3122 bool HasObjCConversion = false;
3123 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3124 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3125 // Okay, the types match exactly. Nothing to do.
3126 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3127 ToFunctionType->getReturnType(),
3128 ConvertedType, IncompatibleObjC)) {
3129 // Okay, we have an Objective-C pointer conversion.
3130 HasObjCConversion = true;
3131 } else {
3132 // Function types are too different. Abort.
3133 return false;
3134 }
3135
3136 // Check argument types.
3137 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3138 ArgIdx != NumArgs; ++ArgIdx) {
3139 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3140 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3141 if (Context.getCanonicalType(FromArgType)
3142 == Context.getCanonicalType(ToArgType)) {
3143 // Okay, the types match exactly. Nothing to do.
3144 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3145 ConvertedType, IncompatibleObjC)) {
3146 // Okay, we have an Objective-C pointer conversion.
3147 HasObjCConversion = true;
3148 } else {
3149 // Argument types are too different. Abort.
3150 return false;
3151 }
3152 }
3153
3154 if (HasObjCConversion) {
3155 // We had an Objective-C conversion. Allow this pointer
3156 // conversion, but complain about it.
3157 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3158 IncompatibleObjC = true;
3159 return true;
3160 }
3161 }
3162
3163 return false;
3164}
3165
3167 QualType& ConvertedType) {
3168 QualType ToPointeeType;
3169 if (const BlockPointerType *ToBlockPtr =
3170 ToType->getAs<BlockPointerType>())
3171 ToPointeeType = ToBlockPtr->getPointeeType();
3172 else
3173 return false;
3174
3175 QualType FromPointeeType;
3176 if (const BlockPointerType *FromBlockPtr =
3177 FromType->getAs<BlockPointerType>())
3178 FromPointeeType = FromBlockPtr->getPointeeType();
3179 else
3180 return false;
3181 // We have pointer to blocks, check whether the only
3182 // differences in the argument and result types are in Objective-C
3183 // pointer conversions. If so, we permit the conversion.
3184
3185 const FunctionProtoType *FromFunctionType
3186 = FromPointeeType->getAs<FunctionProtoType>();
3187 const FunctionProtoType *ToFunctionType
3188 = ToPointeeType->getAs<FunctionProtoType>();
3189
3190 if (!FromFunctionType || !ToFunctionType)
3191 return false;
3192
3193 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3194 return true;
3195
3196 // Perform the quick checks that will tell us whether these
3197 // function types are obviously different.
3198 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3199 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3200 return false;
3201
3202 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3203 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3204 if (FromEInfo != ToEInfo)
3205 return false;
3206
3207 bool IncompatibleObjC = false;
3208 if (Context.hasSameType(FromFunctionType->getReturnType(),
3209 ToFunctionType->getReturnType())) {
3210 // Okay, the types match exactly. Nothing to do.
3211 } else {
3212 QualType RHS = FromFunctionType->getReturnType();
3213 QualType LHS = ToFunctionType->getReturnType();
3214 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3215 !RHS.hasQualifiers() && LHS.hasQualifiers())
3216 LHS = LHS.getUnqualifiedType();
3217
3218 if (Context.hasSameType(RHS,LHS)) {
3219 // OK exact match.
3220 } else if (isObjCPointerConversion(RHS, LHS,
3221 ConvertedType, IncompatibleObjC)) {
3222 if (IncompatibleObjC)
3223 return false;
3224 // Okay, we have an Objective-C pointer conversion.
3225 }
3226 else
3227 return false;
3228 }
3229
3230 // Check argument types.
3231 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3232 ArgIdx != NumArgs; ++ArgIdx) {
3233 IncompatibleObjC = false;
3234 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3235 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3236 if (Context.hasSameType(FromArgType, ToArgType)) {
3237 // Okay, the types match exactly. Nothing to do.
3238 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3239 ConvertedType, IncompatibleObjC)) {
3240 if (IncompatibleObjC)
3241 return false;
3242 // Okay, we have an Objective-C pointer conversion.
3243 } else
3244 // Argument types are too different. Abort.
3245 return false;
3246 }
3247
3249 bool CanUseToFPT, CanUseFromFPT;
3250 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3251 CanUseToFPT, CanUseFromFPT,
3252 NewParamInfos))
3253 return false;
3254
3255 ConvertedType = ToType;
3256 return true;
3257}
3258
3259enum {
3268
3269/// Attempts to get the FunctionProtoType from a Type. Handles
3270/// MemberFunctionPointers properly.
3272 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3273 return FPT;
3274
3275 if (auto *MPT = FromType->getAs<MemberPointerType>())
3276 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3277
3278 return nullptr;
3279}
3280
3282 QualType FromType, QualType ToType) {
3283 // If either type is not valid, include no extra info.
3284 if (FromType.isNull() || ToType.isNull()) {
3285 PDiag << ft_default;
3286 return;
3287 }
3288
3289 // Get the function type from the pointers.
3290 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3291 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3292 *ToMember = ToType->castAs<MemberPointerType>();
3293 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3294 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3295 << QualType(FromMember->getClass(), 0);
3296 return;
3297 }
3298 FromType = FromMember->getPointeeType();
3299 ToType = ToMember->getPointeeType();
3300 }
3301
3302 if (FromType->isPointerType())
3303 FromType = FromType->getPointeeType();
3304 if (ToType->isPointerType())
3305 ToType = ToType->getPointeeType();
3306
3307 // Remove references.
3308 FromType = FromType.getNonReferenceType();
3309 ToType = ToType.getNonReferenceType();
3310
3311 // Don't print extra info for non-specialized template functions.
3312 if (FromType->isInstantiationDependentType() &&
3313 !FromType->getAs<TemplateSpecializationType>()) {
3314 PDiag << ft_default;
3315 return;
3316 }
3317
3318 // No extra info for same types.
3319 if (Context.hasSameType(FromType, ToType)) {
3320 PDiag << ft_default;
3321 return;
3322 }
3323
3324 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3325 *ToFunction = tryGetFunctionProtoType(ToType);
3326
3327 // Both types need to be function types.
3328 if (!FromFunction || !ToFunction) {
3329 PDiag << ft_default;
3330 return;
3331 }
3332
3333 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3334 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3335 << FromFunction->getNumParams();
3336 return;
3337 }
3338
3339 // Handle different parameter types.
3340 unsigned ArgPos;
3341 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3342 PDiag << ft_parameter_mismatch << ArgPos + 1
3343 << ToFunction->getParamType(ArgPos)
3344 << FromFunction->getParamType(ArgPos);
3345 return;
3346 }
3347
3348 // Handle different return type.
3349 if (!Context.hasSameType(FromFunction->getReturnType(),
3350 ToFunction->getReturnType())) {
3351 PDiag << ft_return_type << ToFunction->getReturnType()
3352 << FromFunction->getReturnType();
3353 return;
3354 }
3355
3356 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3357 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3358 << FromFunction->getMethodQuals();
3359 return;
3360 }
3361
3362 // Handle exception specification differences on canonical type (in C++17
3363 // onwards).
3364 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3365 ->isNothrow() !=
3366 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3367 ->isNothrow()) {
3368 PDiag << ft_noexcept;
3369 return;
3370 }
3371
3372 // Unable to find a difference, so add no extra info.
3373 PDiag << ft_default;
3374}
3375
3377 ArrayRef<QualType> New, unsigned *ArgPos,
3378 bool Reversed) {
3379 assert(llvm::size(Old) == llvm::size(New) &&
3380 "Can't compare parameters of functions with different number of "
3381 "parameters!");
3382
3383 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3384 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3385 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3386
3387 // Ignore address spaces in pointee type. This is to disallow overloading
3388 // on __ptr32/__ptr64 address spaces.
3389 QualType OldType =
3390 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3391 QualType NewType =
3392 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3393
3394 if (!Context.hasSameType(OldType, NewType)) {
3395 if (ArgPos)
3396 *ArgPos = Idx;
3397 return false;
3398 }
3399 }
3400 return true;
3401}
3402
3404 const FunctionProtoType *NewType,
3405 unsigned *ArgPos, bool Reversed) {
3406 return FunctionParamTypesAreEqual(OldType->param_types(),
3407 NewType->param_types(), ArgPos, Reversed);
3408}
3409
3411 const FunctionDecl *NewFunction,
3412 unsigned *ArgPos,
3413 bool Reversed) {
3414
3415 if (OldFunction->getNumNonObjectParams() !=
3416 NewFunction->getNumNonObjectParams())
3417 return false;
3418
3419 unsigned OldIgnore =
3421 unsigned NewIgnore =
3423
3424 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3425 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3426
3427 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3428 NewPT->param_types().slice(NewIgnore),
3429 ArgPos, Reversed);
3430}
3431
3433 CastKind &Kind,
3434 CXXCastPath& BasePath,
3435 bool IgnoreBaseAccess,
3436 bool Diagnose) {
3437 QualType FromType = From->getType();
3438 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3439
3440 Kind = CK_BitCast;
3441
3442 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3445 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3446 DiagRuntimeBehavior(From->getExprLoc(), From,
3447 PDiag(diag::warn_impcast_bool_to_null_pointer)
3448 << ToType << From->getSourceRange());
3449 else if (!isUnevaluatedContext())
3450 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3451 << ToType << From->getSourceRange();
3452 }
3453 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3454 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3455 QualType FromPointeeType = FromPtrType->getPointeeType(),
3456 ToPointeeType = ToPtrType->getPointeeType();
3457
3458 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3459 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3460 // We must have a derived-to-base conversion. Check an
3461 // ambiguous or inaccessible conversion.
3462 unsigned InaccessibleID = 0;
3463 unsigned AmbiguousID = 0;
3464 if (Diagnose) {
3465 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3466 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3467 }
3468 if (CheckDerivedToBaseConversion(
3469 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3470 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3471 &BasePath, IgnoreBaseAccess))
3472 return true;
3473
3474 // The conversion was successful.
3475 Kind = CK_DerivedToBase;
3476 }
3477
3478 if (Diagnose && !IsCStyleOrFunctionalCast &&
3479 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3480 assert(getLangOpts().MSVCCompat &&
3481 "this should only be possible with MSVCCompat!");
3482 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3483 << From->getSourceRange();
3484 }
3485 }
3486 } else if (const ObjCObjectPointerType *ToPtrType =
3487 ToType->getAs<ObjCObjectPointerType>()) {
3488 if (const ObjCObjectPointerType *FromPtrType =
3489 FromType->getAs<ObjCObjectPointerType>()) {
3490 // Objective-C++ conversions are always okay.
3491 // FIXME: We should have a different class of conversions for the
3492 // Objective-C++ implicit conversions.
3493 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3494 return false;
3495 } else if (FromType->isBlockPointerType()) {
3496 Kind = CK_BlockPointerToObjCPointerCast;
3497 } else {
3498 Kind = CK_CPointerToObjCPointerCast;
3499 }
3500 } else if (ToType->isBlockPointerType()) {
3501 if (!FromType->isBlockPointerType())
3502 Kind = CK_AnyPointerToBlockPointerCast;
3503 }
3504
3505 // We shouldn't fall into this case unless it's valid for other
3506 // reasons.
3508 Kind = CK_NullToPointer;
3509
3510 return false;
3511}
3512
3514 QualType ToType,
3515 bool InOverloadResolution,
3516 QualType &ConvertedType) {
3517 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3518 if (!ToTypePtr)
3519 return false;
3520
3521 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3522 if (From->isNullPointerConstant(Context,
3523 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3525 ConvertedType = ToType;
3526 return true;
3527 }
3528
3529 // Otherwise, both types have to be member pointers.
3530 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3531 if (!FromTypePtr)
3532 return false;
3533
3534 // A pointer to member of B can be converted to a pointer to member of D,
3535 // where D is derived from B (C++ 4.11p2).
3536 QualType FromClass(FromTypePtr->getClass(), 0);
3537 QualType ToClass(ToTypePtr->getClass(), 0);
3538
3539 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3540 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3541 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3542 ToClass.getTypePtr());
3543 return true;
3544 }
3545
3546 return false;
3547}
3548
3550 CastKind &Kind,
3551 CXXCastPath &BasePath,
3552 bool IgnoreBaseAccess) {
3553 QualType FromType = From->getType();
3554 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3555 if (!FromPtrType) {
3556 // This must be a null pointer to member pointer conversion
3557 assert(From->isNullPointerConstant(Context,
3559 "Expr must be null pointer constant!");
3560 Kind = CK_NullToMemberPointer;
3561 return false;
3562 }
3563
3564 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3565 assert(ToPtrType && "No member pointer cast has a target type "
3566 "that is not a member pointer.");
3567
3568 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3569 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3570
3571 // FIXME: What about dependent types?
3572 assert(FromClass->isRecordType() && "Pointer into non-class.");
3573 assert(ToClass->isRecordType() && "Pointer into non-class.");
3574
3575 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3576 /*DetectVirtual=*/true);
3577 bool DerivationOkay =
3578 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3579 assert(DerivationOkay &&
3580 "Should not have been called if derivation isn't OK.");
3581 (void)DerivationOkay;
3582
3583 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3584 getUnqualifiedType())) {
3585 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3586 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3587 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3588 return true;
3589 }
3590
3591 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3592 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3593 << FromClass << ToClass << QualType(VBase, 0)
3594 << From->getSourceRange();
3595 return true;
3596 }
3597
3598 if (!IgnoreBaseAccess)
3599 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3600 Paths.front(),
3601 diag::err_downcast_from_inaccessible_base);
3602
3603 // Must be a base to derived member conversion.
3604 BuildBasePathArray(Paths, BasePath);
3605 Kind = CK_BaseToDerivedMemberPointer;
3606 return false;
3607}
3608
3609/// Determine whether the lifetime conversion between the two given
3610/// qualifiers sets is nontrivial.
3612 Qualifiers ToQuals) {
3613 // Converting anything to const __unsafe_unretained is trivial.
3614 if (ToQuals.hasConst() &&
3616 return false;
3617
3618 return true;
3619}
3620
3621/// Perform a single iteration of the loop for checking if a qualification
3622/// conversion is valid.
3623///
3624/// Specifically, check whether any change between the qualifiers of \p
3625/// FromType and \p ToType is permissible, given knowledge about whether every
3626/// outer layer is const-qualified.
3628 bool CStyle, bool IsTopLevel,
3629 bool &PreviousToQualsIncludeConst,
3630 bool &ObjCLifetimeConversion,
3631 const ASTContext &Ctx) {
3632 Qualifiers FromQuals = FromType.getQualifiers();
3633 Qualifiers ToQuals = ToType.getQualifiers();
3634
3635 // Ignore __unaligned qualifier.
3636 FromQuals.removeUnaligned();
3637
3638 // Objective-C ARC:
3639 // Check Objective-C lifetime conversions.
3640 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3641 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3642 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3643 ObjCLifetimeConversion = true;
3644 FromQuals.removeObjCLifetime();
3645 ToQuals.removeObjCLifetime();
3646 } else {
3647 // Qualification conversions cannot cast between different
3648 // Objective-C lifetime qualifiers.
3649 return false;
3650 }
3651 }
3652
3653 // Allow addition/removal of GC attributes but not changing GC attributes.
3654 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3655 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3656 FromQuals.removeObjCGCAttr();
3657 ToQuals.removeObjCGCAttr();
3658 }
3659
3660 // -- for every j > 0, if const is in cv 1,j then const is in cv
3661 // 2,j, and similarly for volatile.
3662 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3663 return false;
3664
3665 // If address spaces mismatch:
3666 // - in top level it is only valid to convert to addr space that is a
3667 // superset in all cases apart from C-style casts where we allow
3668 // conversions between overlapping address spaces.
3669 // - in non-top levels it is not a valid conversion.
3670 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3671 (!IsTopLevel ||
3672 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3673 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3674 return false;
3675
3676 // -- if the cv 1,j and cv 2,j are different, then const is in
3677 // every cv for 0 < k < j.
3678 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3679 !PreviousToQualsIncludeConst)
3680 return false;
3681
3682 // The following wording is from C++20, where the result of the conversion
3683 // is T3, not T2.
3684 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3685 // "array of unknown bound of"
3686 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3687 return false;
3688
3689 // -- if the resulting P3,i is different from P1,i [...], then const is
3690 // added to every cv 3_k for 0 < k < i.
3691 if (!CStyle && FromType->isConstantArrayType() &&
3692 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3693 return false;
3694
3695 // Keep track of whether all prior cv-qualifiers in the "to" type
3696 // include const.
3697 PreviousToQualsIncludeConst =
3698 PreviousToQualsIncludeConst && ToQuals.hasConst();
3699 return true;
3700}
3701
3702bool
3704 bool CStyle, bool &ObjCLifetimeConversion) {
3705 FromType = Context.getCanonicalType(FromType);
3706 ToType = Context.getCanonicalType(ToType);
3707 ObjCLifetimeConversion = false;
3708
3709 // If FromType and ToType are the same type, this is not a
3710 // qualification conversion.
3711 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3712 return false;
3713
3714 // (C++ 4.4p4):
3715 // A conversion can add cv-qualifiers at levels other than the first
3716 // in multi-level pointers, subject to the following rules: [...]
3717 bool PreviousToQualsIncludeConst = true;
3718 bool UnwrappedAnyPointer = false;
3719 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3720 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3721 !UnwrappedAnyPointer,
3722 PreviousToQualsIncludeConst,
3723 ObjCLifetimeConversion, getASTContext()))
3724 return false;
3725 UnwrappedAnyPointer = true;
3726 }
3727
3728 // We are left with FromType and ToType being the pointee types
3729 // after unwrapping the original FromType and ToType the same number
3730 // of times. If we unwrapped any pointers, and if FromType and
3731 // ToType have the same unqualified type (since we checked
3732 // qualifiers above), then this is a qualification conversion.
3733 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3734}
3735
3736/// - Determine whether this is a conversion from a scalar type to an
3737/// atomic type.
3738///
3739/// If successful, updates \c SCS's second and third steps in the conversion
3740/// sequence to finish the conversion.
3741static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3742 bool InOverloadResolution,
3744 bool CStyle) {
3745 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3746 if (!ToAtomic)
3747 return false;
3748
3750 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3751 InOverloadResolution, InnerSCS,
3752 CStyle, /*AllowObjCWritebackConversion=*/false))
3753 return false;
3754
3755 SCS.Second = InnerSCS.Second;
3756 SCS.setToType(1, InnerSCS.getToType(1));
3757 SCS.Third = InnerSCS.Third;
3760 SCS.setToType(2, InnerSCS.getToType(2));
3761 return true;
3762}
3763
3765 CXXConstructorDecl *Constructor,
3766 QualType Type) {
3767 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3768 if (CtorType->getNumParams() > 0) {
3769 QualType FirstArg = CtorType->getParamType(0);
3770 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3771 return true;
3772 }
3773 return false;
3774}
3775
3776static OverloadingResult
3778 CXXRecordDecl *To,
3780 OverloadCandidateSet &CandidateSet,
3781 bool AllowExplicit) {
3783 for (auto *D : S.LookupConstructors(To)) {
3784 auto Info = getConstructorInfo(D);
3785 if (!Info)
3786 continue;
3787
3788 bool Usable = !Info.Constructor->isInvalidDecl() &&
3789 S.isInitListConstructor(Info.Constructor);
3790 if (Usable) {
3791 bool SuppressUserConversions = false;
3792 if (Info.ConstructorTmpl)
3793 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3794 /*ExplicitArgs*/ nullptr, From,
3795 CandidateSet, SuppressUserConversions,
3796 /*PartialOverloading*/ false,
3797 AllowExplicit);
3798 else
3799 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3800 CandidateSet, SuppressUserConversions,
3801 /*PartialOverloading*/ false, AllowExplicit);
3802 }
3803 }
3804
3805 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3806
3808 switch (auto Result =
3809 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3810 case OR_Deleted:
3811 case OR_Success: {
3812 // Record the standard conversion we used and the conversion function.
3813 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3814 QualType ThisType = Constructor->getFunctionObjectParameterType();
3815 // Initializer lists don't have conversions as such.
3817 User.HadMultipleCandidates = HadMultipleCandidates;
3818 User.ConversionFunction = Constructor;
3819 User.FoundConversionFunction = Best->FoundDecl;
3821 User.After.setFromType(ThisType);
3822 User.After.setAllToTypes(ToType);
3823 return Result;
3824 }
3825
3827 return OR_No_Viable_Function;
3828 case OR_Ambiguous:
3829 return OR_Ambiguous;
3830 }
3831
3832 llvm_unreachable("Invalid OverloadResult!");
3833}
3834
3835/// Determines whether there is a user-defined conversion sequence
3836/// (C++ [over.ics.user]) that converts expression From to the type
3837/// ToType. If such a conversion exists, User will contain the
3838/// user-defined conversion sequence that performs such a conversion
3839/// and this routine will return true. Otherwise, this routine returns
3840/// false and User is unspecified.
3841///
3842/// \param AllowExplicit true if the conversion should consider C++0x
3843/// "explicit" conversion functions as well as non-explicit conversion
3844/// functions (C++0x [class.conv.fct]p2).
3845///
3846/// \param AllowObjCConversionOnExplicit true if the conversion should
3847/// allow an extra Objective-C pointer conversion on uses of explicit
3848/// constructors. Requires \c AllowExplicit to also be set.
3849static OverloadingResult
3852 OverloadCandidateSet &CandidateSet,
3853 AllowedExplicit AllowExplicit,
3854 bool AllowObjCConversionOnExplicit) {
3855 assert(AllowExplicit != AllowedExplicit::None ||
3856 !AllowObjCConversionOnExplicit);
3858
3859 // Whether we will only visit constructors.
3860 bool ConstructorsOnly = false;
3861
3862 // If the type we are conversion to is a class type, enumerate its
3863 // constructors.
3864 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3865 // C++ [over.match.ctor]p1:
3866 // When objects of class type are direct-initialized (8.5), or
3867 // copy-initialized from an expression of the same or a
3868 // derived class type (8.5), overload resolution selects the
3869 // constructor. [...] For copy-initialization, the candidate
3870 // functions are all the converting constructors (12.3.1) of
3871 // that class. The argument list is the expression-list within
3872 // the parentheses of the initializer.
3873 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3874 (From->getType()->getAs<RecordType>() &&
3875 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3876 ConstructorsOnly = true;
3877
3878 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3879 // We're not going to find any constructors.
3880 } else if (CXXRecordDecl *ToRecordDecl
3881 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3882
3883 Expr **Args = &From;
3884 unsigned NumArgs = 1;
3885 bool ListInitializing = false;
3886 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3887 // But first, see if there is an init-list-constructor that will work.
3889 S, From, ToType, ToRecordDecl, User, CandidateSet,
3890 AllowExplicit == AllowedExplicit::All);
3892 return Result;
3893 // Never mind.
3894 CandidateSet.clear(
3896
3897 // If we're list-initializing, we pass the individual elements as
3898 // arguments, not the entire list.
3899 Args = InitList->getInits();
3900 NumArgs = InitList->getNumInits();
3901 ListInitializing = true;
3902 }
3903
3904 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3905 auto Info = getConstructorInfo(D);
3906 if (!Info)
3907 continue;
3908
3909 bool Usable = !Info.Constructor->isInvalidDecl();
3910 if (!ListInitializing)
3911 Usable = Usable && Info.Constructor->isConvertingConstructor(
3912 /*AllowExplicit*/ true);
3913 if (Usable) {
3914 bool SuppressUserConversions = !ConstructorsOnly;
3915 // C++20 [over.best.ics.general]/4.5:
3916 // if the target is the first parameter of a constructor [of class
3917 // X] and the constructor [...] is a candidate by [...] the second
3918 // phase of [over.match.list] when the initializer list has exactly
3919 // one element that is itself an initializer list, [...] and the
3920 // conversion is to X or reference to cv X, user-defined conversion
3921 // sequences are not cnosidered.
3922 if (SuppressUserConversions && ListInitializing) {
3923 SuppressUserConversions =
3924 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3925 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3926 ToType);
3927 }
3928 if (Info.ConstructorTmpl)
3930 Info.ConstructorTmpl, Info.FoundDecl,
3931 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3932 CandidateSet, SuppressUserConversions,
3933 /*PartialOverloading*/ false,
3934 AllowExplicit == AllowedExplicit::All);
3935 else
3936 // Allow one user-defined conversion when user specifies a
3937 // From->ToType conversion via an static cast (c-style, etc).
3938 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3939 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3940 SuppressUserConversions,
3941 /*PartialOverloading*/ false,
3942 AllowExplicit == AllowedExplicit::All);
3943 }
3944 }
3945 }
3946 }
3947
3948 // Enumerate conversion functions, if we're allowed to.
3949 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3950 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3951 // No conversion functions from incomplete types.
3952 } else if (const RecordType *FromRecordType =
3953 From->getType()->getAs<RecordType>()) {
3954 if (CXXRecordDecl *FromRecordDecl
3955 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3956 // Add all of the conversion functions as candidates.
3957 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3958 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3959 DeclAccessPair FoundDecl = I.getPair();
3960 NamedDecl *D = FoundDecl.getDecl();
3961 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3962 if (isa<UsingShadowDecl>(D))
3963 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3964
3965 CXXConversionDecl *Conv;
3966 FunctionTemplateDecl *ConvTemplate;
3967 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3968 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3969 else
3970 Conv = cast<CXXConversionDecl>(D);
3971
3972 if (ConvTemplate)
3974 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3975 CandidateSet, AllowObjCConversionOnExplicit,
3976 AllowExplicit != AllowedExplicit::None);
3977 else
3978 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3979 CandidateSet, AllowObjCConversionOnExplicit,
3980 AllowExplicit != AllowedExplicit::None);
3981 }
3982 }
3983 }
3984
3985 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3986
3988 switch (auto Result =
3989 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3990 case OR_Success:
3991 case OR_Deleted:
3992 // Record the standard conversion we used and the conversion function.
3993 if (CXXConstructorDecl *Constructor
3994 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3995 // C++ [over.ics.user]p1:
3996 // If the user-defined conversion is specified by a
3997 // constructor (12.3.1), the initial standard conversion
3998 // sequence converts the source type to the type required by
3999 // the argument of the constructor.
4000 //
4001 if (isa<InitListExpr>(From)) {
4002 // Initializer lists don't have conversions as such.
4004 } else {
4005 if (Best->Conversions[0].isEllipsis())
4006 User.EllipsisConversion = true;
4007 else {
4008 User.Before = Best->Conversions[0].Standard;
4009 User.EllipsisConversion = false;
4010 }
4011 }
4012 User.HadMultipleCandidates = HadMultipleCandidates;
4013 User.ConversionFunction = Constructor;
4014 User.FoundConversionFunction = Best->FoundDecl;
4016 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4017 User.After.setAllToTypes(ToType);
4018 return Result;
4019 }
4020 if (CXXConversionDecl *Conversion
4021 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4022 // C++ [over.ics.user]p1:
4023 //
4024 // [...] If the user-defined conversion is specified by a
4025 // conversion function (12.3.2), the initial standard
4026 // conversion sequence converts the source type to the
4027 // implicit object parameter of the conversion function.
4028 User.Before = Best->Conversions[0].Standard;
4029 User.HadMultipleCandidates = HadMultipleCandidates;
4030 User.ConversionFunction = Conversion;
4031 User.FoundConversionFunction = Best->FoundDecl;
4032 User.EllipsisConversion = false;
4033
4034 // C++ [over.ics.user]p2:
4035 // The second standard conversion sequence converts the
4036 // result of the user-defined conversion to the target type
4037 // for the sequence. Since an implicit conversion sequence
4038 // is an initialization, the special rules for
4039 // initialization by user-defined conversion apply when
4040 // selecting the best user-defined conversion for a
4041 // user-defined conversion sequence (see 13.3.3 and
4042 // 13.3.3.1).
4043 User.After = Best->FinalConversion;
4044 return Result;
4045 }
4046 llvm_unreachable("Not a constructor or conversion function?");
4047
4049 return OR_No_Viable_Function;
4050
4051 case OR_Ambiguous:
4052 return OR_Ambiguous;
4053 }
4054
4055 llvm_unreachable("Invalid OverloadResult!");
4056}
4057
4058bool
4061 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4063 OverloadingResult OvResult =
4064 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4065 CandidateSet, AllowedExplicit::None, false);
4066
4067 if (!(OvResult == OR_Ambiguous ||
4068 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4069 return false;
4070
4071 auto Cands = CandidateSet.CompleteCandidates(
4072 *this,
4074 From);
4075 if (OvResult == OR_Ambiguous)
4076 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4077 << From->getType() << ToType << From->getSourceRange();
4078 else { // OR_No_Viable_Function && !CandidateSet.empty()
4079 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4080 diag::err_typecheck_nonviable_condition_incomplete,
4081 From->getType(), From->getSourceRange()))
4082 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4083 << false << From->getType() << From->getSourceRange() << ToType;
4084 }
4085
4086 CandidateSet.NoteCandidates(
4087 *this, From, Cands);
4088 return true;
4089}
4090
4091// Helper for compareConversionFunctions that gets the FunctionType that the
4092// conversion-operator return value 'points' to, or nullptr.
4093static const FunctionType *
4095 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4096 const PointerType *RetPtrTy =
4097 ConvFuncTy->getReturnType()->getAs<PointerType>();
4098
4099 if (!RetPtrTy)
4100 return nullptr;
4101
4102 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4103}
4104
4105/// Compare the user-defined conversion functions or constructors
4106/// of two user-defined conversion sequences to determine whether any ordering
4107/// is possible.
4110 FunctionDecl *Function2) {
4111 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4112 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4113 if (!Conv1 || !Conv2)
4115
4116 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4118
4119 // Objective-C++:
4120 // If both conversion functions are implicitly-declared conversions from
4121 // a lambda closure type to a function pointer and a block pointer,
4122 // respectively, always prefer the conversion to a function pointer,
4123 // because the function pointer is more lightweight and is more likely
4124 // to keep code working.
4125 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4126 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4127 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4128 if (Block1 != Block2)
4129 return Block1 ? ImplicitConversionSequence::Worse
4131 }
4132
4133 // In order to support multiple calling conventions for the lambda conversion
4134 // operator (such as when the free and member function calling convention is
4135 // different), prefer the 'free' mechanism, followed by the calling-convention
4136 // of operator(). The latter is in place to support the MSVC-like solution of
4137 // defining ALL of the possible conversions in regards to calling-convention.
4138 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4139 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4140
4141 if (Conv1FuncRet && Conv2FuncRet &&
4142 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4143 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4144 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4145
4146 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4147 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4148
4149 CallingConv CallOpCC =
4150 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4152 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4154 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4155
4156 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4157 for (CallingConv CC : PrefOrder) {
4158 if (Conv1CC == CC)
4160 if (Conv2CC == CC)
4162 }
4163 }
4164
4166}
4167
4169 const ImplicitConversionSequence &ICS) {
4171 (ICS.isUserDefined() &&
4173}
4174
4175/// CompareImplicitConversionSequences - Compare two implicit
4176/// conversion sequences to determine whether one is better than the
4177/// other or if they are indistinguishable (C++ 13.3.3.2).
4180 const ImplicitConversionSequence& ICS1,
4181 const ImplicitConversionSequence& ICS2)
4182{
4183 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4184 // conversion sequences (as defined in 13.3.3.1)
4185 // -- a standard conversion sequence (13.3.3.1.1) is a better
4186 // conversion sequence than a user-defined conversion sequence or
4187 // an ellipsis conversion sequence, and
4188 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4189 // conversion sequence than an ellipsis conversion sequence
4190 // (13.3.3.1.3).
4191 //
4192 // C++0x [over.best.ics]p10:
4193 // For the purpose of ranking implicit conversion sequences as
4194 // described in 13.3.3.2, the ambiguous conversion sequence is
4195 // treated as a user-defined sequence that is indistinguishable
4196 // from any other user-defined conversion sequence.
4197
4198 // String literal to 'char *' conversion has been deprecated in C++03. It has
4199 // been removed from C++11. We still accept this conversion, if it happens at
4200 // the best viable function. Otherwise, this conversion is considered worse
4201 // than ellipsis conversion. Consider this as an extension; this is not in the
4202 // standard. For example:
4203 //
4204 // int &f(...); // #1
4205 // void f(char*); // #2
4206 // void g() { int &r = f("foo"); }
4207 //
4208 // In C++03, we pick #2 as the best viable function.
4209 // In C++11, we pick #1 as the best viable function, because ellipsis
4210 // conversion is better than string-literal to char* conversion (since there
4211 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4212 // convert arguments, #2 would be the best viable function in C++11.
4213 // If the best viable function has this conversion, a warning will be issued
4214 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4215
4216 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4219 // Ill-formedness must not differ
4220 ICS1.isBad() == ICS2.isBad())
4224
4225 if (ICS1.getKindRank() < ICS2.getKindRank())
4227 if (ICS2.getKindRank() < ICS1.getKindRank())
4229
4230 // The following checks require both conversion sequences to be of
4231 // the same kind.
4232 if (ICS1.getKind() != ICS2.getKind())
4234
4237
4238 // Two implicit conversion sequences of the same form are
4239 // indistinguishable conversion sequences unless one of the
4240 // following rules apply: (C++ 13.3.3.2p3):
4241
4242 // List-initialization sequence L1 is a better conversion sequence than
4243 // list-initialization sequence L2 if:
4244 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4245 // if not that,
4246 // — L1 and L2 convert to arrays of the same element type, and either the
4247 // number of elements n_1 initialized by L1 is less than the number of
4248 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4249 // an array of unknown bound and L1 does not,
4250 // even if one of the other rules in this paragraph would otherwise apply.
4251 if (!ICS1.isBad()) {
4252 bool StdInit1 = false, StdInit2 = false;
4255 nullptr);
4258 nullptr);
4259 if (StdInit1 != StdInit2)
4260 return StdInit1 ? ImplicitConversionSequence::Better
4262
4265 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4267 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4269 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4270 CAT2->getElementType())) {
4271 // Both to arrays of the same element type
4272 if (CAT1->getSize() != CAT2->getSize())
4273 // Different sized, the smaller wins
4274 return CAT1->getSize().ult(CAT2->getSize())
4279 // One is incomplete, it loses
4283 }
4284 }
4285 }
4286
4287 if (ICS1.isStandard())
4288 // Standard conversion sequence S1 is a better conversion sequence than
4289 // standard conversion sequence S2 if [...]
4291 ICS1.Standard, ICS2.Standard);
4292 else if (ICS1.isUserDefined()) {
4293 // User-defined conversion sequence U1 is a better conversion
4294 // sequence than another user-defined conversion sequence U2 if
4295 // they contain the same user-defined conversion function or
4296 // constructor and if the second standard conversion sequence of
4297 // U1 is better than the second standard conversion sequence of
4298 // U2 (C++ 13.3.3.2p3).
4302 ICS1.UserDefined.After,
4303 ICS2.UserDefined.After);
4304 else
4308 }
4309
4310 return Result;
4311}
4312
4313// Per 13.3.3.2p3, compare the given standard conversion sequences to
4314// determine if one is a proper subset of the other.
4317 const StandardConversionSequence& SCS1,
4318 const StandardConversionSequence& SCS2) {
4321
4322 // the identity conversion sequence is considered to be a subsequence of
4323 // any non-identity conversion sequence
4324 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4326 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4328
4329 if (SCS1.Second != SCS2.Second) {
4330 if (SCS1.Second == ICK_Identity)
4332 else if (SCS2.Second == ICK_Identity)
4334 else
4336 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4338
4339 if (SCS1.Third == SCS2.Third) {
4340 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4342 }
4343
4344 if (SCS1.Third == ICK_Identity)
4348
4349 if (SCS2.Third == ICK_Identity)
4353
4355}
4356
4357/// Determine whether one of the given reference bindings is better
4358/// than the other based on what kind of bindings they are.
4359static bool
4361 const StandardConversionSequence &SCS2) {
4362 // C++0x [over.ics.rank]p3b4:
4363 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4364 // implicit object parameter of a non-static member function declared
4365 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4366 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4367 // lvalue reference to a function lvalue and S2 binds an rvalue
4368 // reference*.
4369 //
4370 // FIXME: Rvalue references. We're going rogue with the above edits,
4371 // because the semantics in the current C++0x working paper (N3225 at the
4372 // time of this writing) break the standard definition of std::forward
4373 // and std::reference_wrapper when dealing with references to functions.
4374 // Proposed wording changes submitted to CWG for consideration.
4377 return false;
4378
4379 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4380 SCS2.IsLvalueReference) ||
4383}
4384
4386 None,
4389};
4390
4391/// Returns kind of fixed enum promotion the \a SCS uses.
4392static FixedEnumPromotion
4394
4395 if (SCS.Second != ICK_Integral_Promotion)
4396 return FixedEnumPromotion::None;
4397
4398 QualType FromType = SCS.getFromType();
4399 if (!FromType->isEnumeralType())
4400 return FixedEnumPromotion::None;
4401
4402 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4403 if (!Enum->isFixed())
4404 return FixedEnumPromotion::None;
4405
4406 QualType UnderlyingType = Enum->getIntegerType();
4407 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4408 return FixedEnumPromotion::ToUnderlyingType;
4409
4410 return FixedEnumPromotion::ToPromotedUnderlyingType;
4411}
4412
4413/// CompareStandardConversionSequences - Compare two standard
4414/// conversion sequences to determine whether one is better than the
4415/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4418 const StandardConversionSequence& SCS1,
4419 const StandardConversionSequence& SCS2)
4420{
4421 // Standard conversion sequence S1 is a better conversion sequence
4422 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4423
4424 // -- S1 is a proper subsequence of S2 (comparing the conversion
4425 // sequences in the canonical form defined by 13.3.3.1.1,
4426 // excluding any Lvalue Transformation; the identity conversion
4427 // sequence is considered to be a subsequence of any
4428 // non-identity conversion sequence) or, if not that,
4431 return CK;
4432
4433 // -- the rank of S1 is better than the rank of S2 (by the rules
4434 // defined below), or, if not that,
4435 ImplicitConversionRank Rank1 = SCS1.getRank();
4436 ImplicitConversionRank Rank2 = SCS2.getRank();
4437 if (Rank1 < Rank2)
4439 else if (Rank2 < Rank1)
4441
4442 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4443 // are indistinguishable unless one of the following rules
4444 // applies:
4445
4446 // A conversion that is not a conversion of a pointer, or
4447 // pointer to member, to bool is better than another conversion
4448 // that is such a conversion.
4450 return SCS2.isPointerConversionToBool()
4453
4454 // C++14 [over.ics.rank]p4b2:
4455 // This is retroactively applied to C++11 by CWG 1601.
4456 //
4457 // A conversion that promotes an enumeration whose underlying type is fixed
4458 // to its underlying type is better than one that promotes to the promoted
4459 // underlying type, if the two are different.
4462 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4463 FEP1 != FEP2)
4464 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4467
4468 // C++ [over.ics.rank]p4b2:
4469 //
4470 // If class B is derived directly or indirectly from class A,
4471 // conversion of B* to A* is better than conversion of B* to
4472 // void*, and conversion of A* to void* is better than conversion
4473 // of B* to void*.
4474 bool SCS1ConvertsToVoid
4476 bool SCS2ConvertsToVoid
4478 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4479 // Exactly one of the conversion sequences is a conversion to
4480 // a void pointer; it's the worse conversion.
4481 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4483 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4484 // Neither conversion sequence converts to a void pointer; compare
4485 // their derived-to-base conversions.
4487 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4488 return DerivedCK;
4489 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4490 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4491 // Both conversion sequences are conversions to void
4492 // pointers. Compare the source types to determine if there's an
4493 // inheritance relationship in their sources.
4494 QualType FromType1 = SCS1.getFromType();
4495 QualType FromType2 = SCS2.getFromType();
4496
4497 // Adjust the types we're converting from via the array-to-pointer
4498 // conversion, if we need to.
4499 if (SCS1.First == ICK_Array_To_Pointer)
4500 FromType1 = S.Context.getArrayDecayedType(FromType1);
4501 if (SCS2.First == ICK_Array_To_Pointer)
4502 FromType2 = S.Context.getArrayDecayedType(FromType2);
4503
4504 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4505 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4506
4507 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4509 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4511
4512 // Objective-C++: If one interface is more specific than the
4513 // other, it is the better one.
4514 const ObjCObjectPointerType* FromObjCPtr1
4515 = FromType1->getAs<ObjCObjectPointerType>();
4516 const ObjCObjectPointerType* FromObjCPtr2
4517 = FromType2->getAs<ObjCObjectPointerType>();
4518 if (FromObjCPtr1 && FromObjCPtr2) {
4519 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4520 FromObjCPtr2);
4521 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4522 FromObjCPtr1);
4523 if (AssignLeft != AssignRight) {
4524 return AssignLeft? ImplicitConversionSequence::Better
4526 }
4527 }
4528 }
4529
4530 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4531 // Check for a better reference binding based on the kind of bindings.
4532 if (isBetterReferenceBindingKind(SCS1, SCS2))
4534 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4536 }
4537
4538 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4539 // bullet 3).
4541 = CompareQualificationConversions(S, SCS1, SCS2))
4542 return QualCK;
4543
4544 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4545 // C++ [over.ics.rank]p3b4:
4546 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4547 // which the references refer are the same type except for
4548 // top-level cv-qualifiers, and the type to which the reference
4549 // initialized by S2 refers is more cv-qualified than the type
4550 // to which the reference initialized by S1 refers.
4551 QualType T1 = SCS1.getToType(2);
4552 QualType T2 = SCS2.getToType(2);
4553 T1 = S.Context.getCanonicalType(T1);
4554 T2 = S.Context.getCanonicalType(T2);
4555 Qualifiers T1Quals, T2Quals;
4556 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4557 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4558 if (UnqualT1 == UnqualT2) {
4559 // Objective-C++ ARC: If the references refer to objects with different
4560 // lifetimes, prefer bindings that don't change lifetime.
4566 }
4567
4568 // If the type is an array type, promote the element qualifiers to the
4569 // type for comparison.
4570 if (isa<ArrayType>(T1) && T1Quals)
4571 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4572 if (isa<ArrayType>(T2) && T2Quals)
4573 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4574 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4576 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4578 }
4579 }
4580
4581 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4582 // floating-to-integral conversion if the integral conversion
4583 // is between types of the same size.
4584 // For example:
4585 // void f(float);
4586 // void f(int);
4587 // int main {
4588 // long a;
4589 // f(a);
4590 // }
4591 // Here, MSVC will call f(int) instead of generating a compile error
4592 // as clang will do in standard mode.
4593 if (S.getLangOpts().MSVCCompat &&
4596 SCS2.Second == ICK_Floating_Integral &&
4597 S.Context.getTypeSize(SCS1.getFromType()) ==
4598 S.Context.getTypeSize(SCS1.getToType(2)))
4600
4601 // Prefer a compatible vector conversion over a lax vector conversion
4602 // For example:
4603 //
4604 // typedef float __v4sf __attribute__((__vector_size__(16)));
4605 // void f(vector float);
4606 // void f(vector signed int);
4607 // int main() {
4608 // __v4sf a;
4609 // f(a);
4610 // }
4611 // Here, we'd like to choose f(vector float) and not
4612 // report an ambiguous call error
4613 if (SCS1.Second == ICK_Vector_Conversion &&
4614 SCS2.Second == ICK_Vector_Conversion) {
4615 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4616 SCS1.getFromType(), SCS1.getToType(2));
4617 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4618 SCS2.getFromType(), SCS2.getToType(2));
4619
4620 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4621 return SCS1IsCompatibleVectorConversion
4624 }
4625
4626 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4628 bool SCS1IsCompatibleSVEVectorConversion =
4630 bool SCS2IsCompatibleSVEVectorConversion =
4632
4633 if (SCS1IsCompatibleSVEVectorConversion !=
4634 SCS2IsCompatibleSVEVectorConversion)
4635 return SCS1IsCompatibleSVEVectorConversion
4638 }
4639
4640 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4642 bool SCS1IsCompatibleRVVVectorConversion =
4644 bool SCS2IsCompatibleRVVVectorConversion =
4646
4647 if (SCS1IsCompatibleRVVVectorConversion !=
4648 SCS2IsCompatibleRVVVectorConversion)
4649 return SCS1IsCompatibleRVVVectorConversion
4652 }
4654}
4655
4656/// CompareQualificationConversions - Compares two standard conversion
4657/// sequences to determine whether they can be ranked based on their
4658/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4661 const StandardConversionSequence& SCS1,
4662 const StandardConversionSequence& SCS2) {
4663 // C++ [over.ics.rank]p3:
4664 // -- S1 and S2 differ only in their qualification conversion and
4665 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4666 // [C++98]
4667 // [...] and the cv-qualification signature of type T1 is a proper subset
4668 // of the cv-qualification signature of type T2, and S1 is not the
4669 // deprecated string literal array-to-pointer conversion (4.2).
4670 // [C++2a]
4671 // [...] where T1 can be converted to T2 by a qualification conversion.
4672 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4673 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4675
4676 // FIXME: the example in the standard doesn't use a qualification
4677 // conversion (!)
4678 QualType T1 = SCS1.getToType(2);
4679 QualType T2 = SCS2.getToType(2);
4680 T1 = S.Context.getCanonicalType(T1);
4681 T2 = S.Context.getCanonicalType(T2);
4682 assert(!T1->isReferenceType() && !T2->isReferenceType());
4683 Qualifiers T1Quals, T2Quals;
4684 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4685 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4686
4687 // If the types are the same, we won't learn anything by unwrapping
4688 // them.
4689 if (UnqualT1 == UnqualT2)
4691
4692 // Don't ever prefer a standard conversion sequence that uses the deprecated
4693 // string literal array to pointer conversion.
4694 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4695 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4696
4697 // Objective-C++ ARC:
4698 // Prefer qualification conversions not involving a change in lifetime
4699 // to qualification conversions that do change lifetime.
4702 CanPick1 = false;
4705 CanPick2 = false;
4706
4707 bool ObjCLifetimeConversion;
4708 if (CanPick1 &&
4709 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4710 CanPick1 = false;
4711 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4712 // directions, so we can't short-cut this second check in general.
4713 if (CanPick2 &&
4714 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4715 CanPick2 = false;
4716
4717 if (CanPick1 != CanPick2)
4718 return CanPick1 ? ImplicitConversionSequence::Better
4721}
4722
4723/// CompareDerivedToBaseConversions - Compares two standard conversion
4724/// sequences to determine whether they can be ranked based on their
4725/// various kinds of derived-to-base conversions (C++
4726/// [over.ics.rank]p4b3). As part of these checks, we also look at
4727/// conversions between Objective-C interface types.
4730 const StandardConversionSequence& SCS1,
4731 const StandardConversionSequence& SCS2) {
4732 QualType FromType1 = SCS1.getFromType();
4733 QualType ToType1 = SCS1.getToType(1);
4734 QualType FromType2 = SCS2.getFromType();
4735 QualType ToType2 = SCS2.getToType(1);
4736
4737 // Adjust the types we're converting from via the array-to-pointer
4738 // conversion, if we need to.
4739 if (SCS1.First == ICK_Array_To_Pointer)
4740 FromType1 = S.Context.getArrayDecayedType(FromType1);
4741 if (SCS2.First == ICK_Array_To_Pointer)
4742 FromType2 = S.Context.getArrayDecayedType(FromType2);
4743
4744 // Canonicalize all of the types.
4745 FromType1 = S.Context.getCanonicalType(FromType1);
4746 ToType1 = S.Context.getCanonicalType(ToType1);
4747 FromType2 = S.Context.getCanonicalType(FromType2);
4748 ToType2 = S.Context.getCanonicalType(ToType2);
4749
4750 // C++ [over.ics.rank]p4b3:
4751 //
4752 // If class B is derived directly or indirectly from class A and
4753 // class C is derived directly or indirectly from B,
4754 //
4755 // Compare based on pointer conversions.
4756 if (SCS1.Second == ICK_Pointer_Conversion &&
4758 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4759 FromType1->isPointerType() && FromType2->isPointerType() &&
4760 ToType1->isPointerType() && ToType2->isPointerType()) {
4761 QualType FromPointee1 =
4763 QualType ToPointee1 =
4765 QualType FromPointee2 =
4767 QualType ToPointee2 =
4769
4770 // -- conversion of C* to B* is better than conversion of C* to A*,
4771 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4772 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4774 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4776 }
4777
4778 // -- conversion of B* to A* is better than conversion of C* to A*,
4779 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4780 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4782 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4784 }
4785 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4787 const ObjCObjectPointerType *FromPtr1
4788 = FromType1->getAs<ObjCObjectPointerType>();
4789 const ObjCObjectPointerType *FromPtr2
4790 = FromType2->getAs<ObjCObjectPointerType>();
4791 const ObjCObjectPointerType *ToPtr1
4792 = ToType1->getAs<ObjCObjectPointerType>();
4793 const ObjCObjectPointerType *ToPtr2
4794 = ToType2->getAs<ObjCObjectPointerType>();
4795
4796 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4797 // Apply the same conversion ranking rules for Objective-C pointer types
4798 // that we do for C++ pointers to class types. However, we employ the
4799 // Objective-C pseudo-subtyping relationship used for assignment of
4800 // Objective-C pointer types.
4801 bool FromAssignLeft
4802 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4803 bool FromAssignRight
4804 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4805 bool ToAssignLeft
4806 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4807 bool ToAssignRight
4808 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4809
4810 // A conversion to an a non-id object pointer type or qualified 'id'
4811 // type is better than a conversion to 'id'.
4812 if (ToPtr1->isObjCIdType() &&
4813 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4815 if (ToPtr2->isObjCIdType() &&
4816 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4818
4819 // A conversion to a non-id object pointer type is better than a
4820 // conversion to a qualified 'id' type
4821 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4823 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4825
4826 // A conversion to an a non-Class object pointer type or qualified 'Class'
4827 // type is better than a conversion to 'Class'.
4828 if (ToPtr1->isObjCClassType() &&
4829 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4831 if (ToPtr2->isObjCClassType() &&
4832 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4834
4835 // A conversion to a non-Class object pointer type is better than a
4836 // conversion to a qualified 'Class' type.
4837 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4839 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4841
4842 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4843 if (S.Context.hasSameType(FromType1, FromType2) &&
4844 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4845 (ToAssignLeft != ToAssignRight)) {
4846 if (FromPtr1->isSpecialized()) {
4847 // "conversion of B<A> * to B * is better than conversion of B * to
4848 // C *.
4849 bool IsFirstSame =
4850 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4851 bool IsSecondSame =
4852 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4853 if (IsFirstSame) {
4854 if (!IsSecondSame)
4856 } else if (IsSecondSame)
4858 }
4859 return ToAssignLeft? ImplicitConversionSequence::Worse
4861 }
4862
4863 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4864 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4865 (FromAssignLeft != FromAssignRight))
4866 return FromAssignLeft? ImplicitConversionSequence::Better
4868 }
4869 }
4870
4871 // Ranking of member-pointer types.
4872 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4873 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4874 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4875 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4876 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4877 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4878 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4879 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4880 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4881 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4882 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4883 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4884 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4885 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4886 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4887 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4888 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4889 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4891 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4893 }
4894 // conversion of B::* to C::* is better than conversion of A::* to C::*
4895 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4896 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4898 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4900 }
4901 }
4902
4903 if (SCS1.Second == ICK_Derived_To_Base) {
4904 // -- conversion of C to B is better than conversion of C to A,
4905 // -- binding of an expression of type C to a reference of type
4906 // B& is better than binding an expression of type C to a
4907 // reference of type A&,
4908 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4909 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4910 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4912 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4914 }
4915
4916 // -- conversion of B to A is better than conversion of C to A.
4917 // -- binding of an expression of type B to a reference of type
4918 // A& is better than binding an expression of type C to a
4919 // reference of type A&,
4920 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4921 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4922 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4924 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4926 }
4927 }
4928
4930}
4931
4933 if (!T.getQualifiers().hasUnaligned())
4934 return T;
4935
4936 Qualifiers Q;
4937 T = Ctx.getUnqualifiedArrayType(T, Q);
4938 Q.removeUnaligned();
4939 return Ctx.getQualifiedType(T, Q);
4940}
4941
4944 QualType OrigT1, QualType OrigT2,
4945 ReferenceConversions *ConvOut) {
4946 assert(!OrigT1->isReferenceType() &&
4947 "T1 must be the pointee type of the reference type");
4948 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4949
4950 QualType T1 = Context.getCanonicalType(OrigT1);
4951 QualType T2 = Context.getCanonicalType(OrigT2);
4952 Qualifiers T1Quals, T2Quals;
4953 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4954 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4955
4956 ReferenceConversions ConvTmp;
4957 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4958 Conv = ReferenceConversions();
4959
4960 // C++2a [dcl.init.ref]p4:
4961 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4962 // reference-related to "cv2 T2" if T1 is similar to T2, or
4963 // T1 is a base class of T2.
4964 // "cv1 T1" is reference-compatible with "cv2 T2" if
4965 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4966 // "pointer to cv1 T1" via a standard conversion sequence.
4967
4968 // Check for standard conversions we can apply to pointers: derived-to-base
4969 // conversions, ObjC pointer conversions, and function pointer conversions.
4970 // (Qualification conversions are checked last.)
4971 QualType ConvertedT2;
4972 if (UnqualT1 == UnqualT2) {
4973 // Nothing to do.
4974 } else if (isCompleteType(Loc, OrigT2) &&
4975 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4976 Conv |= ReferenceConversions::DerivedToBase;
4977 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4978 UnqualT2->isObjCObjectOrInterfaceType() &&
4979 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4980 Conv |= ReferenceConversions::ObjC;
4981 else if (UnqualT2->isFunctionType() &&
4982 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4983 Conv |= ReferenceConversions::Function;
4984 // No need to check qualifiers; function types don't have them.
4985 return Ref_Compatible;
4986 }
4987 bool ConvertedReferent = Conv != 0;
4988
4989 // We can have a qualification conversion. Compute whether the types are
4990 // similar at the same time.
4991 bool PreviousToQualsIncludeConst = true;
4992 bool TopLevel = true;
4993 do {
4994 if (T1 == T2)
4995 break;
4996
4997 // We will need a qualification conversion.
4998 Conv |= ReferenceConversions::Qualification;
4999
5000 // Track whether we performed a qualification conversion anywhere other
5001 // than the top level. This matters for ranking reference bindings in
5002 // overload resolution.
5003 if (!TopLevel)
5004 Conv |= ReferenceConversions::NestedQualification;
5005
5006 // MS compiler ignores __unaligned qualifier for references; do the same.
5007 T1 = withoutUnaligned(Context, T1);
5008 T2 = withoutUnaligned(Context, T2);
5009
5010 // If we find a qualifier mismatch, the types are not reference-compatible,
5011 // but are still be reference-related if they're similar.
5012 bool ObjCLifetimeConversion = false;
5013 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5014 PreviousToQualsIncludeConst,
5015 ObjCLifetimeConversion, getASTContext()))
5016 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5017 ? Ref_Related
5018 : Ref_Incompatible;
5019
5020 // FIXME: Should we track this for any level other than the first?
5021 if (ObjCLifetimeConversion)
5022 Conv |= ReferenceConversions::ObjCLifetime;
5023
5024 TopLevel = false;
5025 } while (Context.UnwrapSimilarTypes(T1, T2));
5026
5027 // At this point, if the types are reference-related, we must either have the
5028 // same inner type (ignoring qualifiers), or must have already worked out how
5029 // to convert the referent.
5030 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5031 ? Ref_Compatible
5032 : Ref_Incompatible;
5033}
5034
5035/// Look for a user-defined conversion to a value reference-compatible
5036/// with DeclType. Return true if something definite is found.
5037static bool
5039 QualType DeclType, SourceLocation DeclLoc,
5040 Expr *Init, QualType T2, bool AllowRvalues,
5041 bool AllowExplicit) {
5042 assert(T2->isRecordType() && "Can only find conversions of record types.");
5043 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5044
5045 OverloadCandidateSet CandidateSet(
5047 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5048 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5049 NamedDecl *D = *I;
5050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5051 if (isa<UsingShadowDecl>(D))
5052 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5053
5054 FunctionTemplateDecl *ConvTemplate
5055 = dyn_cast<FunctionTemplateDecl>(D);
5056 CXXConversionDecl *Conv;
5057 if (ConvTemplate)
5058 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5059 else
5060 Conv = cast<CXXConversionDecl>(D);
5061
5062 if (AllowRvalues) {
5063 // If we are initializing an rvalue reference, don't permit conversion
5064 // functions that return lvalues.
5065 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5066 const ReferenceType *RefType
5068 if (RefType && !RefType->getPointeeType()->isFunctionType())
5069 continue;
5070 }
5071
5072 if (!ConvTemplate &&
5074 DeclLoc,
5075 Conv->getConversionType()
5080 continue;
5081 } else {
5082 // If the conversion function doesn't return a reference type,
5083 // it can't be considered for this conversion. An rvalue reference
5084 // is only acceptable if its referencee is a function type.
5085
5086 const ReferenceType *RefType =
5088 if (!RefType ||
5089 (!RefType->isLValueReferenceType() &&
5090 !RefType->getPointeeType()->isFunctionType()))
5091 continue;
5092 }
5093
5094 if (ConvTemplate)
5096 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5097 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5098 else
5100 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5101 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5102 }
5103
5104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5105
5107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5108 case OR_Success:
5109 // C++ [over.ics.ref]p1:
5110 //
5111 // [...] If the parameter binds directly to the result of
5112 // applying a conversion function to the argument
5113 // expression, the implicit conversion sequence is a
5114 // user-defined conversion sequence (13.3.3.1.2), with the
5115 // second standard conversion sequence either an identity
5116 // conversion or, if the conversion function returns an
5117 // entity of a type that is a derived class of the parameter
5118 // type, a derived-to-base Conversion.
5119 if (!Best->FinalConversion.DirectBinding)
5120 return false;
5121
5122 ICS.setUserDefined();
5123 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5124 ICS.UserDefined.After = Best->FinalConversion;
5125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5126 ICS.UserDefined.ConversionFunction = Best->Function;
5127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5128 ICS.UserDefined.EllipsisConversion = false;
5129 assert(ICS.UserDefined.After.ReferenceBinding &&
5131 "Expected a direct reference binding!");
5132 return true;
5133
5134 case OR_Ambiguous:
5135 ICS.setAmbiguous();
5136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5137 Cand != CandidateSet.end(); ++Cand)
5138 if (Cand->Best)
5139 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5140 return true;
5141
5143 case OR_Deleted:
5144 // There was no suitable conversion, or we found a deleted
5145 // conversion; continue with other checks.
5146 return false;
5147 }
5148
5149 llvm_unreachable("Invalid OverloadResult!");
5150}
5151
5152/// Compute an implicit conversion sequence for reference
5153/// initialization.
5156 SourceLocation DeclLoc,
5157 bool SuppressUserConversions,
5158 bool AllowExplicit) {
5159 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5160
5161 // Most paths end in a failed conversion.
5164
5165 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5166 QualType T2 = Init->getType();
5167
5168 // If the initializer is the address of an overloaded function, try
5169 // to resolve the overloaded function. If all goes well, T2 is the
5170 // type of the resulting function.
5171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5174 false, Found))
5175 T2 = Fn->getType();
5176 }
5177
5178 // Compute some basic properties of the types and the initializer.
5179 bool isRValRef = DeclType->isRValueReferenceType();
5180 Expr::Classification InitCategory = Init->Classify(S.Context);
5181
5183 Sema::ReferenceCompareResult RefRelationship =
5184 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5185
5186 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5187 ICS.setStandard();
5189 // FIXME: A reference binding can be a function conversion too. We should
5190 // consider that when ordering reference-to-function bindings.
5191 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5193 : (RefConv & Sema::ReferenceConversions::ObjC)
5195 : ICK_Identity;
5197 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5198 // a reference binding that performs a non-top-level qualification
5199 // conversion as a qualification conversion, not as an identity conversion.
5200 ICS.Standard.Third = (RefConv &
5201 Sema::ReferenceConversions::NestedQualification)
5203 : ICK_Identity;
5204 ICS.Standard.setFromType(T2);
5205 ICS.Standard.setToType(0, T2);
5206 ICS.Standard.setToType(1, T1);
5207 ICS.Standard.setToType(2, T1);
5208 ICS.Standard.ReferenceBinding = true;
5209 ICS.Standard.DirectBinding = BindsDirectly;
5210 ICS.Standard.IsLvalueReference = !isRValRef;
5212 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5215 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5216 ICS.Standard.CopyConstructor = nullptr;
5218 };
5219
5220 // C++0x [dcl.init.ref]p5:
5221 // A reference to type "cv1 T1" is initialized by an expression
5222 // of type "cv2 T2" as follows:
5223
5224 // -- If reference is an lvalue reference and the initializer expression
5225 if (!isRValRef) {
5226 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5227 // reference-compatible with "cv2 T2," or
5228 //
5229 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5230 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5231 // C++ [over.ics.ref]p1:
5232 // When a parameter of reference type binds directly (8.5.3)
5233 // to an argument expression, the implicit conversion sequence
5234 // is the identity conversion, unless the argument expression
5235 // has a type that is a derived class of the parameter type,
5236 // in which case the implicit conversion sequence is a
5237 // derived-to-base Conversion (13.3.3.1).
5238 SetAsReferenceBinding(/*BindsDirectly=*/true);
5239
5240 // Nothing more to do: the inaccessibility/ambiguity check for
5241 // derived-to-base conversions is suppressed when we're
5242 // computing the implicit conversion sequence (C++
5243 // [over.best.ics]p2).
5244 return ICS;
5245 }
5246
5247 // -- has a class type (i.e., T2 is a class type), where T1 is
5248 // not reference-related to T2, and can be implicitly
5249 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5250 // is reference-compatible with "cv3 T3" 92) (this
5251 // conversion is selected by enumerating the applicable
5252 // conversion functions (13.3.1.6) and choosing the best
5253 // one through overload resolution (13.3)),
5254 if (!SuppressUserConversions && T2->isRecordType() &&
5255 S.isCompleteType(DeclLoc, T2) &&
5256 RefRelationship == Sema::Ref_Incompatible) {
5257 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5258 Init, T2, /*AllowRvalues=*/false,
5259 AllowExplicit))
5260 return ICS;
5261 }
5262 }
5263
5264 // -- Otherwise, the reference shall be an lvalue reference to a
5265 // non-volatile const type (i.e., cv1 shall be const), or the reference
5266 // shall be an rvalue reference.
5267 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5268 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5270 return ICS;
5271 }
5272
5273 // -- If the initializer expression
5274 //
5275 // -- is an xvalue, class prvalue, array prvalue or function
5276 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5277 if (RefRelationship == Sema::Ref_Compatible &&
5278 (InitCategory.isXValue() ||
5279 (InitCategory.isPRValue() &&
5280 (T2->isRecordType() || T2->isArrayType())) ||
5281 (InitCategory.isLValue() && T2->isFunctionType()))) {
5282 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5283 // binding unless we're binding to a class prvalue.
5284 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5285 // allow the use of rvalue references in C++98/03 for the benefit of
5286 // standard library implementors; therefore, we need the xvalue check here.
5287 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5288 !(InitCategory.isPRValue() || T2->isRecordType()));
5289 return ICS;
5290 }
5291
5292 // -- has a class type (i.e., T2 is a class type), where T1 is not
5293 // reference-related to T2, and can be implicitly converted to
5294 // an xvalue, class prvalue, or function lvalue of type
5295 // "cv3 T3", where "cv1 T1" is reference-compatible with
5296 // "cv3 T3",
5297 //
5298 // then the reference is bound to the value of the initializer
5299 // expression in the first case and to the result of the conversion
5300 // in the second case (or, in either case, to an appropriate base
5301 // class subobject).
5302 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5303 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5304 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5305 Init, T2, /*AllowRvalues=*/true,
5306 AllowExplicit)) {
5307 // In the second case, if the reference is an rvalue reference
5308 // and the second standard conversion sequence of the
5309 // user-defined conversion sequence includes an lvalue-to-rvalue
5310 // conversion, the program is ill-formed.
5311 if (ICS.isUserDefined() && isRValRef &&
5314
5315 return ICS;
5316 }
5317
5318 // A temporary of function type cannot be created; don't even try.
5319 if (T1->isFunctionType())
5320 return ICS;
5321
5322 // -- Otherwise, a temporary of type "cv1 T1" is created and
5323 // initialized from the initializer expression using the
5324 // rules for a non-reference copy initialization (8.5). The
5325 // reference is then bound to the temporary. If T1 is
5326 // reference-related to T2, cv1 must be the same
5327 // cv-qualification as, or greater cv-qualification than,
5328 // cv2; otherwise, the program is ill-formed.
5329 if (RefRelationship == Sema::Ref_Related) {
5330 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5331 // we would be reference-compatible or reference-compatible with
5332 // added qualification. But that wasn't the case, so the reference
5333 // initialization fails.
5334 //
5335 // Note that we only want to check address spaces and cvr-qualifiers here.
5336 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5337 Qualifiers T1Quals = T1.getQualifiers();
5338 Qualifiers T2Quals = T2.getQualifiers();
5339 T1Quals.removeObjCGCAttr();
5340 T1Quals.removeObjCLifetime();
5341 T2Quals.removeObjCGCAttr();
5342 T2Quals.removeObjCLifetime();
5343 // MS compiler ignores __unaligned qualifier for references; do the same.
5344 T1Quals.removeUnaligned();
5345 T2Quals.removeUnaligned();
5346 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5347 return ICS;
5348 }
5349
5350 // If at least one of the types is a class type, the types are not
5351 // related, and we aren't allowed any user conversions, the
5352 // reference binding fails. This case is important for breaking
5353 // recursion, since TryImplicitConversion below will attempt to
5354 // create a temporary through the use of a copy constructor.
5355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5356 (T1->isRecordType() || T2->isRecordType()))
5357 return ICS;
5358
5359 // If T1 is reference-related to T2 and the reference is an rvalue
5360 // reference, the initializer expression shall not be an lvalue.
5361 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5362 Init->Classify(S.Context).isLValue()) {
5364 return ICS;
5365 }
5366
5367 // C++ [over.ics.ref]p2:
5368 // When a parameter of reference type is not bound directly to
5369 // an argument expression, the conversion sequence is the one
5370 // required to convert the argument expression to the
5371 // underlying type of the reference according to
5372 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5373 // to copy-initializing a temporary of the underlying type with
5374 // the argument expression. Any difference in top-level
5375 // cv-qualification is subsumed by the initialization itself
5376 // and does not constitute a conversion.
5377 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5378 AllowedExplicit::None,
5379 /*InOverloadResolution=*/false,
5380 /*CStyle=*/false,
5381 /*AllowObjCWritebackConversion=*/false,
5382 /*AllowObjCConversionOnExplicit=*/false);
5383
5384 // Of course, that's still a reference binding.
5385 if (ICS.isStandard()) {
5386 ICS.Standard.ReferenceBinding = true;
5387 ICS.Standard.IsLvalueReference = !isRValRef;
5388 ICS.Standard.BindsToFunctionLvalue = false;
5389 ICS.Standard.BindsToRvalue = true;
5392 } else if (ICS.isUserDefined()) {
5393 const ReferenceType *LValRefType =
5396
5397 // C++ [over.ics.ref]p3:
5398 // Except for an implicit object parameter, for which see 13.3.1, a
5399 // standard conversion sequence cannot be formed if it requires [...]
5400 // binding an rvalue reference to an lvalue other than a function
5401 // lvalue.
5402 // Note that the function case is not possible here.
5403 if (isRValRef && LValRefType) {
5405 return ICS;
5406 }
5407
5409 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5411 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5414 }
5415
5416 return ICS;
5417}
5418
5420TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5421 bool SuppressUserConversions,
5422 bool InOverloadResolution,
5423 bool AllowObjCWritebackConversion,
5424 bool AllowExplicit = false);
5425
5426/// TryListConversion - Try to copy-initialize a value of type ToType from the
5427/// initializer list From.
5430 bool SuppressUserConversions,
5431 bool InOverloadResolution,
5432 bool AllowObjCWritebackConversion) {
5433 // C++11 [over.ics.list]p1:
5434 // When an argument is an initializer list, it is not an expression and
5435 // special rules apply for converting it to a parameter type.
5436
5438 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5439
5440 // We need a complete type for what follows. With one C++20 exception,
5441 // incomplete types can never be initialized from init lists.
5442 QualType InitTy = ToType;
5443 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5444 if (AT && S.getLangOpts().CPlusPlus20)
5445 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5446 // C++20 allows list initialization of an incomplete array type.
5447 InitTy = IAT->getElementType();
5448 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5449 return Result;
5450
5451 // C++20 [over.ics.list]/2:
5452 // If the initializer list is a designated-initializer-list, a conversion
5453 // is only possible if the parameter has an aggregate type
5454 //
5455 // FIXME: The exception for reference initialization here is not part of the
5456 // language rules, but follow other compilers in adding it as a tentative DR
5457 // resolution.
5458 bool IsDesignatedInit = From->hasDesignatedInit();
5459 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5460 IsDesignatedInit)
5461 return Result;
5462
5463 // Per DR1467 and DR2137:
5464 // If the parameter type is an aggregate class X and the initializer list
5465 // has a single element of type cv U, where U is X or a class derived from
5466 // X, the implicit conversion sequence is the one required to convert the
5467 // element to the parameter type.
5468 //
5469 // Otherwise, if the parameter type is a character array [... ]
5470 // and the initializer list has a single element that is an
5471 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5472 // implicit conversion sequence is the identity conversion.
5473 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5474 if (ToType->isRecordType() && ToType->isAggregateType()) {
5475 QualType InitType = From->getInit(0)->getType();
5476 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5477 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5478 return TryCopyInitialization(S, From->getInit(0), ToType,
5479 SuppressUserConversions,
5480 InOverloadResolution,
5481 AllowObjCWritebackConversion);
5482 }
5483
5484 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5485 InitializedEntity Entity =
5487 /*Consumed=*/false);
5488 if (S.CanPerformCopyInitialization(Entity, From)) {
5489 Result.setStandard();
5490 Result.Standard.setAsIdentityConversion();
5491 Result.Standard.setFromType(ToType);
5492 Result.Standard.setAllToTypes(ToType);
5493 return Result;
5494 }
5495 }
5496 }
5497
5498 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5499 // C++11 [over.ics.list]p2:
5500 // If the parameter type is std::initializer_list<X> or "array of X" and
5501 // all the elements can be implicitly converted to X, the implicit
5502 // conversion sequence is the worst conversion necessary to convert an
5503 // element of the list to X.
5504 //
5505 // C++14 [over.ics.list]p3:
5506 // Otherwise, if the parameter type is "array of N X", if the initializer
5507 // list has exactly N elements or if it has fewer than N elements and X is
5508 // default-constructible, and if all the elements of the initializer list
5509 // can be implicitly converted to X, the implicit conversion sequence is
5510 // the worst conversion necessary to convert an element of the list to X.
5511 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5512 unsigned e = From->getNumInits();
5515 QualType());
5516 QualType ContTy = ToType;
5517 bool IsUnbounded = false;
5518 if (AT) {
5519 InitTy = AT->getElementType();
5520 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5521 if (CT->getSize().ult(e)) {
5522 // Too many inits, fatally bad
5524 ToType);
5525 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5526 return Result;
5527 }
5528 if (CT->getSize().ugt(e)) {
5529 // Need an init from empty {}, is there one?
5530 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5531 From->getEndLoc());
5532 EmptyList.setType(S.Context.VoidTy);
5533 DfltElt = TryListConversion(
5534 S, &EmptyList, InitTy, SuppressUserConversions,
5535 InOverloadResolution, AllowObjCWritebackConversion);
5536 if (DfltElt.isBad()) {
5537 // No {} init, fatally bad
5539 ToType);
5540 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5541 return Result;
5542 }
5543 }
5544 } else {
5545 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5546 IsUnbounded = true;
5547 if (!e) {
5548 // Cannot convert to zero-sized.
5550 ToType);
5551 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5552 return Result;
5553 }
5554 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5555 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5557 }
5558 }
5559
5560 Result.setStandard();
5561 Result.Standard.setAsIdentityConversion();
5562 Result.Standard.setFromType(InitTy);
5563 Result.Standard.setAllToTypes(InitTy);
5564 for (unsigned i = 0; i < e; ++i) {
5565 Expr *Init = From->getInit(i);
5567 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5568 AllowObjCWritebackConversion);
5569
5570 // Keep the worse conversion seen so far.
5571 // FIXME: Sequences are not totally ordered, so 'worse' can be
5572 // ambiguous. CWG has been informed.
5574 Result) ==
5576 Result = ICS;
5577 // Bail as soon as we find something unconvertible.
5578 if (Result.isBad()) {
5579 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5580 return Result;
5581 }
5582 }
5583 }
5584
5585 // If we needed any implicit {} initialization, compare that now.
5586 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5587 // has been informed that this might not be the best thing.
5588 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5589 S, From->getEndLoc(), DfltElt, Result) ==
5591 Result = DfltElt;
5592 // Record the type being initialized so that we may compare sequences
5593 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5594 return Result;
5595 }
5596
5597 // C++14 [over.ics.list]p4:
5598 // C++11 [over.ics.list]p3:
5599 // Otherwise, if the parameter is a non-aggregate class X and overload
5600 // resolution chooses a single best constructor [...] the implicit
5601 // conversion sequence is a user-defined conversion sequence. If multiple
5602 // constructors are viable but none is better than the others, the
5603 // implicit conversion sequence is a user-defined conversion sequence.
5604 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5605 // This function can deal with initializer lists.
5606 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5607 AllowedExplicit::None,
5608 InOverloadResolution, /*CStyle=*/false,
5609 AllowObjCWritebackConversion,
5610 /*AllowObjCConversionOnExplicit=*/false);
5611 }
5612
5613 // C++14 [over.ics.list]p5:
5614 // C++11 [over.ics.list]p4:
5615 // Otherwise, if the parameter has an aggregate type which can be
5616 // initialized from the initializer list [...] the implicit conversion
5617 // sequence is a user-defined conversion sequence.
5618 if (ToType->isAggregateType()) {
5619 // Type is an aggregate, argument is an init list. At this point it comes
5620 // down to checking whether the initialization works.
5621 // FIXME: Find out whether this parameter is consumed or not.
5622 InitializedEntity Entity =
5624 /*Consumed=*/false);
5626 From)) {
5627 Result.setUserDefined();
5628 Result.UserDefined.Before.setAsIdentityConversion();
5629 // Initializer lists don't have a type.
5630 Result.UserDefined.Before.setFromType(QualType());
5631 Result.UserDefined.Before.setAllToTypes(QualType());
5632
5633 Result.UserDefined.After.setAsIdentityConversion();
5634 Result.UserDefined.After.setFromType(ToType);
5635 Result.UserDefined.After.setAllToTypes(ToType);
5636 Result.UserDefined.ConversionFunction = nullptr;
5637 }
5638 return Result;
5639 }
5640
5641 // C++14 [over.ics.list]p6:
5642 // C++11 [over.ics.list]p5:
5643 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5644 if (ToType->isReferenceType()) {
5645 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5646 // mention initializer lists in any way. So we go by what list-
5647 // initialization would do and try to extrapolate from that.
5648
5649 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5650
5651 // If the initializer list has a single element that is reference-related
5652 // to the parameter type, we initialize the reference from that.
5653 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5654 Expr *Init = From->getInit(0);
5655
5656 QualType T2 = Init->getType();
5657
5658 // If the initializer is the address of an overloaded function, try
5659 // to resolve the overloaded function. If all goes well, T2 is the
5660 // type of the resulting function.
5661 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5664 Init, ToType, false, Found))
5665 T2 = Fn->getType();
5666 }
5667
5668 // Compute some basic properties of the types and the initializer.
5669 Sema::ReferenceCompareResult RefRelationship =
5670 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5671
5672 if (RefRelationship >= Sema::Ref_Related) {
5673 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5674 SuppressUserConversions,
5675 /*AllowExplicit=*/false);
5676 }
5677 }
5678
5679 // Otherwise, we bind the reference to a temporary created from the
5680 // initializer list.
5681 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5682 InOverloadResolution,
5683 AllowObjCWritebackConversion);
5684 if (Result.isFailure())
5685 return Result;
5686 assert(!Result.isEllipsis() &&
5687 "Sub-initialization cannot result in ellipsis conversion.");
5688
5689 // Can we even bind to a temporary?
5690 if (ToType->isRValueReferenceType() ||
5691 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5692 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5693 Result.UserDefined.After;
5694 SCS.ReferenceBinding = true;
5696 SCS.BindsToRvalue = true;
5697 SCS.BindsToFunctionLvalue = false;
5700 } else
5702 From, ToType);
5703 return Result;
5704 }
5705
5706 // C++14 [over.ics.list]p7:
5707 // C++11 [over.ics.list]p6:
5708 // Otherwise, if the parameter type is not a class:
5709 if (!ToType->isRecordType()) {
5710 // - if the initializer list has one element that is not itself an
5711 // initializer list, the implicit conversion sequence is the one
5712 // required to convert the element to the parameter type.
5713 unsigned NumInits = From->getNumInits();
5714 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5715 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5716 SuppressUserConversions,
5717 InOverloadResolution,
5718 AllowObjCWritebackConversion);
5719 // - if the initializer list has no elements, the implicit conversion
5720 // sequence is the identity conversion.
5721 else if (NumInits == 0) {
5722 Result.setStandard();
5723 Result.Standard.setAsIdentityConversion();
5724 Result.Standard.setFromType(ToType);
5725 Result.Standard.setAllToTypes(ToType);
5726 }
5727 return Result;
5728 }
5729
5730 // C++14 [over.ics.list]p8:
5731 // C++11 [over.ics.list]p7:
5732 // In all cases other than those enumerated above, no conversion is possible
5733 return Result;
5734}
5735
5736/// TryCopyInitialization - Try to copy-initialize a value of type
5737/// ToType from the expression From. Return the implicit conversion
5738/// sequence required to pass this argument, which may be a bad
5739/// conversion sequence (meaning that the argument cannot be passed to
5740/// a parameter of this type). If @p SuppressUserConversions, then we
5741/// do not permit any user-defined conversion sequences.
5744 bool SuppressUserConversions,
5745 bool InOverloadResolution,
5746 bool AllowObjCWritebackConversion,
5747 bool AllowExplicit) {
5748 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5749 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5750 InOverloadResolution,AllowObjCWritebackConversion);
5751
5752 if (ToType->isReferenceType())
5753 return TryReferenceInit(S, From, ToType,
5754 /*FIXME:*/ From->getBeginLoc(),
5755 SuppressUserConversions, AllowExplicit);
5756
5757 return TryImplicitConversion(S, From, ToType,
5758 SuppressUserConversions,
5759 AllowedExplicit::None,
5760 InOverloadResolution,
5761 /*CStyle=*/false,
5762 AllowObjCWritebackConversion,
5763 /*AllowObjCConversionOnExplicit=*/false);
5764}
5765
5766static bool TryCopyInitialization(const CanQualType FromQTy,
5767 const CanQualType ToQTy,
5768 Sema &S,
5769 SourceLocation Loc,
5770 ExprValueKind FromVK) {
5771 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5773 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5774
5775 return !ICS.isBad();
5776}
5777
5778/// TryObjectArgumentInitialization - Try to initialize the object
5779/// parameter of the given member function (@c Method) from the
5780/// expression @p From.
5782 Sema &S, SourceLocation Loc, QualType FromType,
5783 Expr::Classification FromClassification, CXXMethodDecl *Method,
5784 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5785 QualType ExplicitParameterType = QualType(),
5786 bool SuppressUserConversion = false) {
5787
5788 // We need to have an object of class type.
5789 if (const auto *PT = FromType->getAs<PointerType>()) {
5790 FromType = PT->getPointeeType();
5791
5792 // When we had a pointer, it's implicitly dereferenced, so we
5793 // better have an lvalue.
5794 assert(FromClassification.isLValue());
5795 }
5796
5797 auto ValueKindFromClassification = [](Expr::Classification C) {
5798 if (C.isPRValue())
5799 return clang::VK_PRValue;
5800 if (C.isXValue())
5801 return VK_XValue;
5802 return clang::VK_LValue;
5803 };
5804
5805 if (Method->isExplicitObjectMemberFunction()) {
5806 if (ExplicitParameterType.isNull())
5807 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5808 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5809 ValueKindFromClassification(FromClassification));
5811 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5812 /*InOverloadResolution=*/true, false);
5813 if (ICS.isBad())
5814 ICS.Bad.FromExpr = nullptr;
5815 return ICS;
5816 }
5817
5818 assert(FromType->isRecordType());
5819
5820 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5821 // C++98 [class.dtor]p2:
5822 // A destructor can be invoked for a const, volatile or const volatile
5823 // object.
5824 // C++98 [over.match.funcs]p4:
5825 // For static member functions, the implicit object parameter is considered
5826 // to match any object (since if the function is selected, the object is
5827 // discarded).
5828 Qualifiers Quals = Method->getMethodQualifiers();
5829 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5830 Quals.addConst();
5831 Quals.addVolatile();
5832 }
5833
5834 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5835
5836 // Set up the conversion sequence as a "bad" conversion, to allow us
5837 // to exit early.
5839
5840 // C++0x [over.match.funcs]p4:
5841 // For non-static member functions, the type of the implicit object
5842 // parameter is
5843 //
5844 // - "lvalue reference to cv X" for functions declared without a
5845 // ref-qualifier or with the & ref-qualifier
5846 // - "rvalue reference to cv X" for functions declared with the &&
5847 // ref-qualifier
5848 //
5849 // where X is the class of which the function is a member and cv is the
5850 // cv-qualification on the member function declaration.
5851 //
5852 // However, when finding an implicit conversion sequence for the argument, we
5853 // are not allowed to perform user-defined conversions
5854 // (C++ [over.match.funcs]p5). We perform a simplified version of
5855 // reference binding here, that allows class rvalues to bind to
5856 // non-constant references.
5857
5858 // First check the qualifiers.
5859 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5860 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5861 if (ImplicitParamType.getCVRQualifiers() !=
5862 FromTypeCanon.getLocalCVRQualifiers() &&
5863 !ImplicitParamType.isAtLeastAsQualifiedAs(
5864 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5866 FromType, ImplicitParamType);
5867 return ICS;
5868 }
5869
5870 if (FromTypeCanon.hasAddressSpace()) {
5871 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5872 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5873 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5874 S.getASTContext())) {
5876 FromType, ImplicitParamType);
5877 return ICS;
5878 }
5879 }
5880
5881 // Check that we have either the same type or a derived type. It
5882 // affects the conversion rank.
5883 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5884 ImplicitConversionKind SecondKind;
5885 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5886 SecondKind = ICK_Identity;
5887 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5888 SecondKind = ICK_Derived_To_Base;
5889 } else if (!Method->isExplicitObjectMemberFunction()) {
5891 FromType, ImplicitParamType);
5892 return ICS;
5893 }
5894
5895 // Check the ref-qualifier.
5896 switch (Method->getRefQualifier()) {
5897 case RQ_None:
5898 // Do nothing; we don't care about lvalueness or rvalueness.
5899 break;
5900
5901 case RQ_LValue:
5902 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5903 // non-const lvalue reference cannot bind to an rvalue
5905 ImplicitParamType);
5906 return ICS;
5907 }
5908 break;
5909
5910 case RQ_RValue:
5911 if (!FromClassification.isRValue()) {
5912 // rvalue reference cannot bind to an lvalue
5914 ImplicitParamType);
5915 return ICS;
5916 }
5917 break;
5918 }
5919
5920 // Success. Mark this as a reference binding.
5921 ICS.setStandard();
5923 ICS.Standard.Second = SecondKind;
5924 ICS.Standard.setFromType(FromType);
5925 ICS.Standard.setAllToTypes(ImplicitParamType);
5926 ICS.Standard.ReferenceBinding = true;
5927 ICS.Standard.DirectBinding = true;
5929 ICS.Standard.BindsToFunctionLvalue = false;
5930 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5932 = (Method->getRefQualifier() == RQ_None);
5933 return ICS;
5934}
5935
5936/// PerformObjectArgumentInitialization - Perform initialization of
5937/// the implicit object parameter for the given Method with the given
5938/// expression.
5940 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5941 CXXMethodDecl *Method) {
5942 QualType FromRecordType, DestType;
5943 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5944
5945 Expr::Classification FromClassification;
5946 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5947 FromRecordType = PT->getPointeeType();
5948 DestType = Method->getThisType();
5949 FromClassification = Expr::Classification::makeSimpleLValue();
5950 } else {
5951 FromRecordType = From->getType();
5952 DestType = ImplicitParamRecordType;
5953 FromClassification = From->Classify(Context);
5954
5955 // CWG2813 [expr.call]p6:
5956 // If the function is an implicit object member function, the object
5957 // expression of the class member access shall be a glvalue [...]
5958 if (From->isPRValue()) {
5959 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5960 Method->getRefQualifier() !=
5962 }
5963 }
5964
5965 // Note that we always use the true parent context when performing
5966 // the actual argument initialization.
5968 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5969 Method->getParent());
5970 if (ICS.isBad()) {
5971 switch (ICS.Bad.Kind) {
5973 Qualifiers FromQs = FromRecordType.getQualifiers();
5974 Qualifiers ToQs = DestType.getQualifiers();
5975 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5976 if (CVR) {
5977 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5978 << Method->getDeclName() << FromRecordType << (CVR - 1)
5979 << From->getSourceRange();
5980 Diag(Method->getLocation(), diag::note_previous_decl)
5981 << Method->getDeclName();
5982 return ExprError();
5983 }
5984 break;
5985 }
5986
5989 bool IsRValueQualified =
5991 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5992 << Method->getDeclName() << FromClassification.isRValue()
5993 << IsRValueQualified;
5994 Diag(Method->getLocation(), diag::note_previous_decl)
5995 << Method->getDeclName();
5996 return ExprError();
5997 }
5998
6001 break;
6002
6005 llvm_unreachable("Lists are not objects");
6006 }
6007
6008 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6009 << ImplicitParamRecordType << FromRecordType
6010 << From->getSourceRange();
6011 }
6012
6013 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6014 ExprResult FromRes =
6015 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6016 if (FromRes.isInvalid())
6017 return ExprError();
6018 From = FromRes.get();
6019 }
6020
6021 if (!Context.hasSameType(From->getType(), DestType)) {
6022 CastKind CK;
6023 QualType PteeTy = DestType->getPointeeType();
6024 LangAS DestAS =
6025 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6026 if (FromRecordType.getAddressSpace() != DestAS)
6027 CK = CK_AddressSpaceConversion;
6028 else
6029 CK = CK_NoOp;
6030 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6031 }
6032 return From;
6033}
6034
6035/// TryContextuallyConvertToBool - Attempt to contextually convert the
6036/// expression From to bool (C++0x [conv]p3).
6039 // C++ [dcl.init]/17.8:
6040 // - Otherwise, if the initialization is direct-initialization, the source
6041 // type is std::nullptr_t, and the destination type is bool, the initial
6042 // value of the object being initialized is false.
6043 if (From->getType()->isNullPtrType())
6045 S.Context.BoolTy,
6046 From->isGLValue());
6047
6048 // All other direct-initialization of bool is equivalent to an implicit
6049 // conversion to bool in which explicit conversions are permitted.
6050 return TryImplicitConversion(S, From, S.Context.BoolTy,
6051 /*SuppressUserConversions=*/false,
6052 AllowedExplicit::Conversions,
6053 /*InOverloadResolution=*/false,
6054 /*CStyle=*/false,
6055 /*AllowObjCWritebackConversion=*/false,
6056 /*AllowObjCConversionOnExplicit=*/false);
6057}
6058
6060 if (checkPlaceholderForOverload(*this, From))
6061 return ExprError();
6062
6064 if (!ICS.isBad())
6065 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6067
6068 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6069 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6070 << From->getType() << From->getSourceRange();
6071 return ExprError();
6072}
6073
6074/// Check that the specified conversion is permitted in a converted constant
6075/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6076/// is acceptable.
6079 // Since we know that the target type is an integral or unscoped enumeration
6080 // type, most conversion kinds are impossible. All possible First and Third
6081 // conversions are fine.
6082 switch (SCS.Second) {
6083 case ICK_Identity:
6085 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6087 return true;
6088
6090 // Conversion from an integral or unscoped enumeration type to bool is
6091 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6092 // conversion, so we allow it in a converted constant expression.
6093 //
6094 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6095 // a lot of popular code. We should at least add a warning for this
6096 // (non-conforming) extension.
6098 SCS.getToType(2)->isBooleanType();
6099
6101 case ICK_Pointer_Member:
6102 // C++1z: null pointer conversions and null member pointer conversions are
6103 // only permitted if the source type is std::nullptr_t.
6104 return SCS.getFromType()->isNullPtrType();
6105
6117 case ICK_Vector_Splat:
6118 case ICK_Complex_Real:
6127 return false;
6128
6133 llvm_unreachable("found a first conversion kind in Second");
6134
6136 case ICK_Qualification:
6137 llvm_unreachable("found a third conversion kind in Second");
6138
6140 break;
6141 }
6142
6143 llvm_unreachable("unknown conversion kind");
6144}
6145
6146/// BuildConvertedConstantExpression - Check that the expression From is a
6147/// converted constant expression of type T, perform the conversion but
6148/// does not evaluate the expression
6150 QualType T,
6151 Sema::CCEKind CCE,
6152 NamedDecl *Dest,
6153 APValue &PreNarrowingValue) {
6154 assert(S.getLangOpts().CPlusPlus11 &&
6155 "converted constant expression outside C++11");
6156
6157 if (checkPlaceholderForOverload(S, From))
6158 return ExprError();
6159
6160 // C++1z [expr.const]p3:
6161 // A converted constant expression of type T is an expression,
6162 // implicitly converted to type T, where the converted
6163 // expression is a constant expression and the implicit conversion
6164 // sequence contains only [... list of conversions ...].
6168 : TryCopyInitialization(S, From, T,
6169 /*SuppressUserConversions=*/false,
6170 /*InOverloadResolution=*/false,
6171 /*AllowObjCWritebackConversion=*/false,
6172 /*AllowExplicit=*/false);
6173 StandardConversionSequence *SCS = nullptr;
6174 switch (ICS.getKind()) {
6176 SCS = &ICS.Standard;
6177 break;
6179 if (T->isRecordType())
6180 SCS = &ICS.UserDefined.Before;
6181 else
6182 SCS = &ICS.UserDefined.After;
6183 break;
6187 return S.Diag(From->getBeginLoc(),
6188 diag::err_typecheck_converted_constant_expression)
6189 << From->getType() << From->getSourceRange() << T;
6190 return ExprError();
6191
6194 llvm_unreachable("bad conversion in converted constant expression");
6195 }
6196
6197 // Check that we would only use permitted conversions.
6198 if (!CheckConvertedConstantConversions(S, *SCS)) {
6199 return S.Diag(From->getBeginLoc(),
6200 diag::err_typecheck_converted_constant_expression_disallowed)
6201 << From->getType() << From->getSourceRange() << T;
6202 }
6203 // [...] and where the reference binding (if any) binds directly.
6204 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6205 return S.Diag(From->getBeginLoc(),
6206 diag::err_typecheck_converted_constant_expression_indirect)
6207 << From->getType() << From->getSourceRange() << T;
6208 }
6209 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6210 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6211 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6212 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6213 // case explicitly.
6214 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6215 return S.Diag(From->getBeginLoc(),
6216 diag::err_reference_bind_to_bitfield_in_cce)
6217 << From->getSourceRange();
6218 }
6219
6220 // Usually we can simply apply the ImplicitConversionSequence we formed
6221 // earlier, but that's not guaranteed to work when initializing an object of
6222 // class type.
6224 if (T->isRecordType()) {
6225 assert(CCE == Sema::CCEK_TemplateArg &&
6226 "unexpected class type converted constant expr");
6229 T, cast<NonTypeTemplateParmDecl>(Dest)),
6230 SourceLocation(), From);
6231 } else {
6232 Result =
6234 }
6235 if (Result.isInvalid())
6236 return Result;
6237
6238 // C++2a [intro.execution]p5:
6239 // A full-expression is [...] a constant-expression [...]
6240 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6241 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6243 if (Result.isInvalid())
6244 return Result;
6245
6246 // Check for a narrowing implicit conversion.
6247 bool ReturnPreNarrowingValue = false;
6248 QualType PreNarrowingType;
6249 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6250 PreNarrowingType)) {
6252 // Implicit conversion to a narrower type, but the expression is
6253 // value-dependent so we can't tell whether it's actually narrowing.
6255 // Implicit conversion to a narrower type, and the value is not a constant
6256 // expression. We'll diagnose this in a moment.
6257 case NK_Not_Narrowing:
6258 break;
6259
6261 if (CCE == Sema::CCEK_ArrayBound &&
6262 PreNarrowingType->isIntegralOrEnumerationType() &&
6263 PreNarrowingValue.isInt()) {
6264 // Don't diagnose array bound narrowing here; we produce more precise
6265 // errors by allowing the un-narrowed value through.
6266 ReturnPreNarrowingValue = true;
6267 break;
6268 }
6269 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6270 << CCE << /*Constant*/ 1
6271 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6272 break;
6273
6274 case NK_Type_Narrowing:
6275 // FIXME: It would be better to diagnose that the expression is not a
6276 // constant expression.
6277 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6278 << CCE << /*Constant*/ 0 << From->getType() << T;
6279 break;
6280 }
6281 if (!ReturnPreNarrowingValue)
6282 PreNarrowingValue = {};
6283
6284 return Result;
6285}
6286
6287/// CheckConvertedConstantExpression - Check that the expression From is a
6288/// converted constant expression of type T, perform the conversion and produce
6289/// the converted expression, per C++11 [expr.const]p3.
6292 Sema::CCEKind CCE,
6293 bool RequireInt,
6294 NamedDecl *Dest) {
6295
6296 APValue PreNarrowingValue;
6298 PreNarrowingValue);
6299 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6300 Value = APValue();
6301 return Result;
6302 }
6303 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6304 RequireInt, PreNarrowingValue);
6305}
6306
6308 CCEKind CCE,
6309 NamedDecl *Dest) {
6310 APValue PreNarrowingValue;
6311 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6312 PreNarrowingValue);
6313}
6314
6316 APValue &Value, CCEKind CCE,
6317 NamedDecl *Dest) {
6318 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6319 Dest);
6320}
6321
6323 llvm::APSInt &Value,
6324 CCEKind CCE) {
6325 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6326
6327 APValue V;
6328 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6329 /*Dest=*/nullptr);
6330 if (!R.isInvalid() && !R.get()->isValueDependent())
6331 Value = V.getInt();
6332 return R;
6333}
6334
6337 Sema::CCEKind CCE, bool RequireInt,
6338 const APValue &PreNarrowingValue) {
6339
6341 // Check the expression is a constant expression.
6343 Expr::EvalResult Eval;
6344 Eval.Diag = &Notes;
6345
6346 ConstantExprKind Kind;
6347 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6348 Kind = ConstantExprKind::ClassTemplateArgument;
6349 else if (CCE == Sema::CCEK_TemplateArg)
6350 Kind = ConstantExprKind::NonClassTemplateArgument;
6351 else
6352 Kind = ConstantExprKind::Normal;
6353
6354 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6355 (RequireInt && !Eval.Val.isInt())) {
6356 // The expression can't be folded, so we can't keep it at this position in
6357 // the AST.
6358 Result = ExprError();
6359 } else {
6360 Value = Eval.Val;
6361
6362 if (Notes.empty()) {
6363 // It's a constant expression.
6364 Expr *E = Result.get();
6365 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6366 // We expect a ConstantExpr to have a value associated with it
6367 // by this point.
6368 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6369 "ConstantExpr has no value associated with it");
6370 (void)CE;
6371 } else {
6372 E = ConstantExpr::Create(Context, Result.get(), Value);
6373 }
6374 if (!PreNarrowingValue.isAbsent())
6375 Value = std::move(PreNarrowingValue);
6376 return E;
6377 }
6378 }
6379
6380 // It's not a constant expression. Produce an appropriate diagnostic.
6381 if (Notes.size() == 1 &&
6382 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6383 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6384 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6385 diag::note_constexpr_invalid_template_arg) {
6386 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6387 for (unsigned I = 0; I < Notes.size(); ++I)
6388 Diag(Notes[I].first, Notes[I].second);
6389 } else {
6390 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6391 << CCE << E->getSourceRange();
6392 for (unsigned I = 0; I < Notes.size(); ++I)
6393 Diag(Notes[I].first, Notes[I].second);
6394 }
6395 return ExprError();
6396}
6397
6398/// dropPointerConversions - If the given standard conversion sequence
6399/// involves any pointer conversions, remove them. This may change
6400/// the result type of the conversion sequence.
6402 if (SCS.Second == ICK_Pointer_Conversion) {
6403 SCS.Second = ICK_Identity;
6404 SCS.Dimension = ICK_Identity;
6405 SCS.Third = ICK_Identity;
6406 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6407 }
6408}
6409
6410/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6411/// convert the expression From to an Objective-C pointer type.
6414 // Do an implicit conversion to 'id'.
6417 = TryImplicitConversion(S, From, Ty,
6418 // FIXME: Are these flags correct?
6419 /*SuppressUserConversions=*/false,
6420 AllowedExplicit::Conversions,
6421 /*InOverloadResolution=*/false,
6422 /*CStyle=*/false,
6423 /*AllowObjCWritebackConversion=*/false,
6424 /*AllowObjCConversionOnExplicit=*/true);
6425
6426 // Strip off any final conversions to 'id'.
6427 switch (ICS.getKind()) {
6432 break;
6433
6436 break;
6437
6440 break;
6441 }
6442
6443 return ICS;
6444}
6445
6447 if (checkPlaceholderForOverload(*this, From))
6448 return ExprError();
6449
6450 QualType Ty = Context.getObjCIdType();
6453 if (!ICS.isBad())
6454 return PerformImplicitConversion(From, Ty, ICS,
6456 return ExprResult();
6457}
6458
6459static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6460 const Expr *Base = nullptr;
6461 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6462 "expected a member expression");
6463
6464 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6465 M && !M->isImplicitAccess())
6466 Base = M->getBase();
6467 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6468 M && !M->isImplicitAccess())
6469 Base = M->getBase();
6470
6471 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6472
6473 if (T->isPointerType())
6474 T = T->getPointeeType();
6475
6476 return T;
6477}
6478
6480 const FunctionDecl *Fun) {
6481 QualType ObjType = Obj->getType();
6482 if (ObjType->isPointerType()) {
6483 ObjType = ObjType->getPointeeType();
6484 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6486 /*CanOverflow=*/false, FPOptionsOverride());
6487 }
6488 return Obj;
6489}
6490
6492 FunctionDecl *Fun) {
6493 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6496 Obj->getExprLoc(), Obj);
6497}
6498
6500 Expr *Object, MultiExprArg &Args,
6501 SmallVectorImpl<Expr *> &NewArgs) {
6502 assert(Method->isExplicitObjectMemberFunction() &&
6503 "Method is not an explicit member function");
6504 assert(NewArgs.empty() && "NewArgs should be empty");
6505
6506 NewArgs.reserve(Args.size() + 1);
6507 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6508 NewArgs.push_back(This);
6509 NewArgs.append(Args.begin(), Args.end());
6510 Args = NewArgs;
6512 Method, Object->getBeginLoc());
6513}
6514
6515/// Determine whether the provided type is an integral type, or an enumeration
6516/// type of a permitted flavor.
6518 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6520}
6521
6522static ExprResult
6525 QualType T, UnresolvedSetImpl &ViableConversions) {
6526
6527 if (Converter.Suppress)
6528 return ExprError();
6529
6530 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6531 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6532 CXXConversionDecl *Conv =
6533 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6535 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6536 }
6537 return From;
6538}
6539
6540static bool
6543 QualType T, bool HadMultipleCandidates,
6544 UnresolvedSetImpl &ExplicitConversions) {
6545 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6546 DeclAccessPair Found = ExplicitConversions[0];
6547 CXXConversionDecl *Conversion =
6548 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6549
6550 // The user probably meant to invoke the given explicit
6551 // conversion; use it.
6552 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6553 std::string TypeStr;
6554 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6555
6556 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6558 "static_cast<" + TypeStr + ">(")
6560 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6561 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6562
6563 // If we aren't in a SFINAE context, build a call to the
6564 // explicit conversion function.
6565 if (SemaRef.isSFINAEContext())
6566 return true;
6567
6568 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6569 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6570 HadMultipleCandidates);
6571 if (Result.isInvalid())
6572 return true;
6573
6574 // Replace the conversion with a RecoveryExpr, so we don't try to
6575 // instantiate it later, but can further diagnose here.
6576 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6577 From, Result.get()->getType());
6578 if (Result.isInvalid())
6579 return true;
6580 From = Result.get();
6581 }
6582 return false;
6583}
6584
6585static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6587 QualType T, bool HadMultipleCandidates,
6589 CXXConversionDecl *Conversion =
6590 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6591 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6592
6593 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6594 if (!Converter.SuppressConversion) {
6595 if (SemaRef.isSFINAEContext())
6596 return true;
6597
6598 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6599 << From->getSourceRange();
6600 }
6601
6602 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6603 HadMultipleCandidates);
6604 if (Result.isInvalid())
6605 return true;
6606 // Record usage of conversion in an implicit cast.
6607 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6608 CK_UserDefinedConversion, Result.get(),
6609 nullptr, Result.get()->getValueKind(),
6610 SemaRef.CurFPFeatureOverrides());
6611 return false;
6612}
6613
6615 Sema &SemaRef, SourceLocation Loc, Expr *From,
6617 if (!Converter.match(From->getType()) && !Converter.Suppress)
6618 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6619 << From->getSourceRange();
6620
6621 return SemaRef.DefaultLvalueConversion(From);
6622}
6623
6624static void
6626 UnresolvedSetImpl &ViableConversions,
6627 OverloadCandidateSet &CandidateSet) {
6628 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6629 NamedDecl *D = FoundDecl.getDecl();
6630 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6631 if (isa<UsingShadowDecl>(D))
6632 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6633
6634 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6636 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6637 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6638 continue;
6639 }
6640 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6641 SemaRef.AddConversionCandidate(
6642 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6643 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6644 }
6645}
6646
6647/// Attempt to convert the given expression to a type which is accepted
6648/// by the given converter.
6649///
6650/// This routine will attempt to convert an expression of class type to a
6651/// type accepted by the specified converter. In C++11 and before, the class
6652/// must have a single non-explicit conversion function converting to a matching
6653/// type. In C++1y, there can be multiple such conversion functions, but only
6654/// one target type.
6655///
6656/// \param Loc The source location of the construct that requires the
6657/// conversion.
6658///
6659/// \param From The expression we're converting from.
6660///
6661/// \param Converter Used to control and diagnose the conversion process.
6662///
6663/// \returns The expression, converted to an integral or enumeration type if
6664/// successful.
6666 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6667 // We can't perform any more checking for type-dependent expressions.
6668 if (From->isTypeDependent())
6669 return From;
6670
6671 // Process placeholders immediately.
6672 if (From->hasPlaceholderType()) {
6673 ExprResult result = CheckPlaceholderExpr(From);
6674 if (result.isInvalid())
6675 return result;
6676 From = result.get();
6677 }
6678
6679 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6680 ExprResult Converted = DefaultLvalueConversion(From);
6681 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6682 // If the expression already has a matching type, we're golden.
6683 if (Converter.match(T))
6684 return Converted;
6685
6686 // FIXME: Check for missing '()' if T is a function type?
6687
6688 // We can only perform contextual implicit conversions on objects of class
6689 // type.
6690 const RecordType *RecordTy = T->getAs<RecordType>();
6691 if (!RecordTy || !getLangOpts().CPlusPlus) {
6692 if (!Converter.Suppress)
6693 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6694 return From;
6695 }
6696
6697 // We must have a complete class type.
6698 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6699 ContextualImplicitConverter &Converter;
6700 Expr *From;
6701
6702 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6703 : Converter(Converter), From(From) {}
6704
6705 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6706 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6707 }
6708 } IncompleteDiagnoser(Converter, From);
6709
6710 if (Converter.Suppress ? !isCompleteType(Loc, T)
6711 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6712 return From;
6713
6714 // Look for a conversion to an integral or enumeration type.
6716 ViableConversions; // These are *potentially* viable in C++1y.
6717 UnresolvedSet<4> ExplicitConversions;
6718 const auto &Conversions =
6719 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6720
6721 bool HadMultipleCandidates =
6722 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6723
6724 // To check that there is only one target type, in C++1y:
6725 QualType ToType;
6726 bool HasUniqueTargetType = true;
6727
6728 // Collect explicit or viable (potentially in C++1y) conversions.
6729 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6730 NamedDecl *D = (*I)->getUnderlyingDecl();
6731 CXXConversionDecl *Conversion;
6732 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6733 if (ConvTemplate) {
6734 if (getLangOpts().CPlusPlus14)
6735 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6736 else
6737 continue; // C++11 does not consider conversion operator templates(?).
6738 } else
6739 Conversion = cast<CXXConversionDecl>(D);
6740
6741 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6742 "Conversion operator templates are considered potentially "
6743 "viable in C++1y");
6744
6745 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6746 if (Converter.match(CurToType) || ConvTemplate) {
6747
6748 if (Conversion->isExplicit()) {
6749 // FIXME: For C++1y, do we need this restriction?
6750 // cf. diagnoseNoViableConversion()
6751 if (!ConvTemplate)
6752 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6753 } else {
6754 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6755 if (ToType.isNull())
6756 ToType = CurToType.getUnqualifiedType();
6757 else if (HasUniqueTargetType &&
6758 (CurToType.getUnqualifiedType() != ToType))
6759 HasUniqueTargetType = false;
6760 }
6761 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6762 }
6763 }
6764 }
6765
6766 if (getLangOpts().CPlusPlus14) {
6767 // C++1y [conv]p6:
6768 // ... An expression e of class type E appearing in such a context
6769 // is said to be contextually implicitly converted to a specified
6770 // type T and is well-formed if and only if e can be implicitly
6771 // converted to a type T that is determined as follows: E is searched
6772 // for conversion functions whose return type is cv T or reference to
6773 // cv T such that T is allowed by the context. There shall be
6774 // exactly one such T.
6775
6776 // If no unique T is found:
6777 if (ToType.isNull()) {
6778 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6779 HadMultipleCandidates,
6780 ExplicitConversions))
6781 return ExprError();
6782 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6783 }
6784
6785 // If more than one unique Ts are found:
6786 if (!HasUniqueTargetType)
6787 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6788 ViableConversions);
6789
6790 // If one unique T is found:
6791 // First, build a candidate set from the previously recorded
6792 // potentially viable conversions.
6794 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6795 CandidateSet);
6796
6797 // Then, perform overload resolution over the candidate set.
6799 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6800 case OR_Success: {
6801 // Apply this conversion.
6803 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6804 if (recordConversion(*this, Loc, From, Converter, T,
6805 HadMultipleCandidates, Found))
6806 return ExprError();
6807 break;
6808 }
6809 case OR_Ambiguous:
6810 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6811 ViableConversions);
6813 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6814 HadMultipleCandidates,
6815 ExplicitConversions))
6816 return ExprError();
6817 [[fallthrough]];
6818 case OR_Deleted:
6819 // We'll complain below about a non-integral condition type.
6820 break;
6821 }
6822 } else {
6823 switch (ViableConversions.size()) {
6824 case 0: {
6825 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6826 HadMultipleCandidates,
6827 ExplicitConversions))
6828 return ExprError();
6829
6830 // We'll complain below about a non-integral condition type.
6831 break;
6832 }
6833 case 1: {
6834 // Apply this conversion.
6835 DeclAccessPair Found = ViableConversions[0];
6836 if (recordConversion(*this, Loc, From, Converter, T,
6837 HadMultipleCandidates, Found))
6838 return ExprError();
6839 break;
6840 }
6841 default:
6842 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6843 ViableConversions);
6844 }
6845 }
6846
6847 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6848}
6849
6850/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6851/// an acceptable non-member overloaded operator for a call whose
6852/// arguments have types T1 (and, if non-empty, T2). This routine
6853/// implements the check in C++ [over.match.oper]p3b2 concerning
6854/// enumeration types.
6856 FunctionDecl *Fn,
6857 ArrayRef<Expr *> Args) {
6858 QualType T1 = Args[0]->getType();
6859 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6860
6861 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6862 return true;
6863
6864 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6865 return true;
6866
6867 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6868 if (Proto->getNumParams() < 1)
6869 return false;
6870
6871 if (T1->isEnumeralType()) {
6872 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6873 if (Context.hasSameUnqualifiedType(T1, ArgType))
6874 return true;
6875 }
6876
6877 if (Proto->getNumParams() < 2)
6878 return false;
6879
6880 if (!T2.isNull() && T2->isEnumeralType()) {
6881 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6882 if (Context.hasSameUnqualifiedType(T2, ArgType))
6883 return true;
6884 }
6885
6886 return false;
6887}
6888
6891 return false;
6892
6893 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6894 return FD->isTargetMultiVersion();
6895
6896 if (!FD->isMultiVersion())
6897 return false;
6898
6899 // Among multiple target versions consider either the default,
6900 // or the first non-default in the absence of default version.
6901 unsigned SeenAt = 0;
6902 unsigned I = 0;
6903 bool HasDefault = false;
6905 FD, [&](const FunctionDecl *CurFD) {
6906 if (FD == CurFD)
6907 SeenAt = I;
6908 else if (CurFD->isTargetMultiVersionDefault())
6909 HasDefault = true;
6910 ++I;
6911 });
6912 return HasDefault || SeenAt != 0;
6913}
6914
6917 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6918 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6919 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6920 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
6921 bool HasMatchedPackOnParmToNonPackOnArg) {
6922 const FunctionProtoType *Proto
6923 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6924 assert(Proto && "Functions without a prototype cannot be overloaded");
6925 assert(!Function->getDescribedFunctionTemplate() &&
6926 "Use AddTemplateOverloadCandidate for function templates");
6927
6928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6929 if (!isa<CXXConstructorDecl>(Method)) {
6930 // If we get here, it's because we're calling a member function
6931 // that is named without a member access expression (e.g.,
6932 // "this->f") that was either written explicitly or created
6933 // implicitly. This can happen with a qualified call to a member
6934 // function, e.g., X::f(). We use an empty type for the implied
6935 // object argument (C++ [over.call.func]p3), and the acting context
6936 // is irrelevant.
6937 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6939 CandidateSet, SuppressUserConversions,
6940 PartialOverloading, EarlyConversions, PO,
6941 HasMatchedPackOnParmToNonPackOnArg);
6942 return;
6943 }
6944 // We treat a constructor like a non-member function, since its object
6945 // argument doesn't participate in overload resolution.
6946 }
6947
6948 if (!CandidateSet.isNewCandidate(Function, PO))
6949 return;
6950
6951 // C++11 [class.copy]p11: [DR1402]
6952 // A defaulted move constructor that is defined as deleted is ignored by
6953 // overload resolution.
6954 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6955 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6956 Constructor->isMoveConstructor())
6957 return;
6958
6959 // Overload resolution is always an unevaluated context.
6962
6963 // C++ [over.match.oper]p3:
6964 // if no operand has a class type, only those non-member functions in the
6965 // lookup set that have a first parameter of type T1 or "reference to
6966 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6967 // is a right operand) a second parameter of type T2 or "reference to
6968 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6969 // candidate functions.
6970 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6972 return;
6973
6974 // Add this candidate
6975 OverloadCandidate &Candidate =
6976 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6977 Candidate.FoundDecl = FoundDecl;
6978 Candidate.Function = Function;
6979 Candidate.Viable = true;
6980 Candidate.RewriteKind =
6981 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6982 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
6983 Candidate.ExplicitCallArguments = Args.size();
6985 HasMatchedPackOnParmToNonPackOnArg;
6986
6987 // Explicit functions are not actually candidates at all if we're not
6988 // allowing them in this context, but keep them around so we can point
6989 // to them in diagnostics.
6990 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6991 Candidate.Viable = false;
6992 Candidate.FailureKind = ovl_fail_explicit;
6993 return;
6994 }
6995
6996 // Functions with internal linkage are only viable in the same module unit.
6997 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6998 /// FIXME: Currently, the semantics of linkage in clang is slightly
6999 /// different from the semantics in C++ spec. In C++ spec, only names
7000 /// have linkage. So that all entities of the same should share one
7001 /// linkage. But in clang, different entities of the same could have
7002 /// different linkage.
7003 const NamedDecl *ND = Function;
7004 bool IsImplicitlyInstantiated = false;
7005 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7006 ND = SpecInfo->getTemplate();
7007 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7009 }
7010
7011 /// Don't remove inline functions with internal linkage from the overload
7012 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7013 /// However:
7014 /// - Inline functions with internal linkage are a common pattern in
7015 /// headers to avoid ODR issues.
7016 /// - The global module is meant to be a transition mechanism for C and C++
7017 /// headers, and the current rules as written work against that goal.
7018 const bool IsInlineFunctionInGMF =
7019 Function->isFromGlobalModule() &&
7020 (IsImplicitlyInstantiated || Function->isInlined());
7021
7022 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7023 Candidate.Viable = false;
7025 return;
7026 }
7027 }
7028
7030 Candidate.Viable = false;
7032 return;
7033 }
7034
7035 if (Constructor) {
7036 // C++ [class.copy]p3:
7037 // A member function template is never instantiated to perform the copy
7038 // of a class object to an object of its class type.
7039 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7040 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7041 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7042 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7043 ClassType))) {
7044 Candidate.Viable = false;
7046 return;
7047 }
7048
7049 // C++ [over.match.funcs]p8: (proposed DR resolution)
7050 // A constructor inherited from class type C that has a first parameter
7051 // of type "reference to P" (including such a constructor instantiated
7052 // from a template) is excluded from the set of candidate functions when
7053 // constructing an object of type cv D if the argument list has exactly
7054 // one argument and D is reference-related to P and P is reference-related
7055 // to C.
7056 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7057 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7058 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7059 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7060 QualType C = Context.getRecordType(Constructor->getParent());
7061 QualType D = Context.getRecordType(Shadow->getParent());
7062 SourceLocation Loc = Args.front()->getExprLoc();
7063 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7064 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7065 Candidate.Viable = false;
7067 return;
7068 }
7069 }
7070
7071 // Check that the constructor is capable of constructing an object in the
7072 // destination address space.
7074 Constructor->getMethodQualifiers().getAddressSpace(),
7075 CandidateSet.getDestAS(), getASTContext())) {
7076 Candidate.Viable = false;
7078 }
7079 }
7080
7081 unsigned NumParams = Proto->getNumParams();
7082
7083 // (C++ 13.3.2p2): A candidate function having fewer than m
7084 // parameters is viable only if it has an ellipsis in its parameter
7085 // list (8.3.5).
7086 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7087 !Proto->isVariadic() &&
7088 shouldEnforceArgLimit(PartialOverloading, Function)) {
7089 Candidate.Viable = false;
7091 return;
7092 }
7093
7094 // (C++ 13.3.2p2): A candidate function having more than m parameters
7095 // is viable only if the (m+1)st parameter has a default argument
7096 // (8.3.6). For the purposes of overload resolution, the
7097 // parameter list is truncated on the right, so that there are
7098 // exactly m parameters.
7099 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7100 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7101 !PartialOverloading) {
7102 // Not enough arguments.
7103 Candidate.Viable = false;
7105 return;
7106 }
7107
7108 // (CUDA B.1): Check for invalid calls between targets.
7109 if (getLangOpts().CUDA) {
7110 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7111 // Skip the check for callers that are implicit members, because in this
7112 // case we may not yet know what the member's target is; the target is
7113 // inferred for the member automatically, based on the bases and fields of
7114 // the class.
7115 if (!(Caller && Caller->isImplicit()) &&
7116 !CUDA().IsAllowedCall(Caller, Function)) {
7117 Candidate.Viable = false;
7118 Candidate.FailureKind = ovl_fail_bad_target;
7119 return;
7120 }
7121 }
7122
7123 if (Function->getTrailingRequiresClause()) {
7124 ConstraintSatisfaction Satisfaction;
7125 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7126 /*ForOverloadResolution*/ true) ||
7127 !Satisfaction.IsSatisfied) {
7128 Candidate.Viable = false;
7130 return;
7131 }
7132 }
7133
7134 // Determine the implicit conversion sequences for each of the
7135 // arguments.
7136 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7137 unsigned ConvIdx =
7138 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7139 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7140 // We already formed a conversion sequence for this parameter during
7141 // template argument deduction.
7142 } else if (ArgIdx < NumParams) {
7143 // (C++ 13.3.2p3): for F to be a viable function, there shall
7144 // exist for each argument an implicit conversion sequence
7145 // (13.3.3.1) that converts that argument to the corresponding
7146 // parameter of F.
7147 QualType ParamType = Proto->getParamType(ArgIdx);
7148 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7149 if (ParamABI == ParameterABI::HLSLOut ||
7150 ParamABI == ParameterABI::HLSLInOut)
7151 ParamType = ParamType.getNonReferenceType();
7152 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7153 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7154 /*InOverloadResolution=*/true,
7155 /*AllowObjCWritebackConversion=*/
7156 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7157 if (Candidate.Conversions[ConvIdx].isBad()) {
7158 Candidate.Viable = false;
7160 return;
7161 }
7162 } else {
7163 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7164 // argument for which there is no corresponding parameter is
7165 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7166 Candidate.Conversions[ConvIdx].setEllipsis();
7167 }
7168 }
7169
7170 if (EnableIfAttr *FailedAttr =
7171 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7172 Candidate.Viable = false;
7173 Candidate.FailureKind = ovl_fail_enable_if;
7174 Candidate.DeductionFailure.Data = FailedAttr;
7175 return;
7176 }
7177}
7178
7182 if (Methods.size() <= 1)
7183 return nullptr;
7184
7185 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7186 bool Match = true;
7187 ObjCMethodDecl *Method = Methods[b];
7188 unsigned NumNamedArgs = Sel.getNumArgs();
7189 // Method might have more arguments than selector indicates. This is due
7190 // to addition of c-style arguments in method.
7191 if (Method->param_size() > NumNamedArgs)
7192 NumNamedArgs = Method->param_size();
7193 if (Args.size() < NumNamedArgs)
7194 continue;
7195
7196 for (unsigned i = 0; i < NumNamedArgs; i++) {
7197 // We can't do any type-checking on a type-dependent argument.
7198 if (Args[i]->isTypeDependent()) {
7199 Match = false;
7200 break;
7201 }
7202
7203 ParmVarDecl *param = Method->parameters()[i];
7204 Expr *argExpr = Args[i];
7205 assert(argExpr && "SelectBestMethod(): missing expression");
7206
7207 // Strip the unbridged-cast placeholder expression off unless it's
7208 // a consumed argument.
7209 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7210 !param->hasAttr<CFConsumedAttr>())
7211 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7212
7213 // If the parameter is __unknown_anytype, move on to the next method.
7214 if (param->getType() == Context.UnknownAnyTy) {
7215 Match = false;
7216 break;
7217 }
7218
7219 ImplicitConversionSequence ConversionState
7220 = TryCopyInitialization(*this, argExpr, param->getType(),
7221 /*SuppressUserConversions*/false,
7222 /*InOverloadResolution=*/true,
7223 /*AllowObjCWritebackConversion=*/
7224 getLangOpts().ObjCAutoRefCount,
7225 /*AllowExplicit*/false);
7226 // This function looks for a reasonably-exact match, so we consider
7227 // incompatible pointer conversions to be a failure here.
7228 if (ConversionState.isBad() ||
7229 (ConversionState.isStandard() &&
7230 ConversionState.Standard.Second ==
7232 Match = false;
7233 break;
7234 }
7235 }
7236 // Promote additional arguments to variadic methods.
7237 if (Match && Method->isVariadic()) {
7238 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7239 if (Args[i]->isTypeDependent()) {
7240 Match = false;
7241 break;
7242 }
7243 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7244 nullptr);
7245 if (Arg.isInvalid()) {
7246 Match = false;
7247 break;
7248 }
7249 }
7250 } else {
7251 // Check for extra arguments to non-variadic methods.
7252 if (Args.size() != NumNamedArgs)
7253 Match = false;
7254 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7255 // Special case when selectors have no argument. In this case, select
7256 // one with the most general result type of 'id'.
7257 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7258 QualType ReturnT = Methods[b]->getReturnType();
7259 if (ReturnT->isObjCIdType())
7260 return Methods[b];
7261 }
7262 }
7263 }
7264
7265 if (Match)
7266 return Method;
7267 }
7268 return nullptr;
7269}
7270
7272 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7273 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7274 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7275 if (ThisArg) {
7276 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7277 assert(!isa<CXXConstructorDecl>(Method) &&
7278 "Shouldn't have `this` for ctors!");
7279 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7281 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7282 if (R.isInvalid())
7283 return false;
7284 ConvertedThis = R.get();
7285 } else {
7286 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7287 (void)MD;
7288 assert((MissingImplicitThis || MD->isStatic() ||
7289 isa<CXXConstructorDecl>(MD)) &&
7290 "Expected `this` for non-ctor instance methods");
7291 }
7292 ConvertedThis = nullptr;
7293 }
7294
7295 // Ignore any variadic arguments. Converting them is pointless, since the
7296 // user can't refer to them in the function condition.
7297 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7298
7299 // Convert the arguments.
7300 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7301 ExprResult R;
7303 S.Context, Function->getParamDecl(I)),
7304 SourceLocation(), Args[I]);
7305
7306 if (R.isInvalid())
7307 return false;
7308
7309 ConvertedArgs.push_back(R.get());
7310 }
7311
7312 if (Trap.hasErrorOccurred())
7313 return false;
7314
7315 // Push default arguments if needed.
7316 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7317 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7318 ParmVarDecl *P = Function->getParamDecl(i);
7319 if (!P->hasDefaultArg())
7320 return false;
7322 if (R.isInvalid())
7323 return false;
7324 ConvertedArgs.push_back(R.get());
7325 }
7326
7327 if (Trap.hasErrorOccurred())
7328 return false;
7329 }
7330 return true;
7331}
7332
7334 SourceLocation CallLoc,
7335 ArrayRef<Expr *> Args,
7336 bool MissingImplicitThis) {
7337 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7338 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7339 return nullptr;
7340
7341 SFINAETrap Trap(*this);
7342 SmallVector<Expr *, 16> ConvertedArgs;
7343 // FIXME: We should look into making enable_if late-parsed.
7344 Expr *DiscardedThis;
7346 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7347 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7348 return *EnableIfAttrs.begin();
7349
7350 for (auto *EIA : EnableIfAttrs) {
7352 // FIXME: This doesn't consider value-dependent cases, because doing so is
7353 // very difficult. Ideally, we should handle them more gracefully.
7354 if (EIA->getCond()->isValueDependent() ||
7355 !EIA->getCond()->EvaluateWithSubstitution(
7356 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7357 return EIA;
7358
7359 if (!Result.isInt() || !Result.getInt().getBoolValue())
7360 return EIA;
7361 }
7362 return nullptr;
7363}
7364
7365template <typename CheckFn>
7367 bool ArgDependent, SourceLocation Loc,
7368 CheckFn &&IsSuccessful) {
7370 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7371 if (ArgDependent == DIA->getArgDependent())
7372 Attrs.push_back(DIA);
7373 }
7374
7375 // Common case: No diagnose_if attributes, so we can quit early.
7376 if (Attrs.empty())
7377 return false;
7378
7379 auto WarningBegin = std::stable_partition(
7380 Attrs.begin(), Attrs.end(),
7381 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7382
7383 // Note that diagnose_if attributes are late-parsed, so they appear in the
7384 // correct order (unlike enable_if attributes).
7385 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7386 IsSuccessful);
7387 if (ErrAttr != WarningBegin) {
7388 const DiagnoseIfAttr *DIA = *ErrAttr;
7389 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7390 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7391 << DIA->getParent() << DIA->getCond()->getSourceRange();
7392 return true;
7393 }
7394
7395 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7396 if (IsSuccessful(DIA)) {
7397 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7398 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7399 << DIA->getParent() << DIA->getCond()->getSourceRange();
7400 }
7401
7402 return false;
7403}
7404
7406 const Expr *ThisArg,
7408 SourceLocation Loc) {
7410 *this, Function, /*ArgDependent=*/true, Loc,
7411 [&](const DiagnoseIfAttr *DIA) {
7413 // It's sane to use the same Args for any redecl of this function, since
7414 // EvaluateWithSubstitution only cares about the position of each
7415 // argument in the arg list, not the ParmVarDecl* it maps to.
7416 if (!DIA->getCond()->EvaluateWithSubstitution(
7417 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7418 return false;
7419 return Result.isInt() && Result.getInt().getBoolValue();
7420 });
7421}
7422
7424 SourceLocation Loc) {
7426 *this, ND, /*ArgDependent=*/false, Loc,
7427 [&](const DiagnoseIfAttr *DIA) {
7428 bool Result;
7429 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7430 Result;
7431 });
7432}
7433
7435 ArrayRef<Expr *> Args,
7436 OverloadCandidateSet &CandidateSet,
7437 TemplateArgumentListInfo *ExplicitTemplateArgs,
7438 bool SuppressUserConversions,
7439 bool PartialOverloading,
7440 bool FirstArgumentIsBase) {
7441 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7442 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7443 ArrayRef<Expr *> FunctionArgs = Args;
7444
7445 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7446 FunctionDecl *FD =
7447 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7448
7449 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7450 QualType ObjectType;
7451 Expr::Classification ObjectClassification;
7452 if (Args.size() > 0) {
7453 if (Expr *E = Args[0]) {
7454 // Use the explicit base to restrict the lookup:
7455 ObjectType = E->getType();
7456 // Pointers in the object arguments are implicitly dereferenced, so we
7457 // always classify them as l-values.
7458 if (!ObjectType.isNull() && ObjectType->isPointerType())
7459 ObjectClassification = Expr::Classification::makeSimpleLValue();
7460 else
7461 ObjectClassification = E->Classify(Context);
7462 } // .. else there is an implicit base.
7463 FunctionArgs = Args.slice(1);
7464 }
7465 if (FunTmpl) {
7466 AddMethodTemplateCandidate(
7467 FunTmpl, F.getPair(),
7468 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7469 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7470 FunctionArgs, CandidateSet, SuppressUserConversions,
7471 PartialOverloading);
7472 } else {
7473 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7474 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7475 ObjectClassification, FunctionArgs, CandidateSet,
7476 SuppressUserConversions, PartialOverloading);
7477 }
7478 } else {
7479 // This branch handles both standalone functions and static methods.
7480
7481 // Slice the first argument (which is the base) when we access
7482 // static method as non-static.
7483 if (Args.size() > 0 &&
7484 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7485 !isa<CXXConstructorDecl>(FD)))) {
7486 assert(cast<CXXMethodDecl>(FD)->isStatic());
7487 FunctionArgs = Args.slice(1);
7488 }
7489 if (FunTmpl) {
7490 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7491 ExplicitTemplateArgs, FunctionArgs,
7492 CandidateSet, SuppressUserConversions,
7493 PartialOverloading);
7494 } else {
7495 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7496 SuppressUserConversions, PartialOverloading);
7497 }
7498 }
7499 }
7500}
7501
7503 Expr::Classification ObjectClassification,
7504 ArrayRef<Expr *> Args,
7505 OverloadCandidateSet &CandidateSet,
7506 bool SuppressUserConversions,
7508 NamedDecl *Decl = FoundDecl.getDecl();
7509 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7510
7511 if (isa<UsingShadowDecl>(Decl))
7512 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7513
7514 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7515 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7516 "Expected a member function template");
7517 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7518 /*ExplicitArgs*/ nullptr, ObjectType,
7519 ObjectClassification, Args, CandidateSet,
7520 SuppressUserConversions, false, PO);
7521 } else {
7522 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7523 ObjectType, ObjectClassification, Args, CandidateSet,
7524 SuppressUserConversions, false, {}, PO);
7525 }
7526}
7527
7529 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7530 CXXRecordDecl *ActingContext, QualType ObjectType,
7531 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7532 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7533 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7534 OverloadCandidateParamOrder PO, bool HasMatchedPackOnParmToNonPackOnArg) {
7535 const FunctionProtoType *Proto
7536 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7537 assert(Proto && "Methods without a prototype cannot be overloaded");
7538 assert(!isa<CXXConstructorDecl>(Method) &&
7539 "Use AddOverloadCandidate for constructors");
7540
7541 if (!CandidateSet.isNewCandidate(Method, PO))
7542 return;
7543
7544 // C++11 [class.copy]p23: [DR1402]
7545 // A defaulted move assignment operator that is defined as deleted is
7546 // ignored by overload resolution.
7547 if (Method->isDefaulted() && Method->isDeleted() &&
7548 Method->isMoveAssignmentOperator())
7549 return;
7550
7551 // Overload resolution is always an unevaluated context.
7554
7555 // Add this candidate
7556 OverloadCandidate &Candidate =
7557 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7558 Candidate.FoundDecl = FoundDecl;
7559 Candidate.Function = Method;
7560 Candidate.RewriteKind =
7561 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7562 Candidate.TookAddressOfOverload =
7564 Candidate.ExplicitCallArguments = Args.size();
7566 HasMatchedPackOnParmToNonPackOnArg;
7567
7568 bool IgnoreExplicitObject =
7569 (Method->isExplicitObjectMemberFunction() &&
7570 CandidateSet.getKind() ==
7572 bool ImplicitObjectMethodTreatedAsStatic =
7573 CandidateSet.getKind() ==
7576
7577 unsigned ExplicitOffset =
7578 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7579
7580 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7581 int(ImplicitObjectMethodTreatedAsStatic);
7582
7583 // (C++ 13.3.2p2): A candidate function having fewer than m
7584 // parameters is viable only if it has an ellipsis in its parameter
7585 // list (8.3.5).
7586 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7587 !Proto->isVariadic() &&
7588 shouldEnforceArgLimit(PartialOverloading, Method)) {
7589 Candidate.Viable = false;
7591 return;
7592 }
7593
7594 // (C++ 13.3.2p2): A candidate function having more than m parameters
7595 // is viable only if the (m+1)st parameter has a default argument
7596 // (8.3.6). For the purposes of overload resolution, the
7597 // parameter list is truncated on the right, so that there are
7598 // exactly m parameters.
7599 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7600 ExplicitOffset +
7601 int(ImplicitObjectMethodTreatedAsStatic);
7602
7603 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7604 // Not enough arguments.
7605 Candidate.Viable = false;
7607 return;
7608 }
7609
7610 Candidate.Viable = true;
7611
7612 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7613 if (ObjectType.isNull())
7614 Candidate.IgnoreObjectArgument = true;
7615 else if (Method->isStatic()) {
7616 // [over.best.ics.general]p8
7617 // When the parameter is the implicit object parameter of a static member
7618 // function, the implicit conversion sequence is a standard conversion
7619 // sequence that is neither better nor worse than any other standard
7620 // conversion sequence.
7621 //
7622 // This is a rule that was introduced in C++23 to support static lambdas. We
7623 // apply it retroactively because we want to support static lambdas as an
7624 // extension and it doesn't hurt previous code.
7625 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7626 } else {
7627 // Determine the implicit conversion sequence for the object
7628 // parameter.
7629 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7630 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7631 Method, ActingContext, /*InOverloadResolution=*/true);
7632 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7633 Candidate.Viable = false;
7635 return;
7636 }
7637 }
7638
7639 // (CUDA B.1): Check for invalid calls between targets.
7640 if (getLangOpts().CUDA)
7641 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7642 Method)) {
7643 Candidate.Viable = false;
7644 Candidate.FailureKind = ovl_fail_bad_target;
7645 return;
7646 }
7647
7648 if (Method->getTrailingRequiresClause()) {
7649 ConstraintSatisfaction Satisfaction;
7650 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7651 /*ForOverloadResolution*/ true) ||
7652 !Satisfaction.IsSatisfied) {
7653 Candidate.Viable = false;
7655 return;
7656 }
7657 }
7658
7659 // Determine the implicit conversion sequences for each of the
7660 // arguments.
7661 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7662 unsigned ConvIdx =
7663 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7664 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7665 // We already formed a conversion sequence for this parameter during
7666 // template argument deduction.
7667 } else if (ArgIdx < NumParams) {
7668 // (C++ 13.3.2p3): for F to be a viable function, there shall
7669 // exist for each argument an implicit conversion sequence
7670 // (13.3.3.1) that converts that argument to the corresponding
7671 // parameter of F.
7672 QualType ParamType;
7673 if (ImplicitObjectMethodTreatedAsStatic) {
7674 ParamType = ArgIdx == 0
7676 : Proto->getParamType(ArgIdx - 1);
7677 } else {
7678 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7679 }
7680 Candidate.Conversions[ConvIdx]
7681 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7682 SuppressUserConversions,
7683 /*InOverloadResolution=*/true,
7684 /*AllowObjCWritebackConversion=*/
7685 getLangOpts().ObjCAutoRefCount);
7686 if (Candidate.Conversions[ConvIdx].isBad()) {
7687 Candidate.Viable = false;
7689 return;
7690 }
7691 } else {
7692 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7693 // argument for which there is no corresponding parameter is
7694 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7695 Candidate.Conversions[ConvIdx].setEllipsis();
7696 }
7697 }
7698
7699 if (EnableIfAttr *FailedAttr =
7700 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7701 Candidate.Viable = false;
7702 Candidate.FailureKind = ovl_fail_enable_if;
7703 Candidate.DeductionFailure.Data = FailedAttr;
7704 return;
7705 }
7706
7707 if (isNonViableMultiVersionOverload(Method)) {
7708 Candidate.Viable = false;
7710 }
7711}
7712
7714 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7715 CXXRecordDecl *ActingContext,
7716 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7717 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7718 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7719 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7720 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7721 return;
7722
7723 // C++ [over.match.funcs]p7:
7724 // In each case where a candidate is a function template, candidate
7725 // function template specializations are generated using template argument
7726 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7727 // candidate functions in the usual way.113) A given name can refer to one
7728 // or more function templates and also to a set of overloaded non-template
7729 // functions. In such a case, the candidate functions generated from each
7730 // function template are combined with the set of non-template candidate
7731 // functions.
7732 TemplateDeductionInfo Info(CandidateSet.getLocation());
7733 FunctionDecl *Specialization = nullptr;
7734 ConversionSequenceList Conversions;
7736 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7737 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7738 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7739 [&](ArrayRef<QualType> ParamTypes) {
7740 return CheckNonDependentConversions(
7741 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7742 SuppressUserConversions, ActingContext, ObjectType,
7743 ObjectClassification, PO);
7744 });
7746 OverloadCandidate &Candidate =
7747 CandidateSet.addCandidate(Conversions.size(), Conversions);
7748 Candidate.FoundDecl = FoundDecl;
7749 Candidate.Function = MethodTmpl->getTemplatedDecl();
7750 Candidate.Viable = false;
7751 Candidate.RewriteKind =
7752 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7753 Candidate.IsSurrogate = false;
7754 Candidate.IgnoreObjectArgument =
7755 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7756 ObjectType.isNull();
7757 Candidate.ExplicitCallArguments = Args.size();
7760 else {
7763 Info);
7764 }
7765 return;
7766 }
7767
7768 // Add the function template specialization produced by template argument
7769 // deduction as a candidate.
7770 assert(Specialization && "Missing member function template specialization?");
7771 assert(isa<CXXMethodDecl>(Specialization) &&
7772 "Specialization is not a member function?");
7773 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7774 ActingContext, ObjectType, ObjectClassification, Args,
7775 CandidateSet, SuppressUserConversions, PartialOverloading,
7776 Conversions, PO,
7778}
7779
7780/// Determine whether a given function template has a simple explicit specifier
7781/// or a non-value-dependent explicit-specification that evaluates to true.
7784}
7785
7787 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7788 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7789 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7790 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7791 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7792 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7793 return;
7794
7795 // If the function template has a non-dependent explicit specification,
7796 // exclude it now if appropriate; we are not permitted to perform deduction
7797 // and substitution in this case.
7798 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7799 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7800 Candidate.FoundDecl = FoundDecl;
7801 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7802 Candidate.Viable = false;
7803 Candidate.FailureKind = ovl_fail_explicit;
7804 return;
7805 }
7806
7807 // C++ [over.match.funcs]p7:
7808 // In each case where a candidate is a function template, candidate
7809 // function template specializations are generated using template argument
7810 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7811 // candidate functions in the usual way.113) A given name can refer to one
7812 // or more function templates and also to a set of overloaded non-template
7813 // functions. In such a case, the candidate functions generated from each
7814 // function template are combined with the set of non-template candidate
7815 // functions.
7816 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7817 FunctionTemplate->getTemplateDepth());
7818 FunctionDecl *Specialization = nullptr;
7819 ConversionSequenceList Conversions;
7821 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7822 PartialOverloading, AggregateCandidateDeduction,
7823 /*PartialOrdering=*/false,
7824 /*ObjectType=*/QualType(),
7825 /*ObjectClassification=*/Expr::Classification(),
7826 [&](ArrayRef<QualType> ParamTypes) {
7827 return CheckNonDependentConversions(
7828 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7829 SuppressUserConversions, nullptr, QualType(), {}, PO);
7830 });
7832 OverloadCandidate &Candidate =
7833 CandidateSet.addCandidate(Conversions.size(), Conversions);
7834 Candidate.FoundDecl = FoundDecl;
7835 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7836 Candidate.Viable = false;
7837 Candidate.RewriteKind =
7838 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7839 Candidate.IsSurrogate = false;
7840 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7841 // Ignore the object argument if there is one, since we don't have an object
7842 // type.
7843 Candidate.IgnoreObjectArgument =
7844 isa<CXXMethodDecl>(Candidate.Function) &&
7845 !isa<CXXConstructorDecl>(Candidate.Function);
7846 Candidate.ExplicitCallArguments = Args.size();
7849 else {
7852 Info);
7853 }
7854 return;
7855 }
7856
7857 // Add the function template specialization produced by template argument
7858 // deduction as a candidate.
7859 assert(Specialization && "Missing function template specialization?");
7860 AddOverloadCandidate(
7861 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7862 PartialOverloading, AllowExplicit,
7863 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7866}
7867
7869 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7870 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7871 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7872 CXXRecordDecl *ActingContext, QualType ObjectType,
7873 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7874 // FIXME: The cases in which we allow explicit conversions for constructor
7875 // arguments never consider calling a constructor template. It's not clear
7876 // that is correct.
7877 const bool AllowExplicit = false;
7878
7879 auto *FD = FunctionTemplate->getTemplatedDecl();
7880 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7881 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7882 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7883
7884 Conversions =
7885 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7886
7887 // Overload resolution is always an unevaluated context.
7890
7891 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7892 // require that, but this check should never result in a hard error, and
7893 // overload resolution is permitted to sidestep instantiations.
7894 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7895 !ObjectType.isNull()) {
7896 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7897 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7898 !ParamTypes[0]->isDependentType()) {
7899 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7900 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7901 Method, ActingContext, /*InOverloadResolution=*/true,
7902 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7903 : QualType());
7904 if (Conversions[ConvIdx].isBad())
7905 return true;
7906 }
7907 }
7908
7909 unsigned Offset =
7910 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7911
7912 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7913 I != N; ++I) {
7914 QualType ParamType = ParamTypes[I + Offset];
7915 if (!ParamType->isDependentType()) {
7916 unsigned ConvIdx;
7918 ConvIdx = Args.size() - 1 - I;
7919 assert(Args.size() + ThisConversions == 2 &&
7920 "number of args (including 'this') must be exactly 2 for "
7921 "reversed order");
7922 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7923 // would also be 0. 'this' got ConvIdx = 1 previously.
7924 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7925 } else {
7926 // For members, 'this' got ConvIdx = 0 previously.
7927 ConvIdx = ThisConversions + I;
7928 }
7929 Conversions[ConvIdx]
7930 = TryCopyInitialization(*this, Args[I], ParamType,
7931 SuppressUserConversions,
7932 /*InOverloadResolution=*/true,
7933 /*AllowObjCWritebackConversion=*/
7934 getLangOpts().ObjCAutoRefCount,
7935 AllowExplicit);
7936 if (Conversions[ConvIdx].isBad())
7937 return true;
7938 }
7939 }
7940
7941 return false;
7942}
7943
7944/// Determine whether this is an allowable conversion from the result
7945/// of an explicit conversion operator to the expected type, per C++
7946/// [over.match.conv]p1 and [over.match.ref]p1.
7947///
7948/// \param ConvType The return type of the conversion function.
7949///
7950/// \param ToType The type we are converting to.
7951///
7952/// \param AllowObjCPointerConversion Allow a conversion from one
7953/// Objective-C pointer to another.
7954///
7955/// \returns true if the conversion is allowable, false otherwise.
7957 QualType ConvType, QualType ToType,
7958 bool AllowObjCPointerConversion) {
7959 QualType ToNonRefType = ToType.getNonReferenceType();
7960
7961 // Easy case: the types are the same.
7962 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7963 return true;
7964
7965 // Allow qualification conversions.
7966 bool ObjCLifetimeConversion;
7967 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7968 ObjCLifetimeConversion))
7969 return true;
7970
7971 // If we're not allowed to consider Objective-C pointer conversions,
7972 // we're done.
7973 if (!AllowObjCPointerConversion)
7974 return false;
7975
7976 // Is this an Objective-C pointer conversion?
7977 bool IncompatibleObjC = false;
7978 QualType ConvertedType;
7979 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7980 IncompatibleObjC);
7981}
7982
7984 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7985 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7986 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7987 bool AllowExplicit, bool AllowResultConversion,
7988 bool HasMatchedPackOnParmToNonPackOnArg) {
7989 assert(!Conversion->getDescribedFunctionTemplate() &&
7990 "Conversion function templates use AddTemplateConversionCandidate");
7991 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7992 if (!CandidateSet.isNewCandidate(Conversion))
7993 return;
7994
7995 // If the conversion function has an undeduced return type, trigger its
7996 // deduction now.
7997 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7998 if (DeduceReturnType(Conversion, From->getExprLoc()))
7999 return;
8000 ConvType = Conversion->getConversionType().getNonReferenceType();
8001 }
8002
8003 // If we don't allow any conversion of the result type, ignore conversion
8004 // functions that don't convert to exactly (possibly cv-qualified) T.
8005 if (!AllowResultConversion &&
8006 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8007 return;
8008
8009 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8010 // operator is only a candidate if its return type is the target type or
8011 // can be converted to the target type with a qualification conversion.
8012 //
8013 // FIXME: Include such functions in the candidate list and explain why we
8014 // can't select them.
8015 if (Conversion->isExplicit() &&
8016 !isAllowableExplicitConversion(*this, ConvType, ToType,
8017 AllowObjCConversionOnExplicit))
8018 return;
8019
8020 // Overload resolution is always an unevaluated context.
8023
8024 // Add this candidate
8025 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8026 Candidate.FoundDecl = FoundDecl;
8027 Candidate.Function = Conversion;
8029 Candidate.FinalConversion.setFromType(ConvType);
8030 Candidate.FinalConversion.setAllToTypes(ToType);
8031 Candidate.Viable = true;
8032 Candidate.ExplicitCallArguments = 1;
8034 HasMatchedPackOnParmToNonPackOnArg;
8035
8036 // Explicit functions are not actually candidates at all if we're not
8037 // allowing them in this context, but keep them around so we can point
8038 // to them in diagnostics.
8039 if (!AllowExplicit && Conversion->isExplicit()) {
8040 Candidate.Viable = false;
8041 Candidate.FailureKind = ovl_fail_explicit;
8042 return;
8043 }
8044
8045 // C++ [over.match.funcs]p4:
8046 // For conversion functions, the function is considered to be a member of
8047 // the class of the implicit implied object argument for the purpose of
8048 // defining the type of the implicit object parameter.
8049 //
8050 // Determine the implicit conversion sequence for the implicit
8051 // object parameter.
8052 QualType ObjectType = From->getType();
8053 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8054 ObjectType = FromPtrType->getPointeeType();
8055 const auto *ConversionContext =
8056 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8057
8058 // C++23 [over.best.ics.general]
8059 // However, if the target is [...]
8060 // - the object parameter of a user-defined conversion function
8061 // [...] user-defined conversion sequences are not considered.
8063 *this, CandidateSet.getLocation(), From->getType(),
8064 From->Classify(Context), Conversion, ConversionContext,
8065 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8066 /*SuppressUserConversion*/ true);
8067
8068 if (Candidate.Conversions[0].isBad()) {
8069 Candidate.Viable = false;
8071 return;
8072 }
8073
8074 if (Conversion->getTrailingRequiresClause()) {
8075 ConstraintSatisfaction Satisfaction;
8076 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8077 !Satisfaction.IsSatisfied) {
8078 Candidate.Viable = false;
8080 return;
8081 }
8082 }
8083
8084 // We won't go through a user-defined type conversion function to convert a
8085 // derived to base as such conversions are given Conversion Rank. They only
8086 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8087 QualType FromCanon
8088 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8089 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8090 if (FromCanon == ToCanon ||
8091 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8092 Candidate.Viable = false;
8094 return;
8095 }
8096
8097 // To determine what the conversion from the result of calling the
8098 // conversion function to the type we're eventually trying to
8099 // convert to (ToType), we need to synthesize a call to the
8100 // conversion function and attempt copy initialization from it. This
8101 // makes sure that we get the right semantics with respect to
8102 // lvalues/rvalues and the type. Fortunately, we can allocate this
8103 // call on the stack and we don't need its arguments to be
8104 // well-formed.
8105 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8106 VK_LValue, From->getBeginLoc());
8108 Context.getPointerType(Conversion->getType()),
8109 CK_FunctionToPointerDecay, &ConversionRef,
8111
8112 QualType ConversionType = Conversion->getConversionType();
8113 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8114 Candidate.Viable = false;
8116 return;
8117 }
8118
8119 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8120
8121 // Note that it is safe to allocate CallExpr on the stack here because
8122 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8123 // allocator).
8124 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8125
8126 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8127 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8128 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8129
8131 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8132 /*SuppressUserConversions=*/true,
8133 /*InOverloadResolution=*/false,
8134 /*AllowObjCWritebackConversion=*/false);
8135
8136 switch (ICS.getKind()) {
8138 Candidate.FinalConversion = ICS.Standard;
8139
8140 // C++ [over.ics.user]p3:
8141 // If the user-defined conversion is specified by a specialization of a
8142 // conversion function template, the second standard conversion sequence
8143 // shall have exact match rank.
8144 if (Conversion->getPrimaryTemplate() &&
8146 Candidate.Viable = false;
8148 return;
8149 }
8150
8151 // C++0x [dcl.init.ref]p5:
8152 // In the second case, if the reference is an rvalue reference and
8153 // the second standard conversion sequence of the user-defined
8154 // conversion sequence includes an lvalue-to-rvalue conversion, the
8155 // program is ill-formed.
8156 if (ToType->isRValueReferenceType() &&
8158 Candidate.Viable = false;
8160 return;
8161 }
8162 break;
8163
8165 Candidate.Viable = false;
8167 return;
8168
8169 default:
8170 llvm_unreachable(
8171 "Can only end up with a standard conversion sequence or failure");
8172 }
8173
8174 if (EnableIfAttr *FailedAttr =
8175 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8176 Candidate.Viable = false;
8177 Candidate.FailureKind = ovl_fail_enable_if;
8178 Candidate.DeductionFailure.Data = FailedAttr;
8179 return;
8180 }
8181
8182 if (isNonViableMultiVersionOverload(Conversion)) {
8183 Candidate.Viable = false;
8185 }
8186}
8187
8189 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8190 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8191 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8192 bool AllowExplicit, bool AllowResultConversion) {
8193 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8194 "Only conversion function templates permitted here");
8195
8196 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8197 return;
8198
8199 // If the function template has a non-dependent explicit specification,
8200 // exclude it now if appropriate; we are not permitted to perform deduction
8201 // and substitution in this case.
8202 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8203 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8204 Candidate.FoundDecl = FoundDecl;
8205 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8206 Candidate.Viable = false;
8207 Candidate.FailureKind = ovl_fail_explicit;
8208 return;
8209 }
8210
8211 QualType ObjectType = From->getType();
8212 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8213
8214 TemplateDeductionInfo Info(CandidateSet.getLocation());
8217 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8218 Specialization, Info);
8220 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8221 Candidate.FoundDecl = FoundDecl;
8222 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8223 Candidate.Viable = false;
8225 Candidate.ExplicitCallArguments = 1;
8227 Info);
8228 return;
8229 }
8230
8231 // Add the conversion function template specialization produced by
8232 // template argument deduction as a candidate.
8233 assert(Specialization && "Missing function template specialization?");
8234 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8235 CandidateSet, AllowObjCConversionOnExplicit,
8236 AllowExplicit, AllowResultConversion,
8238}
8239
8241 DeclAccessPair FoundDecl,
8242 CXXRecordDecl *ActingContext,
8243 const FunctionProtoType *Proto,
8244 Expr *Object,
8245 ArrayRef<Expr *> Args,
8246 OverloadCandidateSet& CandidateSet) {
8247 if (!CandidateSet.isNewCandidate(Conversion))
8248 return;
8249
8250 // Overload resolution is always an unevaluated context.
8253
8254 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8255 Candidate.FoundDecl = FoundDecl;
8256 Candidate.Function = nullptr;
8257 Candidate.Surrogate = Conversion;
8258 Candidate.IsSurrogate = true;
8259 Candidate.Viable = true;
8260 Candidate.ExplicitCallArguments = Args.size();
8261
8262 // Determine the implicit conversion sequence for the implicit
8263 // object parameter.
8264 ImplicitConversionSequence ObjectInit;
8265 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8266 ObjectInit = TryCopyInitialization(*this, Object,
8267 Conversion->getParamDecl(0)->getType(),
8268 /*SuppressUserConversions=*/false,
8269 /*InOverloadResolution=*/true, false);
8270 } else {
8272 *this, CandidateSet.getLocation(), Object->getType(),
8273 Object->Classify(Context), Conversion, ActingContext);
8274 }
8275
8276 if (ObjectInit.isBad()) {
8277 Candidate.Viable = false;
8279 Candidate.Conversions[0] = ObjectInit;
8280 return;
8281 }
8282
8283 // The first conversion is actually a user-defined conversion whose
8284 // first conversion is ObjectInit's standard conversion (which is
8285 // effectively a reference binding). Record it as such.
8286 Candidate.Conversions[0].setUserDefined();
8287 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8288 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8289 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8290 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8291 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8292 Candidate.Conversions[0].UserDefined.After
8293 = Candidate.Conversions[0].UserDefined.Before;
8294 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8295
8296 // Find the
8297 unsigned NumParams = Proto->getNumParams();
8298
8299 // (C++ 13.3.2p2): A candidate function having fewer than m
8300 // parameters is viable only if it has an ellipsis in its parameter
8301 // list (8.3.5).
8302 if (Args.size() > NumParams && !Proto->isVariadic()) {
8303 Candidate.Viable = false;
8305 return;
8306 }
8307
8308 // Function types don't have any default arguments, so just check if
8309 // we have enough arguments.
8310 if (Args.size() < NumParams) {
8311 // Not enough arguments.
8312 Candidate.Viable = false;
8314 return;
8315 }
8316
8317 // Determine the implicit conversion sequences for each of the
8318 // arguments.
8319 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8320 if (ArgIdx < NumParams) {
8321 // (C++ 13.3.2p3): for F to be a viable function, there shall
8322 // exist for each argument an implicit conversion sequence
8323 // (13.3.3.1) that converts that argument to the corresponding
8324 // parameter of F.
8325 QualType ParamType = Proto->getParamType(ArgIdx);
8326 Candidate.Conversions[ArgIdx + 1]
8327 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8328 /*SuppressUserConversions=*/false,
8329 /*InOverloadResolution=*/false,
8330 /*AllowObjCWritebackConversion=*/
8331 getLangOpts().ObjCAutoRefCount);
8332 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8333 Candidate.Viable = false;
8335 return;
8336 }
8337 } else {
8338 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8339 // argument for which there is no corresponding parameter is
8340 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8341 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8342 }
8343 }
8344
8345 if (Conversion->getTrailingRequiresClause()) {
8346 ConstraintSatisfaction Satisfaction;
8347 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8348 /*ForOverloadResolution*/ true) ||
8349 !Satisfaction.IsSatisfied) {
8350 Candidate.Viable = false;
8352 return;
8353 }
8354 }
8355
8356 if (EnableIfAttr *FailedAttr =
8357 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8358 Candidate.Viable = false;
8359 Candidate.FailureKind = ovl_fail_enable_if;
8360 Candidate.DeductionFailure.Data = FailedAttr;
8361 return;
8362 }
8363}
8364
8366 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8367 OverloadCandidateSet &CandidateSet,
8368 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8369 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8370 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8371 ArrayRef<Expr *> FunctionArgs = Args;
8372
8373 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8374 FunctionDecl *FD =
8375 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8376
8377 // Don't consider rewritten functions if we're not rewriting.
8378 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8379 continue;
8380
8381 assert(!isa<CXXMethodDecl>(FD) &&
8382 "unqualified operator lookup found a member function");
8383
8384 if (FunTmpl) {
8385 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8386 FunctionArgs, CandidateSet);
8387 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8388 AddTemplateOverloadCandidate(
8389 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8390 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8391 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8392 } else {
8393 if (ExplicitTemplateArgs)
8394 continue;
8395 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8396 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8397 AddOverloadCandidate(FD, F.getPair(),
8398 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8399 false, false, true, false, ADLCallKind::NotADL, {},
8401 }
8402 }
8403}
8404
8406 SourceLocation OpLoc,
8407 ArrayRef<Expr *> Args,
8408 OverloadCandidateSet &CandidateSet,
8411
8412 // C++ [over.match.oper]p3:
8413 // For a unary operator @ with an operand of a type whose
8414 // cv-unqualified version is T1, and for a binary operator @ with
8415 // a left operand of a type whose cv-unqualified version is T1 and
8416 // a right operand of a type whose cv-unqualified version is T2,
8417 // three sets of candidate functions, designated member
8418 // candidates, non-member candidates and built-in candidates, are
8419 // constructed as follows:
8420 QualType T1 = Args[0]->getType();
8421
8422 // -- If T1 is a complete class type or a class currently being
8423 // defined, the set of member candidates is the result of the
8424 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8425 // the set of member candidates is empty.
8426 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8427 // Complete the type if it can be completed.
8428 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8429 return;
8430 // If the type is neither complete nor being defined, bail out now.
8431 if (!T1Rec->getDecl()->getDefinition())
8432 return;
8433
8434 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8435 LookupQualifiedName(Operators, T1Rec->getDecl());
8436 Operators.suppressAccessDiagnostics();
8437
8438 for (LookupResult::iterator Oper = Operators.begin(),
8439 OperEnd = Operators.end();
8440 Oper != OperEnd; ++Oper) {
8441 if (Oper->getAsFunction() &&
8443 !CandidateSet.getRewriteInfo().shouldAddReversed(
8444 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8445 continue;
8446 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8447 Args[0]->Classify(Context), Args.slice(1),
8448 CandidateSet, /*SuppressUserConversion=*/false, PO);
8449 }
8450 }
8451}
8452
8454 OverloadCandidateSet& CandidateSet,
8455 bool IsAssignmentOperator,
8456 unsigned NumContextualBoolArguments) {
8457 // Overload resolution is always an unevaluated context.
8460
8461 // Add this candidate
8462 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8463 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8464 Candidate.Function = nullptr;
8465 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8466
8467 // Determine the implicit conversion sequences for each of the
8468 // arguments.
8469 Candidate.Viable = true;
8470 Candidate.ExplicitCallArguments = Args.size();
8471 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8472 // C++ [over.match.oper]p4:
8473 // For the built-in assignment operators, conversions of the
8474 // left operand are restricted as follows:
8475 // -- no temporaries are introduced to hold the left operand, and
8476 // -- no user-defined conversions are applied to the left
8477 // operand to achieve a type match with the left-most
8478 // parameter of a built-in candidate.
8479 //
8480 // We block these conversions by turning off user-defined
8481 // conversions, since that is the only way that initialization of
8482 // a reference to a non-class type can occur from something that
8483 // is not of the same type.
8484 if (ArgIdx < NumContextualBoolArguments) {
8485 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8486 "Contextual conversion to bool requires bool type");
8487 Candidate.Conversions[ArgIdx]
8488 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8489 } else {
8490 Candidate.Conversions[ArgIdx]
8491 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8492 ArgIdx == 0 && IsAssignmentOperator,
8493 /*InOverloadResolution=*/false,
8494 /*AllowObjCWritebackConversion=*/
8495 getLangOpts().ObjCAutoRefCount);
8496 }
8497 if (Candidate.Conversions[ArgIdx].isBad()) {
8498 Candidate.Viable = false;
8500 break;
8501 }
8502 }
8503}
8504
8505namespace {
8506
8507/// BuiltinCandidateTypeSet - A set of types that will be used for the
8508/// candidate operator functions for built-in operators (C++
8509/// [over.built]). The types are separated into pointer types and
8510/// enumeration types.
8511class BuiltinCandidateTypeSet {
8512 /// TypeSet - A set of types.
8513 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8514
8515 /// PointerTypes - The set of pointer types that will be used in the
8516 /// built-in candidates.
8517 TypeSet PointerTypes;
8518
8519 /// MemberPointerTypes - The set of member pointer types that will be
8520 /// used in the built-in candidates.
8521 TypeSet MemberPointerTypes;
8522
8523 /// EnumerationTypes - The set of enumeration types that will be
8524 /// used in the built-in candidates.
8525 TypeSet EnumerationTypes;
8526
8527 /// The set of vector types that will be used in the built-in
8528 /// candidates.
8529 TypeSet VectorTypes;
8530
8531 /// The set of matrix types that will be used in the built-in
8532 /// candidates.
8533 TypeSet MatrixTypes;
8534
8535 /// The set of _BitInt types that will be used in the built-in candidates.
8536 TypeSet BitIntTypes;
8537
8538 /// A flag indicating non-record types are viable candidates
8539 bool HasNonRecordTypes;
8540
8541 /// A flag indicating whether either arithmetic or enumeration types
8542 /// were present in the candidate set.
8543 bool HasArithmeticOrEnumeralTypes;
8544
8545 /// A flag indicating whether the nullptr type was present in the
8546 /// candidate set.
8547 bool HasNullPtrType;
8548
8549 /// Sema - The semantic analysis instance where we are building the
8550 /// candidate type set.
8551 Sema &SemaRef;
8552
8553 /// Context - The AST context in which we will build the type sets.
8554 ASTContext &Context;
8555
8556 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8557 const Qualifiers &VisibleQuals);
8558 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8559
8560public:
8561 /// iterator - Iterates through the types that are part of the set.
8562 typedef TypeSet::iterator iterator;
8563
8564 BuiltinCandidateTypeSet(Sema &SemaRef)
8565 : HasNonRecordTypes(false),
8566 HasArithmeticOrEnumeralTypes(false),
8567 HasNullPtrType(false),
8568 SemaRef(SemaRef),
8569 Context(SemaRef.Context) { }
8570
8571 void AddTypesConvertedFrom(QualType Ty,
8573 bool AllowUserConversions,
8574 bool AllowExplicitConversions,
8575 const Qualifiers &VisibleTypeConversionsQuals);
8576
8577 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8578 llvm::iterator_range<iterator> member_pointer_types() {
8579 return MemberPointerTypes;
8580 }
8581 llvm::iterator_range<iterator> enumeration_types() {
8582 return EnumerationTypes;
8583 }
8584 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8585 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8586 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8587
8588 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8589 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8590 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8591 bool hasNullPtrType() const { return HasNullPtrType; }
8592};
8593
8594} // end anonymous namespace
8595
8596/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8597/// the set of pointer types along with any more-qualified variants of
8598/// that type. For example, if @p Ty is "int const *", this routine
8599/// will add "int const *", "int const volatile *", "int const
8600/// restrict *", and "int const volatile restrict *" to the set of
8601/// pointer types. Returns true if the add of @p Ty itself succeeded,
8602/// false otherwise.
8603///
8604/// FIXME: what to do about extended qualifiers?
8605bool
8606BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8607 const Qualifiers &VisibleQuals) {
8608
8609 // Insert this type.
8610 if (!PointerTypes.insert(Ty))
8611 return false;
8612
8613 QualType PointeeTy;
8614 const PointerType *PointerTy = Ty->getAs<PointerType>();
8615 bool buildObjCPtr = false;
8616 if (!PointerTy) {
8618 PointeeTy = PTy->getPointeeType();
8619 buildObjCPtr = true;
8620 } else {
8621 PointeeTy = PointerTy->getPointeeType();
8622 }
8623
8624 // Don't add qualified variants of arrays. For one, they're not allowed
8625 // (the qualifier would sink to the element type), and for another, the
8626 // only overload situation where it matters is subscript or pointer +- int,
8627 // and those shouldn't have qualifier variants anyway.
8628 if (PointeeTy->isArrayType())
8629 return true;
8630
8631 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8632 bool hasVolatile = VisibleQuals.hasVolatile();
8633 bool hasRestrict = VisibleQuals.hasRestrict();
8634
8635 // Iterate through all strict supersets of BaseCVR.
8636 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8637 if ((CVR | BaseCVR) != CVR) continue;
8638 // Skip over volatile if no volatile found anywhere in the types.
8639 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8640
8641 // Skip over restrict if no restrict found anywhere in the types, or if
8642 // the type cannot be restrict-qualified.
8643 if ((CVR & Qualifiers::Restrict) &&
8644 (!hasRestrict ||
8645 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8646 continue;
8647
8648 // Build qualified pointee type.
8649 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8650
8651 // Build qualified pointer type.
8652 QualType QPointerTy;
8653 if (!buildObjCPtr)
8654 QPointerTy = Context.getPointerType(QPointeeTy);
8655 else
8656 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8657
8658 // Insert qualified pointer type.
8659 PointerTypes.insert(QPointerTy);
8660 }
8661
8662 return true;
8663}
8664
8665/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8666/// to the set of pointer types along with any more-qualified variants of
8667/// that type. For example, if @p Ty is "int const *", this routine
8668/// will add "int const *", "int const volatile *", "int const
8669/// restrict *", and "int const volatile restrict *" to the set of
8670/// pointer types. Returns true if the add of @p Ty itself succeeded,
8671/// false otherwise.
8672///
8673/// FIXME: what to do about extended qualifiers?
8674bool
8675BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8676 QualType Ty) {
8677 // Insert this type.
8678 if (!MemberPointerTypes.insert(Ty))
8679 return false;
8680
8681 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8682 assert(PointerTy && "type was not a member pointer type!");
8683
8684 QualType PointeeTy = PointerTy->getPointeeType();
8685 // Don't add qualified variants of arrays. For one, they're not allowed
8686 // (the qualifier would sink to the element type), and for another, the
8687 // only overload situation where it matters is subscript or pointer +- int,
8688 // and those shouldn't have qualifier variants anyway.
8689 if (PointeeTy->isArrayType())
8690 return true;
8691 const Type *ClassTy = PointerTy->getClass();
8692
8693 // Iterate through all strict supersets of the pointee type's CVR
8694 // qualifiers.
8695 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8696 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8697 if ((CVR | BaseCVR) != CVR) continue;
8698
8699 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8700 MemberPointerTypes.insert(
8701 Context.getMemberPointerType(QPointeeTy, ClassTy));
8702 }
8703
8704 return true;
8705}
8706
8707/// AddTypesConvertedFrom - Add each of the types to which the type @p
8708/// Ty can be implicit converted to the given set of @p Types. We're
8709/// primarily interested in pointer types and enumeration types. We also
8710/// take member pointer types, for the conditional operator.
8711/// AllowUserConversions is true if we should look at the conversion
8712/// functions of a class type, and AllowExplicitConversions if we
8713/// should also include the explicit conversion functions of a class
8714/// type.
8715void
8716BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8717 SourceLocation Loc,
8718 bool AllowUserConversions,
8719 bool AllowExplicitConversions,
8720 const Qualifiers &VisibleQuals) {
8721 // Only deal with canonical types.
8722 Ty = Context.getCanonicalType(Ty);
8723
8724 // Look through reference types; they aren't part of the type of an
8725 // expression for the purposes of conversions.
8726 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8727 Ty = RefTy->getPointeeType();
8728
8729 // If we're dealing with an array type, decay to the pointer.
8730 if (Ty->isArrayType())
8731 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8732
8733 // Otherwise, we don't care about qualifiers on the type.
8734 Ty = Ty.getLocalUnqualifiedType();
8735
8736 // Flag if we ever add a non-record type.
8737 const RecordType *TyRec = Ty->getAs<RecordType>();
8738 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8739
8740 // Flag if we encounter an arithmetic type.
8741 HasArithmeticOrEnumeralTypes =
8742 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8743
8744 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8745 PointerTypes.insert(Ty);
8746 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8747 // Insert our type, and its more-qualified variants, into the set
8748 // of types.
8749 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8750 return;
8751 } else if (Ty->isMemberPointerType()) {
8752 // Member pointers are far easier, since the pointee can't be converted.
8753 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8754 return;
8755 } else if (Ty->isEnumeralType()) {
8756 HasArithmeticOrEnumeralTypes = true;
8757 EnumerationTypes.insert(Ty);
8758 } else if (Ty->isBitIntType()) {
8759 HasArithmeticOrEnumeralTypes = true;
8760 BitIntTypes.insert(Ty);
8761 } else if (Ty->isVectorType()) {
8762 // We treat vector types as arithmetic types in many contexts as an
8763 // extension.
8764 HasArithmeticOrEnumeralTypes = true;
8765 VectorTypes.insert(Ty);
8766 } else if (Ty->isMatrixType()) {
8767 // Similar to vector types, we treat vector types as arithmetic types in
8768 // many contexts as an extension.
8769 HasArithmeticOrEnumeralTypes = true;
8770 MatrixTypes.insert(Ty);
8771 } else if (Ty->isNullPtrType()) {
8772 HasNullPtrType = true;
8773 } else if (AllowUserConversions && TyRec) {
8774 // No conversion functions in incomplete types.
8775 if (!SemaRef.isCompleteType(Loc, Ty))
8776 return;
8777
8778 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8779 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8780 if (isa<UsingShadowDecl>(D))
8781 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8782
8783 // Skip conversion function templates; they don't tell us anything
8784 // about which builtin types we can convert to.
8785 if (isa<FunctionTemplateDecl>(D))
8786 continue;
8787
8788 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8789 if (AllowExplicitConversions || !Conv->isExplicit()) {
8790 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8791 VisibleQuals);
8792 }
8793 }
8794 }
8795}
8796/// Helper function for adjusting address spaces for the pointer or reference
8797/// operands of builtin operators depending on the argument.
8799 Expr *Arg) {
8801}
8802
8803/// Helper function for AddBuiltinOperatorCandidates() that adds
8804/// the volatile- and non-volatile-qualified assignment operators for the
8805/// given type to the candidate set.
8807 QualType T,
8808 ArrayRef<Expr *> Args,
8809 OverloadCandidateSet &CandidateSet) {
8810 QualType ParamTypes[2];
8811
8812 // T& operator=(T&, T)
8813 ParamTypes[0] = S.Context.getLValueReferenceType(
8815 ParamTypes[1] = T;
8816 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8817 /*IsAssignmentOperator=*/true);
8818
8820 // volatile T& operator=(volatile T&, T)
8821 ParamTypes[0] = S.Context.getLValueReferenceType(
8823 Args[0]));
8824 ParamTypes[1] = T;
8825 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8826 /*IsAssignmentOperator=*/true);
8827 }
8828}
8829
8830/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8831/// if any, found in visible type conversion functions found in ArgExpr's type.
8832static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8833 Qualifiers VRQuals;
8834 const RecordType *TyRec;
8835 if (const MemberPointerType *RHSMPType =
8836 ArgExpr->getType()->getAs<MemberPointerType>())
8837 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8838 else
8839 TyRec = ArgExpr->getType()->getAs<RecordType>();
8840 if (!TyRec) {
8841 // Just to be safe, assume the worst case.
8842 VRQuals.addVolatile();
8843 VRQuals.addRestrict();
8844 return VRQuals;
8845 }
8846
8847 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8848 if (!ClassDecl->hasDefinition())
8849 return VRQuals;
8850
8851 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8852 if (isa<UsingShadowDecl>(D))
8853 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8854 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8855 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8856 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8857 CanTy = ResTypeRef->getPointeeType();
8858 // Need to go down the pointer/mempointer chain and add qualifiers
8859 // as see them.
8860 bool done = false;
8861 while (!done) {
8862 if (CanTy.isRestrictQualified())
8863 VRQuals.addRestrict();
8864 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8865 CanTy = ResTypePtr->getPointeeType();
8866 else if (const MemberPointerType *ResTypeMPtr =
8867 CanTy->getAs<MemberPointerType>())
8868 CanTy = ResTypeMPtr->getPointeeType();
8869 else
8870 done = true;
8871 if (CanTy.isVolatileQualified())
8872 VRQuals.addVolatile();
8873 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8874 return VRQuals;
8875 }
8876 }
8877 }
8878 return VRQuals;
8879}
8880
8881// Note: We're currently only handling qualifiers that are meaningful for the
8882// LHS of compound assignment overloading.
8884 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8885 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8886 // _Atomic
8887 if (Available.hasAtomic()) {
8888 Available.removeAtomic();
8889 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8890 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8891 return;
8892 }
8893
8894 // volatile
8895 if (Available.hasVolatile()) {
8896 Available.removeVolatile();
8897 assert(!Applied.hasVolatile());
8898 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8899 Callback);
8900 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8901 return;
8902 }
8903
8904 Callback(Applied);
8905}
8906
8908 QualifiersAndAtomic Quals,
8909 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8911 Callback);
8912}
8913
8915 QualifiersAndAtomic Quals,
8916 Sema &S) {
8917 if (Quals.hasAtomic())
8919 if (Quals.hasVolatile())
8922}
8923
8924namespace {
8925
8926/// Helper class to manage the addition of builtin operator overload
8927/// candidates. It provides shared state and utility methods used throughout
8928/// the process, as well as a helper method to add each group of builtin
8929/// operator overloads from the standard to a candidate set.
8930class BuiltinOperatorOverloadBuilder {
8931 // Common instance state available to all overload candidate addition methods.
8932 Sema &S;
8933 ArrayRef<Expr *> Args;
8934 QualifiersAndAtomic VisibleTypeConversionsQuals;
8935 bool HasArithmeticOrEnumeralCandidateType;
8937 OverloadCandidateSet &CandidateSet;
8938
8939 static constexpr int ArithmeticTypesCap = 26;
8941
8942 // Define some indices used to iterate over the arithmetic types in
8943 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8944 // types are that preserved by promotion (C++ [over.built]p2).
8945 unsigned FirstIntegralType,
8946 LastIntegralType;
8947 unsigned FirstPromotedIntegralType,
8948 LastPromotedIntegralType;
8949 unsigned FirstPromotedArithmeticType,
8950 LastPromotedArithmeticType;
8951 unsigned NumArithmeticTypes;
8952
8953 void InitArithmeticTypes() {
8954 // Start of promoted types.
8955 FirstPromotedArithmeticType = 0;
8956 ArithmeticTypes.push_back(S.Context.FloatTy);
8957 ArithmeticTypes.push_back(S.Context.DoubleTy);
8958 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8960 ArithmeticTypes.push_back(S.Context.Float128Ty);
8962 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8963
8964 // Start of integral types.
8965 FirstIntegralType = ArithmeticTypes.size();
8966 FirstPromotedIntegralType = ArithmeticTypes.size();
8967 ArithmeticTypes.push_back(S.Context.IntTy);
8968 ArithmeticTypes.push_back(S.Context.LongTy);
8969 ArithmeticTypes.push_back(S.Context.LongLongTy);
8973 ArithmeticTypes.push_back(S.Context.Int128Ty);
8974 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8975 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8976 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8980 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8981
8982 /// We add candidates for the unique, unqualified _BitInt types present in
8983 /// the candidate type set. The candidate set already handled ensuring the
8984 /// type is unqualified and canonical, but because we're adding from N
8985 /// different sets, we need to do some extra work to unique things. Insert
8986 /// the candidates into a unique set, then move from that set into the list
8987 /// of arithmetic types.
8988 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8989 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8990 BuiltinCandidateTypeSet &Candidate) {
8991 for (QualType BitTy : Candidate.bitint_types())
8992 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8993 });
8994 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8995 LastPromotedIntegralType = ArithmeticTypes.size();
8996 LastPromotedArithmeticType = ArithmeticTypes.size();
8997 // End of promoted types.
8998
8999 ArithmeticTypes.push_back(S.Context.BoolTy);
9000 ArithmeticTypes.push_back(S.Context.CharTy);
9001 ArithmeticTypes.push_back(S.Context.WCharTy);
9002 if (S.Context.getLangOpts().Char8)
9003 ArithmeticTypes.push_back(S.Context.Char8Ty);
9004 ArithmeticTypes.push_back(S.Context.Char16Ty);
9005 ArithmeticTypes.push_back(S.Context.Char32Ty);
9006 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9007 ArithmeticTypes.push_back(S.Context.ShortTy);
9008 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9009 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9010 LastIntegralType = ArithmeticTypes.size();
9011 NumArithmeticTypes = ArithmeticTypes.size();
9012 // End of integral types.
9013 // FIXME: What about complex? What about half?
9014
9015 // We don't know for sure how many bit-precise candidates were involved, so
9016 // we subtract those from the total when testing whether we're under the
9017 // cap or not.
9018 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9019 ArithmeticTypesCap &&
9020 "Enough inline storage for all arithmetic types.");
9021 }
9022
9023 /// Helper method to factor out the common pattern of adding overloads
9024 /// for '++' and '--' builtin operators.
9025 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9026 bool HasVolatile,
9027 bool HasRestrict) {
9028 QualType ParamTypes[2] = {
9029 S.Context.getLValueReferenceType(CandidateTy),
9030 S.Context.IntTy
9031 };
9032
9033 // Non-volatile version.
9034 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9035
9036 // Use a heuristic to reduce number of builtin candidates in the set:
9037 // add volatile version only if there are conversions to a volatile type.
9038 if (HasVolatile) {
9039 ParamTypes[0] =
9041 S.Context.getVolatileType(CandidateTy));
9042 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9043 }
9044
9045 // Add restrict version only if there are conversions to a restrict type
9046 // and our candidate type is a non-restrict-qualified pointer.
9047 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9048 !CandidateTy.isRestrictQualified()) {
9049 ParamTypes[0]
9052 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9053
9054 if (HasVolatile) {
9055 ParamTypes[0]
9057 S.Context.getCVRQualifiedType(CandidateTy,
9060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9061 }
9062 }
9063
9064 }
9065
9066 /// Helper to add an overload candidate for a binary builtin with types \p L
9067 /// and \p R.
9068 void AddCandidate(QualType L, QualType R) {
9069 QualType LandR[2] = {L, R};
9070 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9071 }
9072
9073public:
9074 BuiltinOperatorOverloadBuilder(
9075 Sema &S, ArrayRef<Expr *> Args,
9076 QualifiersAndAtomic VisibleTypeConversionsQuals,
9077 bool HasArithmeticOrEnumeralCandidateType,
9079 OverloadCandidateSet &CandidateSet)
9080 : S(S), Args(Args),
9081 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9082 HasArithmeticOrEnumeralCandidateType(
9083 HasArithmeticOrEnumeralCandidateType),
9084 CandidateTypes(CandidateTypes),
9085 CandidateSet(CandidateSet) {
9086
9087 InitArithmeticTypes();
9088 }
9089
9090 // Increment is deprecated for bool since C++17.
9091 //
9092 // C++ [over.built]p3:
9093 //
9094 // For every pair (T, VQ), where T is an arithmetic type other
9095 // than bool, and VQ is either volatile or empty, there exist
9096 // candidate operator functions of the form
9097 //
9098 // VQ T& operator++(VQ T&);
9099 // T operator++(VQ T&, int);
9100 //
9101 // C++ [over.built]p4:
9102 //
9103 // For every pair (T, VQ), where T is an arithmetic type other
9104 // than bool, and VQ is either volatile or empty, there exist
9105 // candidate operator functions of the form
9106 //
9107 // VQ T& operator--(VQ T&);
9108 // T operator--(VQ T&, int);
9109 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9110 if (!HasArithmeticOrEnumeralCandidateType)
9111 return;
9112
9113 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9114 const auto TypeOfT = ArithmeticTypes[Arith];
9115 if (TypeOfT == S.Context.BoolTy) {
9116 if (Op == OO_MinusMinus)
9117 continue;
9118 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9119 continue;
9120 }
9121 addPlusPlusMinusMinusStyleOverloads(
9122 TypeOfT,
9123 VisibleTypeConversionsQuals.hasVolatile(),
9124 VisibleTypeConversionsQuals.hasRestrict());
9125 }
9126 }
9127
9128 // C++ [over.built]p5:
9129 //
9130 // For every pair (T, VQ), where T is a cv-qualified or
9131 // cv-unqualified object type, and VQ is either volatile or
9132 // empty, there exist candidate operator functions of the form
9133 //
9134 // T*VQ& operator++(T*VQ&);
9135 // T*VQ& operator--(T*VQ&);
9136 // T* operator++(T*VQ&, int);
9137 // T* operator--(T*VQ&, int);
9138 void addPlusPlusMinusMinusPointerOverloads() {
9139 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9140 // Skip pointer types that aren't pointers to object types.
9141 if (!PtrTy->getPointeeType()->isObjectType())
9142 continue;
9143
9144 addPlusPlusMinusMinusStyleOverloads(
9145 PtrTy,
9146 (!PtrTy.isVolatileQualified() &&
9147 VisibleTypeConversionsQuals.hasVolatile()),
9148 (!PtrTy.isRestrictQualified() &&
9149 VisibleTypeConversionsQuals.hasRestrict()));
9150 }
9151 }
9152
9153 // C++ [over.built]p6:
9154 // For every cv-qualified or cv-unqualified object type T, there
9155 // exist candidate operator functions of the form
9156 //
9157 // T& operator*(T*);
9158 //
9159 // C++ [over.built]p7:
9160 // For every function type T that does not have cv-qualifiers or a
9161 // ref-qualifier, there exist candidate operator functions of the form
9162 // T& operator*(T*);
9163 void addUnaryStarPointerOverloads() {
9164 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9165 QualType PointeeTy = ParamTy->getPointeeType();
9166 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9167 continue;
9168
9169 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9170 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9171 continue;
9172
9173 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9174 }
9175 }
9176
9177 // C++ [over.built]p9:
9178 // For every promoted arithmetic type T, there exist candidate
9179 // operator functions of the form
9180 //
9181 // T operator+(T);
9182 // T operator-(T);
9183 void addUnaryPlusOrMinusArithmeticOverloads() {
9184 if (!HasArithmeticOrEnumeralCandidateType)
9185 return;
9186
9187 for (unsigned Arith = FirstPromotedArithmeticType;
9188 Arith < LastPromotedArithmeticType; ++Arith) {
9189 QualType ArithTy = ArithmeticTypes[Arith];
9190 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9191 }
9192
9193 // Extension: We also add these operators for vector types.
9194 for (QualType VecTy : CandidateTypes[0].vector_types())
9195 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9196 }
9197
9198 // C++ [over.built]p8:
9199 // For every type T, there exist candidate operator functions of
9200 // the form
9201 //
9202 // T* operator+(T*);
9203 void addUnaryPlusPointerOverloads() {
9204 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9205 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9206 }
9207
9208 // C++ [over.built]p10:
9209 // For every promoted integral type T, there exist candidate
9210 // operator functions of the form
9211 //
9212 // T operator~(T);
9213 void addUnaryTildePromotedIntegralOverloads() {
9214 if (!HasArithmeticOrEnumeralCandidateType)
9215 return;
9216
9217 for (unsigned Int = FirstPromotedIntegralType;
9218 Int < LastPromotedIntegralType; ++Int) {
9219 QualType IntTy = ArithmeticTypes[Int];
9220 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9221 }
9222
9223 // Extension: We also add this operator for vector types.
9224 for (QualType VecTy : CandidateTypes[0].vector_types())
9225 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9226 }
9227
9228 // C++ [over.match.oper]p16:
9229 // For every pointer to member type T or type std::nullptr_t, there
9230 // exist candidate operator functions of the form
9231 //
9232 // bool operator==(T,T);
9233 // bool operator!=(T,T);
9234 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9235 /// Set of (canonical) types that we've already handled.
9237
9238 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9239 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9240 // Don't add the same builtin candidate twice.
9241 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9242 continue;
9243
9244 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9245 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9246 }
9247
9248 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9250 if (AddedTypes.insert(NullPtrTy).second) {
9251 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9252 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9253 }
9254 }
9255 }
9256 }
9257
9258 // C++ [over.built]p15:
9259 //
9260 // For every T, where T is an enumeration type or a pointer type,
9261 // there exist candidate operator functions of the form
9262 //
9263 // bool operator<(T, T);
9264 // bool operator>(T, T);
9265 // bool operator<=(T, T);
9266 // bool operator>=(T, T);
9267 // bool operator==(T, T);
9268 // bool operator!=(T, T);
9269 // R operator<=>(T, T)
9270 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9271 // C++ [over.match.oper]p3:
9272 // [...]the built-in candidates include all of the candidate operator
9273 // functions defined in 13.6 that, compared to the given operator, [...]
9274 // do not have the same parameter-type-list as any non-template non-member
9275 // candidate.
9276 //
9277 // Note that in practice, this only affects enumeration types because there
9278 // aren't any built-in candidates of record type, and a user-defined operator
9279 // must have an operand of record or enumeration type. Also, the only other
9280 // overloaded operator with enumeration arguments, operator=,
9281 // cannot be overloaded for enumeration types, so this is the only place
9282 // where we must suppress candidates like this.
9283 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9284 UserDefinedBinaryOperators;
9285
9286 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9287 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9288 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9289 CEnd = CandidateSet.end();
9290 C != CEnd; ++C) {
9291 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9292 continue;
9293
9294 if (C->Function->isFunctionTemplateSpecialization())
9295 continue;
9296
9297 // We interpret "same parameter-type-list" as applying to the
9298 // "synthesized candidate, with the order of the two parameters
9299 // reversed", not to the original function.
9300 bool Reversed = C->isReversed();
9301 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9302 ->getType()
9303 .getUnqualifiedType();
9304 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9305 ->getType()
9306 .getUnqualifiedType();
9307
9308 // Skip if either parameter isn't of enumeral type.
9309 if (!FirstParamType->isEnumeralType() ||
9310 !SecondParamType->isEnumeralType())
9311 continue;
9312
9313 // Add this operator to the set of known user-defined operators.
9314 UserDefinedBinaryOperators.insert(
9315 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9316 S.Context.getCanonicalType(SecondParamType)));
9317 }
9318 }
9319 }
9320
9321 /// Set of (canonical) types that we've already handled.
9323
9324 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9325 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9326 // Don't add the same builtin candidate twice.
9327 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9328 continue;
9329 if (IsSpaceship && PtrTy->isFunctionPointerType())
9330 continue;
9331
9332 QualType ParamTypes[2] = {PtrTy, PtrTy};
9333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9334 }
9335 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9336 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9337
9338 // Don't add the same builtin candidate twice, or if a user defined
9339 // candidate exists.
9340 if (!AddedTypes.insert(CanonType).second ||
9341 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9342 CanonType)))
9343 continue;
9344 QualType ParamTypes[2] = {EnumTy, EnumTy};
9345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9346 }
9347 }
9348 }
9349
9350 // C++ [over.built]p13:
9351 //
9352 // For every cv-qualified or cv-unqualified object type T
9353 // there exist candidate operator functions of the form
9354 //
9355 // T* operator+(T*, ptrdiff_t);
9356 // T& operator[](T*, ptrdiff_t); [BELOW]
9357 // T* operator-(T*, ptrdiff_t);
9358 // T* operator+(ptrdiff_t, T*);
9359 // T& operator[](ptrdiff_t, T*); [BELOW]
9360 //
9361 // C++ [over.built]p14:
9362 //
9363 // For every T, where T is a pointer to object type, there
9364 // exist candidate operator functions of the form
9365 //
9366 // ptrdiff_t operator-(T, T);
9367 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9368 /// Set of (canonical) types that we've already handled.
9370
9371 for (int Arg = 0; Arg < 2; ++Arg) {
9372 QualType AsymmetricParamTypes[2] = {
9375 };
9376 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9377 QualType PointeeTy = PtrTy->getPointeeType();
9378 if (!PointeeTy->isObjectType())
9379 continue;
9380
9381 AsymmetricParamTypes[Arg] = PtrTy;
9382 if (Arg == 0 || Op == OO_Plus) {
9383 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9384 // T* operator+(ptrdiff_t, T*);
9385 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9386 }
9387 if (Op == OO_Minus) {
9388 // ptrdiff_t operator-(T, T);
9389 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9390 continue;
9391
9392 QualType ParamTypes[2] = {PtrTy, PtrTy};
9393 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9394 }
9395 }
9396 }
9397 }
9398
9399 // C++ [over.built]p12:
9400 //
9401 // For every pair of promoted arithmetic types L and R, there
9402 // exist candidate operator functions of the form
9403 //
9404 // LR operator*(L, R);
9405 // LR operator/(L, R);
9406 // LR operator+(L, R);
9407 // LR operator-(L, R);
9408 // bool operator<(L, R);
9409 // bool operator>(L, R);
9410 // bool operator<=(L, R);
9411 // bool operator>=(L, R);
9412 // bool operator==(L, R);
9413 // bool operator!=(L, R);
9414 //
9415 // where LR is the result of the usual arithmetic conversions
9416 // between types L and R.
9417 //
9418 // C++ [over.built]p24:
9419 //
9420 // For every pair of promoted arithmetic types L and R, there exist
9421 // candidate operator functions of the form
9422 //
9423 // LR operator?(bool, L, R);
9424 //
9425 // where LR is the result of the usual arithmetic conversions
9426 // between types L and R.
9427 // Our candidates ignore the first parameter.
9428 void addGenericBinaryArithmeticOverloads() {
9429 if (!HasArithmeticOrEnumeralCandidateType)
9430 return;
9431
9432 for (unsigned Left = FirstPromotedArithmeticType;
9433 Left < LastPromotedArithmeticType; ++Left) {
9434 for (unsigned Right = FirstPromotedArithmeticType;
9435 Right < LastPromotedArithmeticType; ++Right) {
9436 QualType LandR[2] = { ArithmeticTypes[Left],
9437 ArithmeticTypes[Right] };
9438 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9439 }
9440 }
9441
9442 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9443 // conditional operator for vector types.
9444 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9445 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9446 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9447 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9448 }
9449 }
9450
9451 /// Add binary operator overloads for each candidate matrix type M1, M2:
9452 /// * (M1, M1) -> M1
9453 /// * (M1, M1.getElementType()) -> M1
9454 /// * (M2.getElementType(), M2) -> M2
9455 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9456 void addMatrixBinaryArithmeticOverloads() {
9457 if (!HasArithmeticOrEnumeralCandidateType)
9458 return;
9459
9460 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9461 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9462 AddCandidate(M1, M1);
9463 }
9464
9465 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9466 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9467 if (!CandidateTypes[0].containsMatrixType(M2))
9468 AddCandidate(M2, M2);
9469 }
9470 }
9471
9472 // C++2a [over.built]p14:
9473 //
9474 // For every integral type T there exists a candidate operator function
9475 // of the form
9476 //
9477 // std::strong_ordering operator<=>(T, T)
9478 //
9479 // C++2a [over.built]p15:
9480 //
9481 // For every pair of floating-point types L and R, there exists a candidate
9482 // operator function of the form
9483 //
9484 // std::partial_ordering operator<=>(L, R);
9485 //
9486 // FIXME: The current specification for integral types doesn't play nice with
9487 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9488 // comparisons. Under the current spec this can lead to ambiguity during
9489 // overload resolution. For example:
9490 //
9491 // enum A : int {a};
9492 // auto x = (a <=> (long)42);
9493 //
9494 // error: call is ambiguous for arguments 'A' and 'long'.
9495 // note: candidate operator<=>(int, int)
9496 // note: candidate operator<=>(long, long)
9497 //
9498 // To avoid this error, this function deviates from the specification and adds
9499 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9500 // arithmetic types (the same as the generic relational overloads).
9501 //
9502 // For now this function acts as a placeholder.
9503 void addThreeWayArithmeticOverloads() {
9504 addGenericBinaryArithmeticOverloads();
9505 }
9506
9507 // C++ [over.built]p17:
9508 //
9509 // For every pair of promoted integral types L and R, there
9510 // exist candidate operator functions of the form
9511 //
9512 // LR operator%(L, R);
9513 // LR operator&(L, R);
9514 // LR operator^(L, R);
9515 // LR operator|(L, R);
9516 // L operator<<(L, R);
9517 // L operator>>(L, R);
9518 //
9519 // where LR is the result of the usual arithmetic conversions
9520 // between types L and R.
9521 void addBinaryBitwiseArithmeticOverloads() {
9522 if (!HasArithmeticOrEnumeralCandidateType)
9523 return;
9524
9525 for (unsigned Left = FirstPromotedIntegralType;
9526 Left < LastPromotedIntegralType; ++Left) {
9527 for (unsigned Right = FirstPromotedIntegralType;
9528 Right < LastPromotedIntegralType; ++Right) {
9529 QualType LandR[2] = { ArithmeticTypes[Left],
9530 ArithmeticTypes[Right] };
9531 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9532 }
9533 }
9534 }
9535
9536 // C++ [over.built]p20:
9537 //
9538 // For every pair (T, VQ), where T is an enumeration or
9539 // pointer to member type and VQ is either volatile or
9540 // empty, there exist candidate operator functions of the form
9541 //
9542 // VQ T& operator=(VQ T&, T);
9543 void addAssignmentMemberPointerOrEnumeralOverloads() {
9544 /// Set of (canonical) types that we've already handled.
9546
9547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9548 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9549 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9550 continue;
9551
9552 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9553 }
9554
9555 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9556 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9557 continue;
9558
9559 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9560 }
9561 }
9562 }
9563
9564 // C++ [over.built]p19:
9565 //
9566 // For every pair (T, VQ), where T is any type and VQ is either
9567 // volatile or empty, there exist candidate operator functions
9568 // of the form
9569 //
9570 // T*VQ& operator=(T*VQ&, T*);
9571 //
9572 // C++ [over.built]p21:
9573 //
9574 // For every pair (T, VQ), where T is a cv-qualified or
9575 // cv-unqualified object type and VQ is either volatile or
9576 // empty, there exist candidate operator functions of the form
9577 //
9578 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9579 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9580 void addAssignmentPointerOverloads(bool isEqualOp) {
9581 /// Set of (canonical) types that we've already handled.
9583
9584 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9585 // If this is operator=, keep track of the builtin candidates we added.
9586 if (isEqualOp)
9587 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9588 else if (!PtrTy->getPointeeType()->isObjectType())
9589 continue;
9590
9591 // non-volatile version
9592 QualType ParamTypes[2] = {
9594 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9595 };
9596 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9597 /*IsAssignmentOperator=*/ isEqualOp);
9598
9599 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9600 VisibleTypeConversionsQuals.hasVolatile();
9601 if (NeedVolatile) {
9602 // volatile version
9603 ParamTypes[0] =
9605 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9606 /*IsAssignmentOperator=*/isEqualOp);
9607 }
9608
9609 if (!PtrTy.isRestrictQualified() &&
9610 VisibleTypeConversionsQuals.hasRestrict()) {
9611 // restrict version
9612 ParamTypes[0] =
9614 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9615 /*IsAssignmentOperator=*/isEqualOp);
9616
9617 if (NeedVolatile) {
9618 // volatile restrict version
9619 ParamTypes[0] =
9622 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9623 /*IsAssignmentOperator=*/isEqualOp);
9624 }
9625 }
9626 }
9627
9628 if (isEqualOp) {
9629 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9630 // Make sure we don't add the same candidate twice.
9631 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9632 continue;
9633
9634 QualType ParamTypes[2] = {
9636 PtrTy,
9637 };
9638
9639 // non-volatile version
9640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9641 /*IsAssignmentOperator=*/true);
9642
9643 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9644 VisibleTypeConversionsQuals.hasVolatile();
9645 if (NeedVolatile) {
9646 // volatile version
9647 ParamTypes[0] = S.Context.getLValueReferenceType(
9648 S.Context.getVolatileType(PtrTy));
9649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9650 /*IsAssignmentOperator=*/true);
9651 }
9652
9653 if (!PtrTy.isRestrictQualified() &&
9654 VisibleTypeConversionsQuals.hasRestrict()) {
9655 // restrict version
9656 ParamTypes[0] = S.Context.getLValueReferenceType(
9657 S.Context.getRestrictType(PtrTy));
9658 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9659 /*IsAssignmentOperator=*/true);
9660
9661 if (NeedVolatile) {
9662 // volatile restrict version
9663 ParamTypes[0] =
9666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9667 /*IsAssignmentOperator=*/true);
9668 }
9669 }
9670 }
9671 }
9672 }
9673
9674 // C++ [over.built]p18:
9675 //
9676 // For every triple (L, VQ, R), where L is an arithmetic type,
9677 // VQ is either volatile or empty, and R is a promoted
9678 // arithmetic type, there exist candidate operator functions of
9679 // the form
9680 //
9681 // VQ L& operator=(VQ L&, R);
9682 // VQ L& operator*=(VQ L&, R);
9683 // VQ L& operator/=(VQ L&, R);
9684 // VQ L& operator+=(VQ L&, R);
9685 // VQ L& operator-=(VQ L&, R);
9686 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9687 if (!HasArithmeticOrEnumeralCandidateType)
9688 return;
9689
9690 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9691 for (unsigned Right = FirstPromotedArithmeticType;
9692 Right < LastPromotedArithmeticType; ++Right) {
9693 QualType ParamTypes[2];
9694 ParamTypes[1] = ArithmeticTypes[Right];
9696 S, ArithmeticTypes[Left], Args[0]);
9697
9699 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9700 ParamTypes[0] =
9701 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9702 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9703 /*IsAssignmentOperator=*/isEqualOp);
9704 });
9705 }
9706 }
9707
9708 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9709 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9710 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9711 QualType ParamTypes[2];
9712 ParamTypes[1] = Vec2Ty;
9713 // Add this built-in operator as a candidate (VQ is empty).
9714 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9715 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9716 /*IsAssignmentOperator=*/isEqualOp);
9717
9718 // Add this built-in operator as a candidate (VQ is 'volatile').
9719 if (VisibleTypeConversionsQuals.hasVolatile()) {
9720 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9721 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9722 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9723 /*IsAssignmentOperator=*/isEqualOp);
9724 }
9725 }
9726 }
9727
9728 // C++ [over.built]p22:
9729 //
9730 // For every triple (L, VQ, R), where L is an integral type, VQ
9731 // is either volatile or empty, and R is a promoted integral
9732 // type, there exist candidate operator functions of the form
9733 //
9734 // VQ L& operator%=(VQ L&, R);
9735 // VQ L& operator<<=(VQ L&, R);
9736 // VQ L& operator>>=(VQ L&, R);
9737 // VQ L& operator&=(VQ L&, R);
9738 // VQ L& operator^=(VQ L&, R);
9739 // VQ L& operator|=(VQ L&, R);
9740 void addAssignmentIntegralOverloads() {
9741 if (!HasArithmeticOrEnumeralCandidateType)
9742 return;
9743
9744 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9745 for (unsigned Right = FirstPromotedIntegralType;
9746 Right < LastPromotedIntegralType; ++Right) {
9747 QualType ParamTypes[2];
9748 ParamTypes[1] = ArithmeticTypes[Right];
9750 S, ArithmeticTypes[Left], Args[0]);
9751
9753 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9754 ParamTypes[0] =
9755 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9756 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9757 });
9758 }
9759 }
9760 }
9761
9762 // C++ [over.operator]p23:
9763 //
9764 // There also exist candidate operator functions of the form
9765 //
9766 // bool operator!(bool);
9767 // bool operator&&(bool, bool);
9768 // bool operator||(bool, bool);
9769 void addExclaimOverload() {
9770 QualType ParamTy = S.Context.BoolTy;
9771 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9772 /*IsAssignmentOperator=*/false,
9773 /*NumContextualBoolArguments=*/1);
9774 }
9775 void addAmpAmpOrPipePipeOverload() {
9776 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9777 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9778 /*IsAssignmentOperator=*/false,
9779 /*NumContextualBoolArguments=*/2);
9780 }
9781
9782 // C++ [over.built]p13:
9783 //
9784 // For every cv-qualified or cv-unqualified object type T there
9785 // exist candidate operator functions of the form
9786 //
9787 // T* operator+(T*, ptrdiff_t); [ABOVE]
9788 // T& operator[](T*, ptrdiff_t);
9789 // T* operator-(T*, ptrdiff_t); [ABOVE]
9790 // T* operator+(ptrdiff_t, T*); [ABOVE]
9791 // T& operator[](ptrdiff_t, T*);
9792 void addSubscriptOverloads() {
9793 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9794 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9795 QualType PointeeType = PtrTy->getPointeeType();
9796 if (!PointeeType->isObjectType())
9797 continue;
9798
9799 // T& operator[](T*, ptrdiff_t)
9800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9801 }
9802
9803 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9804 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9805 QualType PointeeType = PtrTy->getPointeeType();
9806 if (!PointeeType->isObjectType())
9807 continue;
9808
9809 // T& operator[](ptrdiff_t, T*)
9810 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9811 }
9812 }
9813
9814 // C++ [over.built]p11:
9815 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9816 // C1 is the same type as C2 or is a derived class of C2, T is an object
9817 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9818 // there exist candidate operator functions of the form
9819 //
9820 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9821 //
9822 // where CV12 is the union of CV1 and CV2.
9823 void addArrowStarOverloads() {
9824 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9825 QualType C1Ty = PtrTy;
9826 QualType C1;
9828 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9829 if (!isa<RecordType>(C1))
9830 continue;
9831 // heuristic to reduce number of builtin candidates in the set.
9832 // Add volatile/restrict version only if there are conversions to a
9833 // volatile/restrict type.
9834 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9835 continue;
9836 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9837 continue;
9838 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9839 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9840 QualType C2 = QualType(mptr->getClass(), 0);
9841 C2 = C2.getUnqualifiedType();
9842 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9843 break;
9844 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9845 // build CV12 T&
9846 QualType T = mptr->getPointeeType();
9847 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9848 T.isVolatileQualified())
9849 continue;
9850 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9851 T.isRestrictQualified())
9852 continue;
9853 T = Q1.apply(S.Context, T);
9854 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9855 }
9856 }
9857 }
9858
9859 // Note that we don't consider the first argument, since it has been
9860 // contextually converted to bool long ago. The candidates below are
9861 // therefore added as binary.
9862 //
9863 // C++ [over.built]p25:
9864 // For every type T, where T is a pointer, pointer-to-member, or scoped
9865 // enumeration type, there exist candidate operator functions of the form
9866 //
9867 // T operator?(bool, T, T);
9868 //
9869 void addConditionalOperatorOverloads() {
9870 /// Set of (canonical) types that we've already handled.
9872
9873 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9874 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9875 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9876 continue;
9877
9878 QualType ParamTypes[2] = {PtrTy, PtrTy};
9879 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9880 }
9881
9882 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9883 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9884 continue;
9885
9886 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9887 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9888 }
9889
9890 if (S.getLangOpts().CPlusPlus11) {
9891 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9892 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9893 continue;
9894
9895 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9896 continue;
9897
9898 QualType ParamTypes[2] = {EnumTy, EnumTy};
9899 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9900 }
9901 }
9902 }
9903 }
9904};
9905
9906} // end anonymous namespace
9907
9909 SourceLocation OpLoc,
9910 ArrayRef<Expr *> Args,
9911 OverloadCandidateSet &CandidateSet) {
9912 // Find all of the types that the arguments can convert to, but only
9913 // if the operator we're looking at has built-in operator candidates
9914 // that make use of these types. Also record whether we encounter non-record
9915 // candidate types or either arithmetic or enumeral candidate types.
9916 QualifiersAndAtomic VisibleTypeConversionsQuals;
9917 VisibleTypeConversionsQuals.addConst();
9918 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9919 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9920 if (Args[ArgIdx]->getType()->isAtomicType())
9921 VisibleTypeConversionsQuals.addAtomic();
9922 }
9923
9924 bool HasNonRecordCandidateType = false;
9925 bool HasArithmeticOrEnumeralCandidateType = false;
9927 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9928 CandidateTypes.emplace_back(*this);
9929 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9930 OpLoc,
9931 true,
9932 (Op == OO_Exclaim ||
9933 Op == OO_AmpAmp ||
9934 Op == OO_PipePipe),
9935 VisibleTypeConversionsQuals);
9936 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9937 CandidateTypes[ArgIdx].hasNonRecordTypes();
9938 HasArithmeticOrEnumeralCandidateType =
9939 HasArithmeticOrEnumeralCandidateType ||
9940 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9941 }
9942
9943 // Exit early when no non-record types have been added to the candidate set
9944 // for any of the arguments to the operator.
9945 //
9946 // We can't exit early for !, ||, or &&, since there we have always have
9947 // 'bool' overloads.
9948 if (!HasNonRecordCandidateType &&
9949 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9950 return;
9951
9952 // Setup an object to manage the common state for building overloads.
9953 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9954 VisibleTypeConversionsQuals,
9955 HasArithmeticOrEnumeralCandidateType,
9956 CandidateTypes, CandidateSet);
9957
9958 // Dispatch over the operation to add in only those overloads which apply.
9959 switch (Op) {
9960 case OO_None:
9962 llvm_unreachable("Expected an overloaded operator");
9963
9964 case OO_New:
9965 case OO_Delete:
9966 case OO_Array_New:
9967 case OO_Array_Delete:
9968 case OO_Call:
9969 llvm_unreachable(
9970 "Special operators don't use AddBuiltinOperatorCandidates");
9971
9972 case OO_Comma:
9973 case OO_Arrow:
9974 case OO_Coawait:
9975 // C++ [over.match.oper]p3:
9976 // -- For the operator ',', the unary operator '&', the
9977 // operator '->', or the operator 'co_await', the
9978 // built-in candidates set is empty.
9979 break;
9980
9981 case OO_Plus: // '+' is either unary or binary
9982 if (Args.size() == 1)
9983 OpBuilder.addUnaryPlusPointerOverloads();
9984 [[fallthrough]];
9985
9986 case OO_Minus: // '-' is either unary or binary
9987 if (Args.size() == 1) {
9988 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9989 } else {
9990 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9991 OpBuilder.addGenericBinaryArithmeticOverloads();
9992 OpBuilder.addMatrixBinaryArithmeticOverloads();
9993 }
9994 break;
9995
9996 case OO_Star: // '*' is either unary or binary
9997 if (Args.size() == 1)
9998 OpBuilder.addUnaryStarPointerOverloads();
9999 else {
10000 OpBuilder.addGenericBinaryArithmeticOverloads();
10001 OpBuilder.addMatrixBinaryArithmeticOverloads();
10002 }
10003 break;
10004
10005 case OO_Slash:
10006 OpBuilder.addGenericBinaryArithmeticOverloads();
10007 break;
10008
10009 case OO_PlusPlus:
10010 case OO_MinusMinus:
10011 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10012 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10013 break;
10014
10015 case OO_EqualEqual:
10016 case OO_ExclaimEqual:
10017 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10018 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10019 OpBuilder.addGenericBinaryArithmeticOverloads();
10020 break;
10021
10022 case OO_Less:
10023 case OO_Greater:
10024 case OO_LessEqual:
10025 case OO_GreaterEqual:
10026 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10027 OpBuilder.addGenericBinaryArithmeticOverloads();
10028 break;
10029
10030 case OO_Spaceship:
10031 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10032 OpBuilder.addThreeWayArithmeticOverloads();
10033 break;
10034
10035 case OO_Percent:
10036 case OO_Caret:
10037 case OO_Pipe:
10038 case OO_LessLess:
10039 case OO_GreaterGreater:
10040 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10041 break;
10042
10043 case OO_Amp: // '&' is either unary or binary
10044 if (Args.size() == 1)
10045 // C++ [over.match.oper]p3:
10046 // -- For the operator ',', the unary operator '&', or the
10047 // operator '->', the built-in candidates set is empty.
10048 break;
10049
10050 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10051 break;
10052
10053 case OO_Tilde:
10054 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10055 break;
10056
10057 case OO_Equal:
10058 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10059 [[fallthrough]];
10060
10061 case OO_PlusEqual:
10062 case OO_MinusEqual:
10063 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10064 [[fallthrough]];
10065
10066 case OO_StarEqual:
10067 case OO_SlashEqual:
10068 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10069 break;
10070
10071 case OO_PercentEqual:
10072 case OO_LessLessEqual:
10073 case OO_GreaterGreaterEqual:
10074 case OO_AmpEqual:
10075 case OO_CaretEqual:
10076 case OO_PipeEqual:
10077 OpBuilder.addAssignmentIntegralOverloads();
10078 break;
10079
10080 case OO_Exclaim:
10081 OpBuilder.addExclaimOverload();
10082 break;
10083
10084 case OO_AmpAmp:
10085 case OO_PipePipe:
10086 OpBuilder.addAmpAmpOrPipePipeOverload();
10087 break;
10088
10089 case OO_Subscript:
10090 if (Args.size() == 2)
10091 OpBuilder.addSubscriptOverloads();
10092 break;
10093
10094 case OO_ArrowStar:
10095 OpBuilder.addArrowStarOverloads();
10096 break;
10097
10098 case OO_Conditional:
10099 OpBuilder.addConditionalOperatorOverloads();
10100 OpBuilder.addGenericBinaryArithmeticOverloads();
10101 break;
10102 }
10103}
10104
10105void
10107 SourceLocation Loc,
10108 ArrayRef<Expr *> Args,
10109 TemplateArgumentListInfo *ExplicitTemplateArgs,
10110 OverloadCandidateSet& CandidateSet,
10111 bool PartialOverloading) {
10112 ADLResult Fns;
10113
10114 // FIXME: This approach for uniquing ADL results (and removing
10115 // redundant candidates from the set) relies on pointer-equality,
10116 // which means we need to key off the canonical decl. However,
10117 // always going back to the canonical decl might not get us the
10118 // right set of default arguments. What default arguments are
10119 // we supposed to consider on ADL candidates, anyway?
10120
10121 // FIXME: Pass in the explicit template arguments?
10122 ArgumentDependentLookup(Name, Loc, Args, Fns);
10123
10124 // Erase all of the candidates we already knew about.
10125 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10126 CandEnd = CandidateSet.end();
10127 Cand != CandEnd; ++Cand)
10128 if (Cand->Function) {
10129 FunctionDecl *Fn = Cand->Function;
10130 Fns.erase(Fn);
10131 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10132 Fns.erase(FunTmpl);
10133 }
10134
10135 // For each of the ADL candidates we found, add it to the overload
10136 // set.
10137 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10139
10140 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10141 if (ExplicitTemplateArgs)
10142 continue;
10143
10144 AddOverloadCandidate(
10145 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10146 PartialOverloading, /*AllowExplicit=*/true,
10147 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10148 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10149 AddOverloadCandidate(
10150 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10151 /*SuppressUserConversions=*/false, PartialOverloading,
10152 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10153 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10154 }
10155 } else {
10156 auto *FTD = cast<FunctionTemplateDecl>(*I);
10157 AddTemplateOverloadCandidate(
10158 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10159 /*SuppressUserConversions=*/false, PartialOverloading,
10160 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10161 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10162 *this, Args, FTD->getTemplatedDecl())) {
10163 AddTemplateOverloadCandidate(
10164 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10165 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10166 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10168 }
10169 }
10170 }
10171}
10172
10173namespace {
10174enum class Comparison { Equal, Better, Worse };
10175}
10176
10177/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10178/// overload resolution.
10179///
10180/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10181/// Cand1's first N enable_if attributes have precisely the same conditions as
10182/// Cand2's first N enable_if attributes (where N = the number of enable_if
10183/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10184///
10185/// Note that you can have a pair of candidates such that Cand1's enable_if
10186/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10187/// worse than Cand1's.
10188static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10189 const FunctionDecl *Cand2) {
10190 // Common case: One (or both) decls don't have enable_if attrs.
10191 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10192 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10193 if (!Cand1Attr || !Cand2Attr) {
10194 if (Cand1Attr == Cand2Attr)
10195 return Comparison::Equal;
10196 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10197 }
10198
10199 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10200 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10201
10202 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10203 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10204 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10205 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10206
10207 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10208 // has fewer enable_if attributes than Cand2, and vice versa.
10209 if (!Cand1A)
10210 return Comparison::Worse;
10211 if (!Cand2A)
10212 return Comparison::Better;
10213
10214 Cand1ID.clear();
10215 Cand2ID.clear();
10216
10217 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10218 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10219 if (Cand1ID != Cand2ID)
10220 return Comparison::Worse;
10221 }
10222
10223 return Comparison::Equal;
10224}
10225
10226static Comparison
10228 const OverloadCandidate &Cand2) {
10229 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10230 !Cand2.Function->isMultiVersion())
10231 return Comparison::Equal;
10232
10233 // If both are invalid, they are equal. If one of them is invalid, the other
10234 // is better.
10235 if (Cand1.Function->isInvalidDecl()) {
10236 if (Cand2.Function->isInvalidDecl())
10237 return Comparison::Equal;
10238 return Comparison::Worse;
10239 }
10240 if (Cand2.Function->isInvalidDecl())
10241 return Comparison::Better;
10242
10243 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10244 // cpu_dispatch, else arbitrarily based on the identifiers.
10245 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10246 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10247 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10248 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10249
10250 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10251 return Comparison::Equal;
10252
10253 if (Cand1CPUDisp && !Cand2CPUDisp)
10254 return Comparison::Better;
10255 if (Cand2CPUDisp && !Cand1CPUDisp)
10256 return Comparison::Worse;
10257
10258 if (Cand1CPUSpec && Cand2CPUSpec) {
10259 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10260 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10261 ? Comparison::Better
10262 : Comparison::Worse;
10263
10264 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10265 FirstDiff = std::mismatch(
10266 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10267 Cand2CPUSpec->cpus_begin(),
10268 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10269 return LHS->getName() == RHS->getName();
10270 });
10271
10272 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10273 "Two different cpu-specific versions should not have the same "
10274 "identifier list, otherwise they'd be the same decl!");
10275 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10276 ? Comparison::Better
10277 : Comparison::Worse;
10278 }
10279 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10280}
10281
10282/// Compute the type of the implicit object parameter for the given function,
10283/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10284/// null QualType if there is a 'matches anything' implicit object parameter.
10285static std::optional<QualType>
10287 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10288 return std::nullopt;
10289
10290 auto *M = cast<CXXMethodDecl>(F);
10291 // Static member functions' object parameters match all types.
10292 if (M->isStatic())
10293 return QualType();
10294 return M->getFunctionObjectParameterReferenceType();
10295}
10296
10297// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10298// represent the same entity.
10299static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10300 const FunctionDecl *F2) {
10301 if (declaresSameEntity(F1, F2))
10302 return true;
10303 auto PT1 = F1->getPrimaryTemplate();
10304 auto PT2 = F2->getPrimaryTemplate();
10305 if (PT1 && PT2) {
10306 if (declaresSameEntity(PT1, PT2) ||
10307 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10308 PT2->getInstantiatedFromMemberTemplate()))
10309 return true;
10310 }
10311 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10312 // different functions with same params). Consider removing this (as no test
10313 // fail w/o it).
10314 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10315 if (First) {
10316 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10317 return *T;
10318 }
10319 assert(I < F->getNumParams());
10320 return F->getParamDecl(I++)->getType();
10321 };
10322
10323 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10324 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10325
10326 if (F1NumParams != F2NumParams)
10327 return false;
10328
10329 unsigned I1 = 0, I2 = 0;
10330 for (unsigned I = 0; I != F1NumParams; ++I) {
10331 QualType T1 = NextParam(F1, I1, I == 0);
10332 QualType T2 = NextParam(F2, I2, I == 0);
10333 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10334 if (!Context.hasSameUnqualifiedType(T1, T2))
10335 return false;
10336 }
10337 return true;
10338}
10339
10340/// We're allowed to use constraints partial ordering only if the candidates
10341/// have the same parameter types:
10342/// [over.match.best.general]p2.6
10343/// F1 and F2 are non-template functions with the same
10344/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10346 const OverloadCandidate &Cand1,
10347 const OverloadCandidate &Cand2) {
10348 if (!Cand1.Function || !Cand2.Function)
10349 return false;
10350
10351 FunctionDecl *Fn1 = Cand1.Function;
10352 FunctionDecl *Fn2 = Cand2.Function;
10353
10354 if (Fn1->isVariadic() != Fn2->isVariadic())
10355 return false;
10356
10358 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10359 return false;
10360
10361 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10362 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10363 if (Mem1 && Mem2) {
10364 // if they are member functions, both are direct members of the same class,
10365 // and
10366 if (Mem1->getParent() != Mem2->getParent())
10367 return false;
10368 // if both are non-static member functions, they have the same types for
10369 // their object parameters
10370 if (Mem1->isInstance() && Mem2->isInstance() &&
10372 Mem1->getFunctionObjectParameterReferenceType(),
10373 Mem1->getFunctionObjectParameterReferenceType()))
10374 return false;
10375 }
10376 return true;
10377}
10378
10379/// isBetterOverloadCandidate - Determines whether the first overload
10380/// candidate is a better candidate than the second (C++ 13.3.3p1).
10382 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10384 // Define viable functions to be better candidates than non-viable
10385 // functions.
10386 if (!Cand2.Viable)
10387 return Cand1.Viable;
10388 else if (!Cand1.Viable)
10389 return false;
10390
10391 // [CUDA] A function with 'never' preference is marked not viable, therefore
10392 // is never shown up here. The worst preference shown up here is 'wrong side',
10393 // e.g. an H function called by a HD function in device compilation. This is
10394 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10395 // function which is called only by an H function. A deferred diagnostic will
10396 // be triggered if it is emitted. However a wrong-sided function is still
10397 // a viable candidate here.
10398 //
10399 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10400 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10401 // can be emitted, Cand1 is not better than Cand2. This rule should have
10402 // precedence over other rules.
10403 //
10404 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10405 // other rules should be used to determine which is better. This is because
10406 // host/device based overloading resolution is mostly for determining
10407 // viability of a function. If two functions are both viable, other factors
10408 // should take precedence in preference, e.g. the standard-defined preferences
10409 // like argument conversion ranks or enable_if partial-ordering. The
10410 // preference for pass-object-size parameters is probably most similar to a
10411 // type-based-overloading decision and so should take priority.
10412 //
10413 // If other rules cannot determine which is better, CUDA preference will be
10414 // used again to determine which is better.
10415 //
10416 // TODO: Currently IdentifyPreference does not return correct values
10417 // for functions called in global variable initializers due to missing
10418 // correct context about device/host. Therefore we can only enforce this
10419 // rule when there is a caller. We should enforce this rule for functions
10420 // in global variable initializers once proper context is added.
10421 //
10422 // TODO: We can only enable the hostness based overloading resolution when
10423 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10424 // overloading resolution diagnostics.
10425 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10426 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10427 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10428 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10429 bool IsCand1ImplicitHD =
10431 bool IsCand2ImplicitHD =
10433 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10434 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10435 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10436 // The implicit HD function may be a function in a system header which
10437 // is forced by pragma. In device compilation, if we prefer HD candidates
10438 // over wrong-sided candidates, overloading resolution may change, which
10439 // may result in non-deferrable diagnostics. As a workaround, we let
10440 // implicit HD candidates take equal preference as wrong-sided candidates.
10441 // This will preserve the overloading resolution.
10442 // TODO: We still need special handling of implicit HD functions since
10443 // they may incur other diagnostics to be deferred. We should make all
10444 // host/device related diagnostics deferrable and remove special handling
10445 // of implicit HD functions.
10446 auto EmitThreshold =
10447 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10448 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10451 auto Cand1Emittable = P1 > EmitThreshold;
10452 auto Cand2Emittable = P2 > EmitThreshold;
10453 if (Cand1Emittable && !Cand2Emittable)
10454 return true;
10455 if (!Cand1Emittable && Cand2Emittable)
10456 return false;
10457 }
10458 }
10459
10460 // C++ [over.match.best]p1: (Changed in C++23)
10461 //
10462 // -- if F is a static member function, ICS1(F) is defined such
10463 // that ICS1(F) is neither better nor worse than ICS1(G) for
10464 // any function G, and, symmetrically, ICS1(G) is neither
10465 // better nor worse than ICS1(F).
10466 unsigned StartArg = 0;
10467 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10468 StartArg = 1;
10469
10470 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10471 // We don't allow incompatible pointer conversions in C++.
10472 if (!S.getLangOpts().CPlusPlus)
10473 return ICS.isStandard() &&
10474 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10475
10476 // The only ill-formed conversion we allow in C++ is the string literal to
10477 // char* conversion, which is only considered ill-formed after C++11.
10478 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10480 };
10481
10482 // Define functions that don't require ill-formed conversions for a given
10483 // argument to be better candidates than functions that do.
10484 unsigned NumArgs = Cand1.Conversions.size();
10485 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10486 bool HasBetterConversion = false;
10487 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10488 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10489 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10490 if (Cand1Bad != Cand2Bad) {
10491 if (Cand1Bad)
10492 return false;
10493 HasBetterConversion = true;
10494 }
10495 }
10496
10497 if (HasBetterConversion)
10498 return true;
10499
10500 // C++ [over.match.best]p1:
10501 // A viable function F1 is defined to be a better function than another
10502 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10503 // conversion sequence than ICSi(F2), and then...
10504 bool HasWorseConversion = false;
10505 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10507 Cand1.Conversions[ArgIdx],
10508 Cand2.Conversions[ArgIdx])) {
10510 // Cand1 has a better conversion sequence.
10511 HasBetterConversion = true;
10512 break;
10513
10515 if (Cand1.Function && Cand2.Function &&
10516 Cand1.isReversed() != Cand2.isReversed() &&
10517 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10518 // Work around large-scale breakage caused by considering reversed
10519 // forms of operator== in C++20:
10520 //
10521 // When comparing a function against a reversed function, if we have a
10522 // better conversion for one argument and a worse conversion for the
10523 // other, the implicit conversion sequences are treated as being equally
10524 // good.
10525 //
10526 // This prevents a comparison function from being considered ambiguous
10527 // with a reversed form that is written in the same way.
10528 //
10529 // We diagnose this as an extension from CreateOverloadedBinOp.
10530 HasWorseConversion = true;
10531 break;
10532 }
10533
10534 // Cand1 can't be better than Cand2.
10535 return false;
10536
10538 // Do nothing.
10539 break;
10540 }
10541 }
10542
10543 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10544 // ICSj(F2), or, if not that,
10545 if (HasBetterConversion && !HasWorseConversion)
10546 return true;
10547
10548 // -- the context is an initialization by user-defined conversion
10549 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10550 // from the return type of F1 to the destination type (i.e.,
10551 // the type of the entity being initialized) is a better
10552 // conversion sequence than the standard conversion sequence
10553 // from the return type of F2 to the destination type.
10555 Cand1.Function && Cand2.Function &&
10556 isa<CXXConversionDecl>(Cand1.Function) &&
10557 isa<CXXConversionDecl>(Cand2.Function)) {
10558 // First check whether we prefer one of the conversion functions over the
10559 // other. This only distinguishes the results in non-standard, extension
10560 // cases such as the conversion from a lambda closure type to a function
10561 // pointer or block.
10566 Cand1.FinalConversion,
10567 Cand2.FinalConversion);
10568
10571
10572 // FIXME: Compare kind of reference binding if conversion functions
10573 // convert to a reference type used in direct reference binding, per
10574 // C++14 [over.match.best]p1 section 2 bullet 3.
10575 }
10576
10577 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10578 // as combined with the resolution to CWG issue 243.
10579 //
10580 // When the context is initialization by constructor ([over.match.ctor] or
10581 // either phase of [over.match.list]), a constructor is preferred over
10582 // a conversion function.
10583 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10584 Cand1.Function && Cand2.Function &&
10585 isa<CXXConstructorDecl>(Cand1.Function) !=
10586 isa<CXXConstructorDecl>(Cand2.Function))
10587 return isa<CXXConstructorDecl>(Cand1.Function);
10588
10592
10593 // -- F1 is a non-template function and F2 is a function template
10594 // specialization, or, if not that,
10595 bool Cand1IsSpecialization = Cand1.Function &&
10597 bool Cand2IsSpecialization = Cand2.Function &&
10599 if (Cand1IsSpecialization != Cand2IsSpecialization)
10600 return Cand2IsSpecialization;
10601
10602 // -- F1 and F2 are function template specializations, and the function
10603 // template for F1 is more specialized than the template for F2
10604 // according to the partial ordering rules described in 14.5.5.2, or,
10605 // if not that,
10606 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10607 const auto *Obj1Context =
10608 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10609 const auto *Obj2Context =
10610 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10611 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10614 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10615 : TPOC_Call,
10617 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10618 : QualType{},
10619 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10620 : QualType{},
10621 Cand1.isReversed() ^ Cand2.isReversed())) {
10622 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10623 }
10624 }
10625
10626 // -— F1 and F2 are non-template functions with the same
10627 // parameter-type-lists, and F1 is more constrained than F2 [...],
10628 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10629 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10631 Cand1.Function)
10632 return true;
10633
10634 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10635 // class B of D, and for all arguments the corresponding parameters of
10636 // F1 and F2 have the same type.
10637 // FIXME: Implement the "all parameters have the same type" check.
10638 bool Cand1IsInherited =
10639 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10640 bool Cand2IsInherited =
10641 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10642 if (Cand1IsInherited != Cand2IsInherited)
10643 return Cand2IsInherited;
10644 else if (Cand1IsInherited) {
10645 assert(Cand2IsInherited);
10646 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10647 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10648 if (Cand1Class->isDerivedFrom(Cand2Class))
10649 return true;
10650 if (Cand2Class->isDerivedFrom(Cand1Class))
10651 return false;
10652 // Inherited from sibling base classes: still ambiguous.
10653 }
10654
10655 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10656 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10657 // with reversed order of parameters and F1 is not
10658 //
10659 // We rank reversed + different operator as worse than just reversed, but
10660 // that comparison can never happen, because we only consider reversing for
10661 // the maximally-rewritten operator (== or <=>).
10662 if (Cand1.RewriteKind != Cand2.RewriteKind)
10663 return Cand1.RewriteKind < Cand2.RewriteKind;
10664
10665 // Check C++17 tie-breakers for deduction guides.
10666 {
10667 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10668 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10669 if (Guide1 && Guide2) {
10670 // -- F1 is generated from a deduction-guide and F2 is not
10671 if (Guide1->isImplicit() != Guide2->isImplicit())
10672 return Guide2->isImplicit();
10673
10674 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10675 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10676 return true;
10677 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10678 return false;
10679
10680 // --F1 is generated from a non-template constructor and F2 is generated
10681 // from a constructor template
10682 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10683 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10684 if (Constructor1 && Constructor2) {
10685 bool isC1Templated = Constructor1->getTemplatedKind() !=
10687 bool isC2Templated = Constructor2->getTemplatedKind() !=
10689 if (isC1Templated != isC2Templated)
10690 return isC2Templated;
10691 }
10692 }
10693 }
10694
10695 // Check for enable_if value-based overload resolution.
10696 if (Cand1.Function && Cand2.Function) {
10697 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10698 if (Cmp != Comparison::Equal)
10699 return Cmp == Comparison::Better;
10700 }
10701
10702 bool HasPS1 = Cand1.Function != nullptr &&
10704 bool HasPS2 = Cand2.Function != nullptr &&
10706 if (HasPS1 != HasPS2 && HasPS1)
10707 return true;
10708
10709 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10710 if (MV == Comparison::Better)
10711 return true;
10712 if (MV == Comparison::Worse)
10713 return false;
10714
10715 // If other rules cannot determine which is better, CUDA preference is used
10716 // to determine which is better.
10717 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10718 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10719 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10720 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10721 }
10722
10723 // General member function overloading is handled above, so this only handles
10724 // constructors with address spaces.
10725 // This only handles address spaces since C++ has no other
10726 // qualifier that can be used with constructors.
10727 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10728 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10729 if (CD1 && CD2) {
10730 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10731 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10732 if (AS1 != AS2) {
10734 return true;
10736 return false;
10737 }
10738 }
10739
10740 return false;
10741}
10742
10743/// Determine whether two declarations are "equivalent" for the purposes of
10744/// name lookup and overload resolution. This applies when the same internal/no
10745/// linkage entity is defined by two modules (probably by textually including
10746/// the same header). In such a case, we don't consider the declarations to
10747/// declare the same entity, but we also don't want lookups with both
10748/// declarations visible to be ambiguous in some cases (this happens when using
10749/// a modularized libstdc++).
10751 const NamedDecl *B) {
10752 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10753 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10754 if (!VA || !VB)
10755 return false;
10756
10757 // The declarations must be declaring the same name as an internal linkage
10758 // entity in different modules.
10759 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10760 VB->getDeclContext()->getRedeclContext()) ||
10761 getOwningModule(VA) == getOwningModule(VB) ||
10762 VA->isExternallyVisible() || VB->isExternallyVisible())
10763 return false;
10764
10765 // Check that the declarations appear to be equivalent.
10766 //
10767 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10768 // For constants and functions, we should check the initializer or body is
10769 // the same. For non-constant variables, we shouldn't allow it at all.
10770 if (Context.hasSameType(VA->getType(), VB->getType()))
10771 return true;
10772
10773 // Enum constants within unnamed enumerations will have different types, but
10774 // may still be similar enough to be interchangeable for our purposes.
10775 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10776 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10777 // Only handle anonymous enums. If the enumerations were named and
10778 // equivalent, they would have been merged to the same type.
10779 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10780 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10781 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10782 !Context.hasSameType(EnumA->getIntegerType(),
10783 EnumB->getIntegerType()))
10784 return false;
10785 // Allow this only if the value is the same for both enumerators.
10786 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10787 }
10788 }
10789
10790 // Nothing else is sufficiently similar.
10791 return false;
10792}
10793
10796 assert(D && "Unknown declaration");
10797 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10798
10799 Module *M = getOwningModule(D);
10800 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10801 << !M << (M ? M->getFullModuleName() : "");
10802
10803 for (auto *E : Equiv) {
10804 Module *M = getOwningModule(E);
10805 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10806 << !M << (M ? M->getFullModuleName() : "");
10807 }
10808}
10809
10811 return FailureKind == ovl_fail_bad_deduction &&
10812 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10814 static_cast<CNSInfo *>(DeductionFailure.Data)
10815 ->Satisfaction.ContainsErrors;
10816}
10817
10818/// Computes the best viable function (C++ 13.3.3)
10819/// within an overload candidate set.
10820///
10821/// \param Loc The location of the function name (or operator symbol) for
10822/// which overload resolution occurs.
10823///
10824/// \param Best If overload resolution was successful or found a deleted
10825/// function, \p Best points to the candidate function found.
10826///
10827/// \returns The result of overload resolution.
10830 iterator &Best) {
10832 std::transform(begin(), end(), std::back_inserter(Candidates),
10833 [](OverloadCandidate &Cand) { return &Cand; });
10834
10835 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10836 // are accepted by both clang and NVCC. However, during a particular
10837 // compilation mode only one call variant is viable. We need to
10838 // exclude non-viable overload candidates from consideration based
10839 // only on their host/device attributes. Specifically, if one
10840 // candidate call is WrongSide and the other is SameSide, we ignore
10841 // the WrongSide candidate.
10842 // We only need to remove wrong-sided candidates here if
10843 // -fgpu-exclude-wrong-side-overloads is off. When
10844 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10845 // uniformly in isBetterOverloadCandidate.
10846 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10847 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10848 bool ContainsSameSideCandidate =
10849 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10850 // Check viable function only.
10851 return Cand->Viable && Cand->Function &&
10852 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10854 });
10855 if (ContainsSameSideCandidate) {
10856 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10857 // Check viable function only to avoid unnecessary data copying/moving.
10858 return Cand->Viable && Cand->Function &&
10859 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10861 };
10862 llvm::erase_if(Candidates, IsWrongSideCandidate);
10863 }
10864 }
10865
10866 // Find the best viable function.
10867 Best = end();
10868 for (auto *Cand : Candidates) {
10869 Cand->Best = false;
10870 if (Cand->Viable) {
10871 if (Best == end() ||
10872 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10873 Best = Cand;
10874 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10875 // This candidate has constraint that we were unable to evaluate because
10876 // it referenced an expression that contained an error. Rather than fall
10877 // back onto a potentially unintended candidate (made worse by
10878 // subsuming constraints), treat this as 'no viable candidate'.
10879 Best = end();
10880 return OR_No_Viable_Function;
10881 }
10882 }
10883
10884 // If we didn't find any viable functions, abort.
10885 if (Best == end())
10886 return OR_No_Viable_Function;
10887
10889
10891 PendingBest.push_back(&*Best);
10892 Best->Best = true;
10893
10894 // Make sure that this function is better than every other viable
10895 // function. If not, we have an ambiguity.
10896 while (!PendingBest.empty()) {
10897 auto *Curr = PendingBest.pop_back_val();
10898 for (auto *Cand : Candidates) {
10899 if (Cand->Viable && !Cand->Best &&
10900 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10901 PendingBest.push_back(Cand);
10902 Cand->Best = true;
10903
10905 Curr->Function))
10906 EquivalentCands.push_back(Cand->Function);
10907 else
10908 Best = end();
10909 }
10910 }
10911 }
10912
10913 // If we found more than one best candidate, this is ambiguous.
10914 if (Best == end())
10915 return OR_Ambiguous;
10916
10917 // Best is the best viable function.
10918 if (Best->Function && Best->Function->isDeleted())
10919 return OR_Deleted;
10920
10921 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10922 Kind == CSK_AddressOfOverloadSet && M &&
10923 M->isImplicitObjectMemberFunction()) {
10924 return OR_No_Viable_Function;
10925 }
10926
10927 if (!EquivalentCands.empty())
10929 EquivalentCands);
10930
10931 return OR_Success;
10932}
10933
10934namespace {
10935
10936enum OverloadCandidateKind {
10937 oc_function,
10938 oc_method,
10939 oc_reversed_binary_operator,
10940 oc_constructor,
10941 oc_implicit_default_constructor,
10942 oc_implicit_copy_constructor,
10943 oc_implicit_move_constructor,
10944 oc_implicit_copy_assignment,
10945 oc_implicit_move_assignment,
10946 oc_implicit_equality_comparison,
10947 oc_inherited_constructor
10948};
10949
10950enum OverloadCandidateSelect {
10951 ocs_non_template,
10952 ocs_template,
10953 ocs_described_template,
10954};
10955
10956static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10957ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10958 const FunctionDecl *Fn,
10960 std::string &Description) {
10961
10962 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10963 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10964 isTemplate = true;
10965 Description = S.getTemplateArgumentBindingsText(
10966 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10967 }
10968
10969 OverloadCandidateSelect Select = [&]() {
10970 if (!Description.empty())
10971 return ocs_described_template;
10972 return isTemplate ? ocs_template : ocs_non_template;
10973 }();
10974
10975 OverloadCandidateKind Kind = [&]() {
10976 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10977 return oc_implicit_equality_comparison;
10978
10979 if (CRK & CRK_Reversed)
10980 return oc_reversed_binary_operator;
10981
10982 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10983 if (!Ctor->isImplicit()) {
10984 if (isa<ConstructorUsingShadowDecl>(Found))
10985 return oc_inherited_constructor;
10986 else
10987 return oc_constructor;
10988 }
10989
10990 if (Ctor->isDefaultConstructor())
10991 return oc_implicit_default_constructor;
10992
10993 if (Ctor->isMoveConstructor())
10994 return oc_implicit_move_constructor;
10995
10996 assert(Ctor->isCopyConstructor() &&
10997 "unexpected sort of implicit constructor");
10998 return oc_implicit_copy_constructor;
10999 }
11000
11001 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11002 // This actually gets spelled 'candidate function' for now, but
11003 // it doesn't hurt to split it out.
11004 if (!Meth->isImplicit())
11005 return oc_method;
11006
11007 if (Meth->isMoveAssignmentOperator())
11008 return oc_implicit_move_assignment;
11009
11010 if (Meth->isCopyAssignmentOperator())
11011 return oc_implicit_copy_assignment;
11012
11013 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11014 return oc_method;
11015 }
11016
11017 return oc_function;
11018 }();
11019
11020 return std::make_pair(Kind, Select);
11021}
11022
11023void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11024 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11025 // set.
11026 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11027 S.Diag(FoundDecl->getLocation(),
11028 diag::note_ovl_candidate_inherited_constructor)
11029 << Shadow->getNominatedBaseClass();
11030}
11031
11032} // end anonymous namespace
11033
11035 const FunctionDecl *FD) {
11036 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11037 bool AlwaysTrue;
11038 if (EnableIf->getCond()->isValueDependent() ||
11039 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11040 return false;
11041 if (!AlwaysTrue)
11042 return false;
11043 }
11044 return true;
11045}
11046
11047/// Returns true if we can take the address of the function.
11048///
11049/// \param Complain - If true, we'll emit a diagnostic
11050/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11051/// we in overload resolution?
11052/// \param Loc - The location of the statement we're complaining about. Ignored
11053/// if we're not complaining, or if we're in overload resolution.
11055 bool Complain,
11056 bool InOverloadResolution,
11057 SourceLocation Loc) {
11058 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11059 if (Complain) {
11060 if (InOverloadResolution)
11061 S.Diag(FD->getBeginLoc(),
11062 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11063 else
11064 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11065 }
11066 return false;
11067 }
11068
11069 if (FD->getTrailingRequiresClause()) {
11070 ConstraintSatisfaction Satisfaction;
11071 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11072 return false;
11073 if (!Satisfaction.IsSatisfied) {
11074 if (Complain) {
11075 if (InOverloadResolution) {
11076 SmallString<128> TemplateArgString;
11077 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11078 TemplateArgString += " ";
11079 TemplateArgString += S.getTemplateArgumentBindingsText(
11080 FunTmpl->getTemplateParameters(),
11082 }
11083
11084 S.Diag(FD->getBeginLoc(),
11085 diag::note_ovl_candidate_unsatisfied_constraints)
11086 << TemplateArgString;
11087 } else
11088 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11089 << FD;
11090 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11091 }
11092 return false;
11093 }
11094 }
11095
11096 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11097 return P->hasAttr<PassObjectSizeAttr>();
11098 });
11099 if (I == FD->param_end())
11100 return true;
11101
11102 if (Complain) {
11103 // Add one to ParamNo because it's user-facing
11104 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11105 if (InOverloadResolution)
11106 S.Diag(FD->getLocation(),
11107 diag::note_ovl_candidate_has_pass_object_size_params)
11108 << ParamNo;
11109 else
11110 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11111 << FD << ParamNo;
11112 }
11113 return false;
11114}
11115
11117 const FunctionDecl *FD) {
11118 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11119 /*InOverloadResolution=*/true,
11120 /*Loc=*/SourceLocation());
11121}
11122
11124 bool Complain,
11125 SourceLocation Loc) {
11126 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11127 /*InOverloadResolution=*/false,
11128 Loc);
11129}
11130
11131// Don't print candidates other than the one that matches the calling
11132// convention of the call operator, since that is guaranteed to exist.
11134 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11135
11136 if (!ConvD)
11137 return false;
11138 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11139 if (!RD->isLambda())
11140 return false;
11141
11142 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11143 CallingConv CallOpCC =
11144 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11145 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11146 CallingConv ConvToCC =
11147 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11148
11149 return ConvToCC != CallOpCC;
11150}
11151
11152// Notes the location of an overload candidate.
11154 OverloadCandidateRewriteKind RewriteKind,
11155 QualType DestType, bool TakingAddress) {
11156 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11157 return;
11158 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11159 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11160 return;
11161 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11162 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11163 return;
11165 return;
11166
11167 std::string FnDesc;
11168 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11169 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11170 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11171 << (unsigned)KSPair.first << (unsigned)KSPair.second
11172 << Fn << FnDesc;
11173
11174 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11175 Diag(Fn->getLocation(), PD);
11176 MaybeEmitInheritedConstructorNote(*this, Found);
11177}
11178
11179static void
11181 // Perhaps the ambiguity was caused by two atomic constraints that are
11182 // 'identical' but not equivalent:
11183 //
11184 // void foo() requires (sizeof(T) > 4) { } // #1
11185 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11186 //
11187 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11188 // #2 to subsume #1, but these constraint are not considered equivalent
11189 // according to the subsumption rules because they are not the same
11190 // source-level construct. This behavior is quite confusing and we should try
11191 // to help the user figure out what happened.
11192
11193 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11194 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11195 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11196 if (!I->Function)
11197 continue;
11199 if (auto *Template = I->Function->getPrimaryTemplate())
11200 Template->getAssociatedConstraints(AC);
11201 else
11202 I->Function->getAssociatedConstraints(AC);
11203 if (AC.empty())
11204 continue;
11205 if (FirstCand == nullptr) {
11206 FirstCand = I->Function;
11207 FirstAC = AC;
11208 } else if (SecondCand == nullptr) {
11209 SecondCand = I->Function;
11210 SecondAC = AC;
11211 } else {
11212 // We have more than one pair of constrained functions - this check is
11213 // expensive and we'd rather not try to diagnose it.
11214 return;
11215 }
11216 }
11217 if (!SecondCand)
11218 return;
11219 // The diagnostic can only happen if there are associated constraints on
11220 // both sides (there needs to be some identical atomic constraint).
11221 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11222 SecondCand, SecondAC))
11223 // Just show the user one diagnostic, they'll probably figure it out
11224 // from here.
11225 return;
11226}
11227
11228// Notes the location of all overload candidates designated through
11229// OverloadedExpr
11230void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11231 bool TakingAddress) {
11232 assert(OverloadedExpr->getType() == Context.OverloadTy);
11233
11234 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11235 OverloadExpr *OvlExpr = Ovl.Expression;
11236
11237 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11238 IEnd = OvlExpr->decls_end();
11239 I != IEnd; ++I) {
11240 if (FunctionTemplateDecl *FunTmpl =
11241 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11242 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11243 TakingAddress);
11244 } else if (FunctionDecl *Fun
11245 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11246 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11247 }
11248 }
11249}
11250
11251/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11252/// "lead" diagnostic; it will be given two arguments, the source and
11253/// target types of the conversion.
11255 Sema &S,
11256 SourceLocation CaretLoc,
11257 const PartialDiagnostic &PDiag) const {
11258 S.Diag(CaretLoc, PDiag)
11259 << Ambiguous.getFromType() << Ambiguous.getToType();
11260 unsigned CandsShown = 0;
11262 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11263 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11264 break;
11265 ++CandsShown;
11266 S.NoteOverloadCandidate(I->first, I->second);
11267 }
11268 S.Diags.overloadCandidatesShown(CandsShown);
11269 if (I != E)
11270 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11271}
11272
11274 unsigned I, bool TakingCandidateAddress) {
11275 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11276 assert(Conv.isBad());
11277 assert(Cand->Function && "for now, candidate must be a function");
11278 FunctionDecl *Fn = Cand->Function;
11279
11280 // There's a conversion slot for the object argument if this is a
11281 // non-constructor method. Note that 'I' corresponds the
11282 // conversion-slot index.
11283 bool isObjectArgument = false;
11284 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11285 if (I == 0)
11286 isObjectArgument = true;
11287 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11288 I--;
11289 }
11290
11291 std::string FnDesc;
11292 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11293 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11294 FnDesc);
11295
11296 Expr *FromExpr = Conv.Bad.FromExpr;
11297 QualType FromTy = Conv.Bad.getFromType();
11298 QualType ToTy = Conv.Bad.getToType();
11299 SourceRange ToParamRange;
11300
11301 // FIXME: In presence of parameter packs we can't determine parameter range
11302 // reliably, as we don't have access to instantiation.
11303 bool HasParamPack =
11304 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11305 return Parm->isParameterPack();
11306 });
11307 if (!isObjectArgument && !HasParamPack)
11308 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11309
11310 if (FromTy == S.Context.OverloadTy) {
11311 assert(FromExpr && "overload set argument came from implicit argument?");
11312 Expr *E = FromExpr->IgnoreParens();
11313 if (isa<UnaryOperator>(E))
11314 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11315 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11316
11317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11318 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11319 << ToParamRange << ToTy << Name << I + 1;
11320 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11321 return;
11322 }
11323
11324 // Do some hand-waving analysis to see if the non-viability is due
11325 // to a qualifier mismatch.
11326 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11327 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11328 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11329 CToTy = RT->getPointeeType();
11330 else {
11331 // TODO: detect and diagnose the full richness of const mismatches.
11332 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11333 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11334 CFromTy = FromPT->getPointeeType();
11335 CToTy = ToPT->getPointeeType();
11336 }
11337 }
11338
11339 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11340 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11341 Qualifiers FromQs = CFromTy.getQualifiers();
11342 Qualifiers ToQs = CToTy.getQualifiers();
11343
11344 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11345 if (isObjectArgument)
11346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11347 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11348 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11349 else
11350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11351 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11352 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11353 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11354 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11355 return;
11356 }
11357
11358 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11360 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11361 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11362 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11363 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11364 return;
11365 }
11366
11367 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11368 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11369 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11370 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11371 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11372 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11373 return;
11374 }
11375
11376 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11377 assert(CVR && "expected qualifiers mismatch");
11378
11379 if (isObjectArgument) {
11380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11381 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11382 << FromTy << (CVR - 1);
11383 } else {
11384 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11385 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11386 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11387 }
11388 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11389 return;
11390 }
11391
11394 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11395 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11396 << (unsigned)isObjectArgument << I + 1
11398 << ToParamRange;
11399 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11400 return;
11401 }
11402
11403 // Special diagnostic for failure to convert an initializer list, since
11404 // telling the user that it has type void is not useful.
11405 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11406 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11407 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11408 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11411 ? 2
11412 : 0);
11413 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11414 return;
11415 }
11416
11417 // Diagnose references or pointers to incomplete types differently,
11418 // since it's far from impossible that the incompleteness triggered
11419 // the failure.
11420 QualType TempFromTy = FromTy.getNonReferenceType();
11421 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11422 TempFromTy = PTy->getPointeeType();
11423 if (TempFromTy->isIncompleteType()) {
11424 // Emit the generic diagnostic and, optionally, add the hints to it.
11425 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11426 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11427 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11428 << (unsigned)(Cand->Fix.Kind);
11429
11430 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11431 return;
11432 }
11433
11434 // Diagnose base -> derived pointer conversions.
11435 unsigned BaseToDerivedConversion = 0;
11436 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11437 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11438 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11439 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11440 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11441 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11442 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11443 FromPtrTy->getPointeeType()))
11444 BaseToDerivedConversion = 1;
11445 }
11446 } else if (const ObjCObjectPointerType *FromPtrTy
11447 = FromTy->getAs<ObjCObjectPointerType>()) {
11448 if (const ObjCObjectPointerType *ToPtrTy
11449 = ToTy->getAs<ObjCObjectPointerType>())
11450 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11451 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11452 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11453 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11454 FromIface->isSuperClassOf(ToIface))
11455 BaseToDerivedConversion = 2;
11456 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11457 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11458 S.getASTContext()) &&
11459 !FromTy->isIncompleteType() &&
11460 !ToRefTy->getPointeeType()->isIncompleteType() &&
11461 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11462 BaseToDerivedConversion = 3;
11463 }
11464 }
11465
11466 if (BaseToDerivedConversion) {
11467 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11468 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11469 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11470 << I + 1;
11471 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11472 return;
11473 }
11474
11475 if (isa<ObjCObjectPointerType>(CFromTy) &&
11476 isa<PointerType>(CToTy)) {
11477 Qualifiers FromQs = CFromTy.getQualifiers();
11478 Qualifiers ToQs = CToTy.getQualifiers();
11479 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11481 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11482 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11483 << I + 1;
11484 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11485 return;
11486 }
11487 }
11488
11489 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11490 return;
11491
11492 // Emit the generic diagnostic and, optionally, add the hints to it.
11493 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11494 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11495 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11496 << (unsigned)(Cand->Fix.Kind);
11497
11498 // Check that location of Fn is not in system header.
11499 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11500 // If we can fix the conversion, suggest the FixIts.
11501 for (const FixItHint &HI : Cand->Fix.Hints)
11502 FDiag << HI;
11503 }
11504
11505 S.Diag(Fn->getLocation(), FDiag);
11506
11507 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11508}
11509
11510/// Additional arity mismatch diagnosis specific to a function overload
11511/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11512/// over a candidate in any candidate set.
11514 unsigned NumArgs, bool IsAddressOf = false) {
11515 assert(Cand->Function && "Candidate is required to be a function.");
11516 FunctionDecl *Fn = Cand->Function;
11517 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11518 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11519
11520 // With invalid overloaded operators, it's possible that we think we
11521 // have an arity mismatch when in fact it looks like we have the
11522 // right number of arguments, because only overloaded operators have
11523 // the weird behavior of overloading member and non-member functions.
11524 // Just don't report anything.
11525 if (Fn->isInvalidDecl() &&
11526 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11527 return true;
11528
11529 if (NumArgs < MinParams) {
11530 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11532 Cand->DeductionFailure.getResult() ==
11534 } else {
11535 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11537 Cand->DeductionFailure.getResult() ==
11539 }
11540
11541 return false;
11542}
11543
11544/// General arity mismatch diagnosis over a candidate in a candidate set.
11546 unsigned NumFormalArgs,
11547 bool IsAddressOf = false) {
11548 assert(isa<FunctionDecl>(D) &&
11549 "The templated declaration should at least be a function"
11550 " when diagnosing bad template argument deduction due to too many"
11551 " or too few arguments");
11552
11553 FunctionDecl *Fn = cast<FunctionDecl>(D);
11554
11555 // TODO: treat calls to a missing default constructor as a special case
11556 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11557 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11558 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11559
11560 // at least / at most / exactly
11561 bool HasExplicitObjectParam =
11562 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11563
11564 unsigned ParamCount =
11565 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11566 unsigned mode, modeCount;
11567
11568 if (NumFormalArgs < MinParams) {
11569 if (MinParams != ParamCount || FnTy->isVariadic() ||
11570 FnTy->isTemplateVariadic())
11571 mode = 0; // "at least"
11572 else
11573 mode = 2; // "exactly"
11574 modeCount = MinParams;
11575 } else {
11576 if (MinParams != ParamCount)
11577 mode = 1; // "at most"
11578 else
11579 mode = 2; // "exactly"
11580 modeCount = ParamCount;
11581 }
11582
11583 std::string Description;
11584 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11585 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11586
11587 if (modeCount == 1 && !IsAddressOf &&
11588 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11590 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11591 << Description << mode
11592 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11593 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11594 else
11595 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11596 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11597 << Description << mode << modeCount << NumFormalArgs
11598 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11599
11600 MaybeEmitInheritedConstructorNote(S, Found);
11601}
11602
11603/// Arity mismatch diagnosis specific to a function overload candidate.
11605 unsigned NumFormalArgs) {
11606 assert(Cand->Function && "Candidate must be a function");
11607 FunctionDecl *Fn = Cand->Function;
11608 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11609 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11610 Cand->TookAddressOfOverload);
11611}
11612
11614 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11615 return TD;
11616 llvm_unreachable("Unsupported: Getting the described template declaration"
11617 " for bad deduction diagnosis");
11618}
11619
11620/// Diagnose a failed template-argument deduction.
11621static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11622 DeductionFailureInfo &DeductionFailure,
11623 unsigned NumArgs,
11624 bool TakingCandidateAddress) {
11625 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11626 NamedDecl *ParamD;
11627 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11628 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11629 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11630 switch (DeductionFailure.getResult()) {
11632 llvm_unreachable(
11633 "TemplateDeductionResult::Success while diagnosing bad deduction");
11635 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11636 "while diagnosing bad deduction");
11639 return;
11640
11642 assert(ParamD && "no parameter found for incomplete deduction result");
11643 S.Diag(Templated->getLocation(),
11644 diag::note_ovl_candidate_incomplete_deduction)
11645 << ParamD->getDeclName();
11646 MaybeEmitInheritedConstructorNote(S, Found);
11647 return;
11648 }
11649
11651 assert(ParamD && "no parameter found for incomplete deduction result");
11652 S.Diag(Templated->getLocation(),
11653 diag::note_ovl_candidate_incomplete_deduction_pack)
11654 << ParamD->getDeclName()
11655 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11656 << *DeductionFailure.getFirstArg();
11657 MaybeEmitInheritedConstructorNote(S, Found);
11658 return;
11659 }
11660
11662 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11663 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11664
11665 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11666
11667 // Param will have been canonicalized, but it should just be a
11668 // qualified version of ParamD, so move the qualifiers to that.
11670 Qs.strip(Param);
11671 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11672 assert(S.Context.hasSameType(Param, NonCanonParam));
11673
11674 // Arg has also been canonicalized, but there's nothing we can do
11675 // about that. It also doesn't matter as much, because it won't
11676 // have any template parameters in it (because deduction isn't
11677 // done on dependent types).
11678 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11679
11680 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11681 << ParamD->getDeclName() << Arg << NonCanonParam;
11682 MaybeEmitInheritedConstructorNote(S, Found);
11683 return;
11684 }
11685
11687 assert(ParamD && "no parameter found for inconsistent deduction result");
11688 int which = 0;
11689 if (isa<TemplateTypeParmDecl>(ParamD))
11690 which = 0;
11691 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11692 // Deduction might have failed because we deduced arguments of two
11693 // different types for a non-type template parameter.
11694 // FIXME: Use a different TDK value for this.
11695 QualType T1 =
11696 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11697 QualType T2 =
11698 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11699 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11700 S.Diag(Templated->getLocation(),
11701 diag::note_ovl_candidate_inconsistent_deduction_types)
11702 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11703 << *DeductionFailure.getSecondArg() << T2;
11704 MaybeEmitInheritedConstructorNote(S, Found);
11705 return;
11706 }
11707
11708 which = 1;
11709 } else {
11710 which = 2;
11711 }
11712
11713 // Tweak the diagnostic if the problem is that we deduced packs of
11714 // different arities. We'll print the actual packs anyway in case that
11715 // includes additional useful information.
11716 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11717 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11718 DeductionFailure.getFirstArg()->pack_size() !=
11719 DeductionFailure.getSecondArg()->pack_size()) {
11720 which = 3;
11721 }
11722
11723 S.Diag(Templated->getLocation(),
11724 diag::note_ovl_candidate_inconsistent_deduction)
11725 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11726 << *DeductionFailure.getSecondArg();
11727 MaybeEmitInheritedConstructorNote(S, Found);
11728 return;
11729 }
11730
11732 assert(ParamD && "no parameter found for invalid explicit arguments");
11733 if (ParamD->getDeclName())
11734 S.Diag(Templated->getLocation(),
11735 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11736 << ParamD->getDeclName();
11737 else {
11738 int index = 0;
11739 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11740 index = TTP->getIndex();
11741 else if (NonTypeTemplateParmDecl *NTTP
11742 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11743 index = NTTP->getIndex();
11744 else
11745 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11746 S.Diag(Templated->getLocation(),
11747 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11748 << (index + 1);
11749 }
11750 MaybeEmitInheritedConstructorNote(S, Found);
11751 return;
11752
11754 // Format the template argument list into the argument string.
11755 SmallString<128> TemplateArgString;
11756 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11757 TemplateArgString = " ";
11758 TemplateArgString += S.getTemplateArgumentBindingsText(
11759 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11760 if (TemplateArgString.size() == 1)
11761 TemplateArgString.clear();
11762 S.Diag(Templated->getLocation(),
11763 diag::note_ovl_candidate_unsatisfied_constraints)
11764 << TemplateArgString;
11765
11767 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11768 return;
11769 }
11772 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11773 return;
11774
11776 S.Diag(Templated->getLocation(),
11777 diag::note_ovl_candidate_instantiation_depth);
11778 MaybeEmitInheritedConstructorNote(S, Found);
11779 return;
11780
11782 // Format the template argument list into the argument string.
11783 SmallString<128> TemplateArgString;
11784 if (TemplateArgumentList *Args =
11785 DeductionFailure.getTemplateArgumentList()) {
11786 TemplateArgString = " ";
11787 TemplateArgString += S.getTemplateArgumentBindingsText(
11788 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11789 if (TemplateArgString.size() == 1)
11790 TemplateArgString.clear();
11791 }
11792
11793 // If this candidate was disabled by enable_if, say so.
11794 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11795 if (PDiag && PDiag->second.getDiagID() ==
11796 diag::err_typename_nested_not_found_enable_if) {
11797 // FIXME: Use the source range of the condition, and the fully-qualified
11798 // name of the enable_if template. These are both present in PDiag.
11799 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11800 << "'enable_if'" << TemplateArgString;
11801 return;
11802 }
11803
11804 // We found a specific requirement that disabled the enable_if.
11805 if (PDiag && PDiag->second.getDiagID() ==
11806 diag::err_typename_nested_not_found_requirement) {
11807 S.Diag(Templated->getLocation(),
11808 diag::note_ovl_candidate_disabled_by_requirement)
11809 << PDiag->second.getStringArg(0) << TemplateArgString;
11810 return;
11811 }
11812
11813 // Format the SFINAE diagnostic into the argument string.
11814 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11815 // formatted message in another diagnostic.
11816 SmallString<128> SFINAEArgString;
11817 SourceRange R;
11818 if (PDiag) {
11819 SFINAEArgString = ": ";
11820 R = SourceRange(PDiag->first, PDiag->first);
11821 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11822 }
11823
11824 S.Diag(Templated->getLocation(),
11825 diag::note_ovl_candidate_substitution_failure)
11826 << TemplateArgString << SFINAEArgString << R;
11827 MaybeEmitInheritedConstructorNote(S, Found);
11828 return;
11829 }
11830
11833 // Format the template argument list into the argument string.
11834 SmallString<128> TemplateArgString;
11835 if (TemplateArgumentList *Args =
11836 DeductionFailure.getTemplateArgumentList()) {
11837 TemplateArgString = " ";
11838 TemplateArgString += S.getTemplateArgumentBindingsText(
11839 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11840 if (TemplateArgString.size() == 1)
11841 TemplateArgString.clear();
11842 }
11843
11844 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11845 << (*DeductionFailure.getCallArgIndex() + 1)
11846 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11847 << TemplateArgString
11848 << (DeductionFailure.getResult() ==
11850 break;
11851 }
11852
11854 // FIXME: Provide a source location to indicate what we couldn't match.
11855 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11856 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11857 if (FirstTA.getKind() == TemplateArgument::Template &&
11858 SecondTA.getKind() == TemplateArgument::Template) {
11859 TemplateName FirstTN = FirstTA.getAsTemplate();
11860 TemplateName SecondTN = SecondTA.getAsTemplate();
11861 if (FirstTN.getKind() == TemplateName::Template &&
11862 SecondTN.getKind() == TemplateName::Template) {
11863 if (FirstTN.getAsTemplateDecl()->getName() ==
11864 SecondTN.getAsTemplateDecl()->getName()) {
11865 // FIXME: This fixes a bad diagnostic where both templates are named
11866 // the same. This particular case is a bit difficult since:
11867 // 1) It is passed as a string to the diagnostic printer.
11868 // 2) The diagnostic printer only attempts to find a better
11869 // name for types, not decls.
11870 // Ideally, this should folded into the diagnostic printer.
11871 S.Diag(Templated->getLocation(),
11872 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11873 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11874 return;
11875 }
11876 }
11877 }
11878
11879 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11880 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11881 return;
11882
11883 // FIXME: For generic lambda parameters, check if the function is a lambda
11884 // call operator, and if so, emit a prettier and more informative
11885 // diagnostic that mentions 'auto' and lambda in addition to
11886 // (or instead of?) the canonical template type parameters.
11887 S.Diag(Templated->getLocation(),
11888 diag::note_ovl_candidate_non_deduced_mismatch)
11889 << FirstTA << SecondTA;
11890 return;
11891 }
11892 // TODO: diagnose these individually, then kill off
11893 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11895 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11896 MaybeEmitInheritedConstructorNote(S, Found);
11897 return;
11899 S.Diag(Templated->getLocation(),
11900 diag::note_cuda_ovl_candidate_target_mismatch);
11901 return;
11902 }
11903}
11904
11905/// Diagnose a failed template-argument deduction, for function calls.
11907 unsigned NumArgs,
11908 bool TakingCandidateAddress) {
11909 assert(Cand->Function && "Candidate must be a function");
11910 FunctionDecl *Fn = Cand->Function;
11914 if (CheckArityMismatch(S, Cand, NumArgs))
11915 return;
11916 }
11917 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11918 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11919}
11920
11921/// CUDA: diagnose an invalid call across targets.
11923 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11924 assert(Cand->Function && "Candidate must be a Function.");
11925 FunctionDecl *Callee = Cand->Function;
11926
11927 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11928 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11929
11930 std::string FnDesc;
11931 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11932 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11933 Cand->getRewriteKind(), FnDesc);
11934
11935 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11936 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11937 << FnDesc /* Ignored */
11938 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11939
11940 // This could be an implicit constructor for which we could not infer the
11941 // target due to a collsion. Diagnose that case.
11942 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11943 if (Meth != nullptr && Meth->isImplicit()) {
11944 CXXRecordDecl *ParentClass = Meth->getParent();
11946
11947 switch (FnKindPair.first) {
11948 default:
11949 return;
11950 case oc_implicit_default_constructor:
11952 break;
11953 case oc_implicit_copy_constructor:
11955 break;
11956 case oc_implicit_move_constructor:
11958 break;
11959 case oc_implicit_copy_assignment:
11961 break;
11962 case oc_implicit_move_assignment:
11964 break;
11965 };
11966
11967 bool ConstRHS = false;
11968 if (Meth->getNumParams()) {
11969 if (const ReferenceType *RT =
11970 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11971 ConstRHS = RT->getPointeeType().isConstQualified();
11972 }
11973 }
11974
11975 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11976 /* ConstRHS */ ConstRHS,
11977 /* Diagnose */ true);
11978 }
11979}
11980
11982 assert(Cand->Function && "Candidate must be a function");
11983 FunctionDecl *Callee = Cand->Function;
11984 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11985
11986 S.Diag(Callee->getLocation(),
11987 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11988 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11989}
11990
11992 assert(Cand->Function && "Candidate must be a function");
11993 FunctionDecl *Fn = Cand->Function;
11995 assert(ES.isExplicit() && "not an explicit candidate");
11996
11997 unsigned Kind;
11998 switch (Fn->getDeclKind()) {
11999 case Decl::Kind::CXXConstructor:
12000 Kind = 0;
12001 break;
12002 case Decl::Kind::CXXConversion:
12003 Kind = 1;
12004 break;
12005 case Decl::Kind::CXXDeductionGuide:
12006 Kind = Fn->isImplicit() ? 0 : 2;
12007 break;
12008 default:
12009 llvm_unreachable("invalid Decl");
12010 }
12011
12012 // Note the location of the first (in-class) declaration; a redeclaration
12013 // (particularly an out-of-class definition) will typically lack the
12014 // 'explicit' specifier.
12015 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12016 FunctionDecl *First = Fn->getFirstDecl();
12017 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12018 First = Pattern->getFirstDecl();
12019
12020 S.Diag(First->getLocation(),
12021 diag::note_ovl_candidate_explicit)
12022 << Kind << (ES.getExpr() ? 1 : 0)
12023 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12024}
12025
12027 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12028 if (!DG)
12029 return;
12030 TemplateDecl *OriginTemplate =
12032 // We want to always print synthesized deduction guides for type aliases.
12033 // They would retain the explicit bit of the corresponding constructor.
12034 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12035 return;
12036 std::string FunctionProto;
12037 llvm::raw_string_ostream OS(FunctionProto);
12038 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12039 if (!Template) {
12040 // This also could be an instantiation. Find out the primary template.
12041 FunctionDecl *Pattern =
12042 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12043 if (!Pattern) {
12044 // The implicit deduction guide is built on an explicit non-template
12045 // deduction guide. Currently, this might be the case only for type
12046 // aliases.
12047 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12048 // gets merged.
12049 assert(OriginTemplate->isTypeAlias() &&
12050 "Non-template implicit deduction guides are only possible for "
12051 "type aliases");
12052 DG->print(OS);
12053 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12054 << FunctionProto;
12055 return;
12056 }
12057 Template = Pattern->getDescribedFunctionTemplate();
12058 assert(Template && "Cannot find the associated function template of "
12059 "CXXDeductionGuideDecl?");
12060 }
12061 Template->print(OS);
12062 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12063 << FunctionProto;
12064}
12065
12066/// Generates a 'note' diagnostic for an overload candidate. We've
12067/// already generated a primary error at the call site.
12068///
12069/// It really does need to be a single diagnostic with its caret
12070/// pointed at the candidate declaration. Yes, this creates some
12071/// major challenges of technical writing. Yes, this makes pointing
12072/// out problems with specific arguments quite awkward. It's still
12073/// better than generating twenty screens of text for every failed
12074/// overload.
12075///
12076/// It would be great to be able to express per-candidate problems
12077/// more richly for those diagnostic clients that cared, but we'd
12078/// still have to be just as careful with the default diagnostics.
12079/// \param CtorDestAS Addr space of object being constructed (for ctor
12080/// candidates only).
12082 unsigned NumArgs,
12083 bool TakingCandidateAddress,
12084 LangAS CtorDestAS = LangAS::Default) {
12085 assert(Cand->Function && "Candidate must be a function");
12086 FunctionDecl *Fn = Cand->Function;
12088 return;
12089
12090 // There is no physical candidate declaration to point to for OpenCL builtins.
12091 // Except for failed conversions, the notes are identical for each candidate,
12092 // so do not generate such notes.
12093 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12095 return;
12096
12097 // Skip implicit member functions when trying to resolve
12098 // the address of a an overload set for a function pointer.
12099 if (Cand->TookAddressOfOverload &&
12100 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12101 return;
12102
12103 // Note deleted candidates, but only if they're viable.
12104 if (Cand->Viable) {
12105 if (Fn->isDeleted()) {
12106 std::string FnDesc;
12107 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12108 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12109 Cand->getRewriteKind(), FnDesc);
12110
12111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12112 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12113 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12114 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12115 return;
12116 }
12117
12118 // We don't really have anything else to say about viable candidates.
12119 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12120 return;
12121 }
12122
12123 // If this is a synthesized deduction guide we're deducing against, add a note
12124 // for it. These deduction guides are not explicitly spelled in the source
12125 // code, so simply printing a deduction failure note mentioning synthesized
12126 // template parameters or pointing to the header of the surrounding RecordDecl
12127 // would be confusing.
12128 //
12129 // We prefer adding such notes at the end of the deduction failure because
12130 // duplicate code snippets appearing in the diagnostic would likely become
12131 // noisy.
12132 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12133
12134 switch (Cand->FailureKind) {
12137 return DiagnoseArityMismatch(S, Cand, NumArgs);
12138
12140 return DiagnoseBadDeduction(S, Cand, NumArgs,
12141 TakingCandidateAddress);
12142
12144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12145 << (Fn->getPrimaryTemplate() ? 1 : 0);
12146 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12147 return;
12148 }
12149
12151 Qualifiers QualsForPrinting;
12152 QualsForPrinting.setAddressSpace(CtorDestAS);
12153 S.Diag(Fn->getLocation(),
12154 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12155 << QualsForPrinting;
12156 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12157 return;
12158 }
12159
12163 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12164
12166 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12167 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12168 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12169 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12170
12171 // FIXME: this currently happens when we're called from SemaInit
12172 // when user-conversion overload fails. Figure out how to handle
12173 // those conditions and diagnose them well.
12174 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12175 }
12176
12178 return DiagnoseBadTarget(S, Cand);
12179
12180 case ovl_fail_enable_if:
12181 return DiagnoseFailedEnableIfAttr(S, Cand);
12182
12183 case ovl_fail_explicit:
12184 return DiagnoseFailedExplicitSpec(S, Cand);
12185
12187 // It's generally not interesting to note copy/move constructors here.
12188 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12189 return;
12190 S.Diag(Fn->getLocation(),
12191 diag::note_ovl_candidate_inherited_constructor_slice)
12192 << (Fn->getPrimaryTemplate() ? 1 : 0)
12193 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12194 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12195 return;
12196
12198 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12199 (void)Available;
12200 assert(!Available);
12201 break;
12202 }
12204 // Do nothing, these should simply be ignored.
12205 break;
12206
12208 std::string FnDesc;
12209 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12210 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12211 Cand->getRewriteKind(), FnDesc);
12212
12213 S.Diag(Fn->getLocation(),
12214 diag::note_ovl_candidate_constraints_not_satisfied)
12215 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12216 << FnDesc /* Ignored */;
12217 ConstraintSatisfaction Satisfaction;
12218 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12219 break;
12220 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12221 }
12222 }
12223}
12224
12227 return;
12228
12229 // Desugar the type of the surrogate down to a function type,
12230 // retaining as many typedefs as possible while still showing
12231 // the function type (and, therefore, its parameter types).
12232 QualType FnType = Cand->Surrogate->getConversionType();
12233 bool isLValueReference = false;
12234 bool isRValueReference = false;
12235 bool isPointer = false;
12236 if (const LValueReferenceType *FnTypeRef =
12237 FnType->getAs<LValueReferenceType>()) {
12238 FnType = FnTypeRef->getPointeeType();
12239 isLValueReference = true;
12240 } else if (const RValueReferenceType *FnTypeRef =
12241 FnType->getAs<RValueReferenceType>()) {
12242 FnType = FnTypeRef->getPointeeType();
12243 isRValueReference = true;
12244 }
12245 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12246 FnType = FnTypePtr->getPointeeType();
12247 isPointer = true;
12248 }
12249 // Desugar down to a function type.
12250 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12251 // Reconstruct the pointer/reference as appropriate.
12252 if (isPointer) FnType = S.Context.getPointerType(FnType);
12253 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12254 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12255
12256 if (!Cand->Viable &&
12258 S.Diag(Cand->Surrogate->getLocation(),
12259 diag::note_ovl_surrogate_constraints_not_satisfied)
12260 << Cand->Surrogate;
12261 ConstraintSatisfaction Satisfaction;
12262 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12263 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12264 } else {
12265 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12266 << FnType;
12267 }
12268}
12269
12270static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12271 SourceLocation OpLoc,
12272 OverloadCandidate *Cand) {
12273 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12274 std::string TypeStr("operator");
12275 TypeStr += Opc;
12276 TypeStr += "(";
12277 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12278 if (Cand->Conversions.size() == 1) {
12279 TypeStr += ")";
12280 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12281 } else {
12282 TypeStr += ", ";
12283 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12284 TypeStr += ")";
12285 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12286 }
12287}
12288
12290 OverloadCandidate *Cand) {
12291 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12292 if (ICS.isBad()) break; // all meaningless after first invalid
12293 if (!ICS.isAmbiguous()) continue;
12294
12296 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12297 }
12298}
12299
12301 if (Cand->Function)
12302 return Cand->Function->getLocation();
12303 if (Cand->IsSurrogate)
12304 return Cand->Surrogate->getLocation();
12305 return SourceLocation();
12306}
12307
12308static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12309 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12313 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12314
12318 return 1;
12319
12322 return 2;
12323
12331 return 3;
12332
12334 return 4;
12335
12337 return 5;
12338
12341 return 6;
12342 }
12343 llvm_unreachable("Unhandled deduction result");
12344}
12345
12346namespace {
12347
12348struct CompareOverloadCandidatesForDisplay {
12349 Sema &S;
12351 size_t NumArgs;
12353
12354 CompareOverloadCandidatesForDisplay(
12355 Sema &S, SourceLocation Loc, size_t NArgs,
12357 : S(S), NumArgs(NArgs), CSK(CSK) {}
12358
12359 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12360 // If there are too many or too few arguments, that's the high-order bit we
12361 // want to sort by, even if the immediate failure kind was something else.
12362 if (C->FailureKind == ovl_fail_too_many_arguments ||
12363 C->FailureKind == ovl_fail_too_few_arguments)
12364 return static_cast<OverloadFailureKind>(C->FailureKind);
12365
12366 if (C->Function) {
12367 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12369 if (NumArgs < C->Function->getMinRequiredArguments())
12371 }
12372
12373 return static_cast<OverloadFailureKind>(C->FailureKind);
12374 }
12375
12376 bool operator()(const OverloadCandidate *L,
12377 const OverloadCandidate *R) {
12378 // Fast-path this check.
12379 if (L == R) return false;
12380
12381 // Order first by viability.
12382 if (L->Viable) {
12383 if (!R->Viable) return true;
12384
12385 if (int Ord = CompareConversions(*L, *R))
12386 return Ord < 0;
12387 // Use other tie breakers.
12388 } else if (R->Viable)
12389 return false;
12390
12391 assert(L->Viable == R->Viable);
12392
12393 // Criteria by which we can sort non-viable candidates:
12394 if (!L->Viable) {
12395 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12396 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12397
12398 // 1. Arity mismatches come after other candidates.
12399 if (LFailureKind == ovl_fail_too_many_arguments ||
12400 LFailureKind == ovl_fail_too_few_arguments) {
12401 if (RFailureKind == ovl_fail_too_many_arguments ||
12402 RFailureKind == ovl_fail_too_few_arguments) {
12403 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12404 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12405 if (LDist == RDist) {
12406 if (LFailureKind == RFailureKind)
12407 // Sort non-surrogates before surrogates.
12408 return !L->IsSurrogate && R->IsSurrogate;
12409 // Sort candidates requiring fewer parameters than there were
12410 // arguments given after candidates requiring more parameters
12411 // than there were arguments given.
12412 return LFailureKind == ovl_fail_too_many_arguments;
12413 }
12414 return LDist < RDist;
12415 }
12416 return false;
12417 }
12418 if (RFailureKind == ovl_fail_too_many_arguments ||
12419 RFailureKind == ovl_fail_too_few_arguments)
12420 return true;
12421
12422 // 2. Bad conversions come first and are ordered by the number
12423 // of bad conversions and quality of good conversions.
12424 if (LFailureKind == ovl_fail_bad_conversion) {
12425 if (RFailureKind != ovl_fail_bad_conversion)
12426 return true;
12427
12428 // The conversion that can be fixed with a smaller number of changes,
12429 // comes first.
12430 unsigned numLFixes = L->Fix.NumConversionsFixed;
12431 unsigned numRFixes = R->Fix.NumConversionsFixed;
12432 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12433 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12434 if (numLFixes != numRFixes) {
12435 return numLFixes < numRFixes;
12436 }
12437
12438 // If there's any ordering between the defined conversions...
12439 if (int Ord = CompareConversions(*L, *R))
12440 return Ord < 0;
12441 } else if (RFailureKind == ovl_fail_bad_conversion)
12442 return false;
12443
12444 if (LFailureKind == ovl_fail_bad_deduction) {
12445 if (RFailureKind != ovl_fail_bad_deduction)
12446 return true;
12447
12449 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12450 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12451 if (LRank != RRank)
12452 return LRank < RRank;
12453 }
12454 } else if (RFailureKind == ovl_fail_bad_deduction)
12455 return false;
12456
12457 // TODO: others?
12458 }
12459
12460 // Sort everything else by location.
12463
12464 // Put candidates without locations (e.g. builtins) at the end.
12465 if (LLoc.isValid() && RLoc.isValid())
12466 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12467 if (LLoc.isValid() && !RLoc.isValid())
12468 return true;
12469 if (RLoc.isValid() && !LLoc.isValid())
12470 return false;
12471 assert(!LLoc.isValid() && !RLoc.isValid());
12472 // For builtins and other functions without locations, fallback to the order
12473 // in which they were added into the candidate set.
12474 return L < R;
12475 }
12476
12477private:
12478 struct ConversionSignals {
12479 unsigned KindRank = 0;
12481
12482 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12483 ConversionSignals Sig;
12484 Sig.KindRank = Seq.getKindRank();
12485 if (Seq.isStandard())
12486 Sig.Rank = Seq.Standard.getRank();
12487 else if (Seq.isUserDefined())
12488 Sig.Rank = Seq.UserDefined.After.getRank();
12489 // We intend StaticObjectArgumentConversion to compare the same as
12490 // StandardConversion with ICR_ExactMatch rank.
12491 return Sig;
12492 }
12493
12494 static ConversionSignals ForObjectArgument() {
12495 // We intend StaticObjectArgumentConversion to compare the same as
12496 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12497 return {};
12498 }
12499 };
12500
12501 // Returns -1 if conversions in L are considered better.
12502 // 0 if they are considered indistinguishable.
12503 // 1 if conversions in R are better.
12504 int CompareConversions(const OverloadCandidate &L,
12505 const OverloadCandidate &R) {
12506 // We cannot use `isBetterOverloadCandidate` because it is defined
12507 // according to the C++ standard and provides a partial order, but we need
12508 // a total order as this function is used in sort.
12509 assert(L.Conversions.size() == R.Conversions.size());
12510 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12511 auto LS = L.IgnoreObjectArgument && I == 0
12512 ? ConversionSignals::ForObjectArgument()
12513 : ConversionSignals::ForSequence(L.Conversions[I]);
12514 auto RS = R.IgnoreObjectArgument
12515 ? ConversionSignals::ForObjectArgument()
12516 : ConversionSignals::ForSequence(R.Conversions[I]);
12517 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12518 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12519 ? -1
12520 : 1;
12521 }
12522 // FIXME: find a way to compare templates for being more or less
12523 // specialized that provides a strict weak ordering.
12524 return 0;
12525 }
12526};
12527}
12528
12529/// CompleteNonViableCandidate - Normally, overload resolution only
12530/// computes up to the first bad conversion. Produces the FixIt set if
12531/// possible.
12532static void
12534 ArrayRef<Expr *> Args,
12536 assert(!Cand->Viable);
12537
12538 // Don't do anything on failures other than bad conversion.
12540 return;
12541
12542 // We only want the FixIts if all the arguments can be corrected.
12543 bool Unfixable = false;
12544 // Use a implicit copy initialization to check conversion fixes.
12546
12547 // Attempt to fix the bad conversion.
12548 unsigned ConvCount = Cand->Conversions.size();
12549 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12550 ++ConvIdx) {
12551 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12552 if (Cand->Conversions[ConvIdx].isInitialized() &&
12553 Cand->Conversions[ConvIdx].isBad()) {
12554 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12555 break;
12556 }
12557 }
12558
12559 // FIXME: this should probably be preserved from the overload
12560 // operation somehow.
12561 bool SuppressUserConversions = false;
12562
12563 unsigned ConvIdx = 0;
12564 unsigned ArgIdx = 0;
12565 ArrayRef<QualType> ParamTypes;
12566 bool Reversed = Cand->isReversed();
12567
12568 if (Cand->IsSurrogate) {
12569 QualType ConvType
12571 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12572 ConvType = ConvPtrType->getPointeeType();
12573 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12574 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12575 ConvIdx = 1;
12576 } else if (Cand->Function) {
12577 ParamTypes =
12578 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12579 if (isa<CXXMethodDecl>(Cand->Function) &&
12580 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12581 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12582 ConvIdx = 1;
12584 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12586 OO_Subscript)
12587 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12588 ArgIdx = 1;
12589 }
12590 } else {
12591 // Builtin operator.
12592 assert(ConvCount <= 3);
12593 ParamTypes = Cand->BuiltinParamTypes;
12594 }
12595
12596 // Fill in the rest of the conversions.
12597 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12598 ConvIdx != ConvCount;
12599 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12600 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12601 if (Cand->Conversions[ConvIdx].isInitialized()) {
12602 // We've already checked this conversion.
12603 } else if (ParamIdx < ParamTypes.size()) {
12604 if (ParamTypes[ParamIdx]->isDependentType())
12605 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12606 Args[ArgIdx]->getType());
12607 else {
12608 Cand->Conversions[ConvIdx] =
12609 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12610 SuppressUserConversions,
12611 /*InOverloadResolution=*/true,
12612 /*AllowObjCWritebackConversion=*/
12613 S.getLangOpts().ObjCAutoRefCount);
12614 // Store the FixIt in the candidate if it exists.
12615 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12616 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12617 }
12618 } else
12619 Cand->Conversions[ConvIdx].setEllipsis();
12620 }
12621}
12622
12625 SourceLocation OpLoc,
12626 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12627 // Sort the candidates by viability and position. Sorting directly would
12628 // be prohibitive, so we make a set of pointers and sort those.
12630 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12631 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12632 if (!Filter(*Cand))
12633 continue;
12634 switch (OCD) {
12635 case OCD_AllCandidates:
12636 if (!Cand->Viable) {
12637 if (!Cand->Function && !Cand->IsSurrogate) {
12638 // This a non-viable builtin candidate. We do not, in general,
12639 // want to list every possible builtin candidate.
12640 continue;
12641 }
12642 CompleteNonViableCandidate(S, Cand, Args, Kind);
12643 }
12644 break;
12645
12647 if (!Cand->Viable)
12648 continue;
12649 break;
12650
12652 if (!Cand->Best)
12653 continue;
12654 break;
12655 }
12656
12657 Cands.push_back(Cand);
12658 }
12659
12660 llvm::stable_sort(
12661 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12662
12663 return Cands;
12664}
12665
12667 SourceLocation OpLoc) {
12668 bool DeferHint = false;
12669 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12670 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12671 // host device candidates.
12672 auto WrongSidedCands =
12673 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12674 return (Cand.Viable == false &&
12675 Cand.FailureKind == ovl_fail_bad_target) ||
12676 (Cand.Function &&
12677 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12678 Cand.Function->template hasAttr<CUDADeviceAttr>());
12679 });
12680 DeferHint = !WrongSidedCands.empty();
12681 }
12682 return DeferHint;
12683}
12684
12685/// When overload resolution fails, prints diagnostic messages containing the
12686/// candidates in the candidate set.
12689 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12690 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12691
12692 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12693
12694 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12695
12696 // In WebAssembly we don't want to emit further diagnostics if a table is
12697 // passed as an argument to a function.
12698 bool NoteCands = true;
12699 for (const Expr *Arg : Args) {
12700 if (Arg->getType()->isWebAssemblyTableType())
12701 NoteCands = false;
12702 }
12703
12704 if (NoteCands)
12705 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12706
12707 if (OCD == OCD_AmbiguousCandidates)
12709}
12710
12713 StringRef Opc, SourceLocation OpLoc) {
12714 bool ReportedAmbiguousConversions = false;
12715
12716 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12717 unsigned CandsShown = 0;
12718 auto I = Cands.begin(), E = Cands.end();
12719 for (; I != E; ++I) {
12720 OverloadCandidate *Cand = *I;
12721
12722 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12723 ShowOverloads == Ovl_Best) {
12724 break;
12725 }
12726 ++CandsShown;
12727
12728 if (Cand->Function)
12729 NoteFunctionCandidate(S, Cand, Args.size(),
12730 /*TakingCandidateAddress=*/false, DestAS);
12731 else if (Cand->IsSurrogate)
12732 NoteSurrogateCandidate(S, Cand);
12733 else {
12734 assert(Cand->Viable &&
12735 "Non-viable built-in candidates are not added to Cands.");
12736 // Generally we only see ambiguities including viable builtin
12737 // operators if overload resolution got screwed up by an
12738 // ambiguous user-defined conversion.
12739 //
12740 // FIXME: It's quite possible for different conversions to see
12741 // different ambiguities, though.
12742 if (!ReportedAmbiguousConversions) {
12743 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12744 ReportedAmbiguousConversions = true;
12745 }
12746
12747 // If this is a viable builtin, print it.
12748 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12749 }
12750 }
12751
12752 // Inform S.Diags that we've shown an overload set with N elements. This may
12753 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12754 S.Diags.overloadCandidatesShown(CandsShown);
12755
12756 if (I != E)
12757 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12758 shouldDeferDiags(S, Args, OpLoc))
12759 << int(E - I);
12760}
12761
12762static SourceLocation
12764 return Cand->Specialization ? Cand->Specialization->getLocation()
12765 : SourceLocation();
12766}
12767
12768namespace {
12769struct CompareTemplateSpecCandidatesForDisplay {
12770 Sema &S;
12771 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12772
12773 bool operator()(const TemplateSpecCandidate *L,
12774 const TemplateSpecCandidate *R) {
12775 // Fast-path this check.
12776 if (L == R)
12777 return false;
12778
12779 // Assuming that both candidates are not matches...
12780
12781 // Sort by the ranking of deduction failures.
12785
12786 // Sort everything else by location.
12789
12790 // Put candidates without locations (e.g. builtins) at the end.
12791 if (LLoc.isInvalid())
12792 return false;
12793 if (RLoc.isInvalid())
12794 return true;
12795
12796 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12797 }
12798};
12799}
12800
12801/// Diagnose a template argument deduction failure.
12802/// We are treating these failures as overload failures due to bad
12803/// deductions.
12805 bool ForTakingAddress) {
12806 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12807 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12808}
12809
12810void TemplateSpecCandidateSet::destroyCandidates() {
12811 for (iterator i = begin(), e = end(); i != e; ++i) {
12812 i->DeductionFailure.Destroy();
12813 }
12814}
12815
12817 destroyCandidates();
12818 Candidates.clear();
12819}
12820
12821/// NoteCandidates - When no template specialization match is found, prints
12822/// diagnostic messages containing the non-matching specializations that form
12823/// the candidate set.
12824/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12825/// OCD == OCD_AllCandidates and Cand->Viable == false.
12827 // Sort the candidates by position (assuming no candidate is a match).
12828 // Sorting directly would be prohibitive, so we make a set of pointers
12829 // and sort those.
12831 Cands.reserve(size());
12832 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12833 if (Cand->Specialization)
12834 Cands.push_back(Cand);
12835 // Otherwise, this is a non-matching builtin candidate. We do not,
12836 // in general, want to list every possible builtin candidate.
12837 }
12838
12839 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12840
12841 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12842 // for generalization purposes (?).
12843 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12844
12846 unsigned CandsShown = 0;
12847 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12848 TemplateSpecCandidate *Cand = *I;
12849
12850 // Set an arbitrary limit on the number of candidates we'll spam
12851 // the user with. FIXME: This limit should depend on details of the
12852 // candidate list.
12853 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12854 break;
12855 ++CandsShown;
12856
12857 assert(Cand->Specialization &&
12858 "Non-matching built-in candidates are not added to Cands.");
12859 Cand->NoteDeductionFailure(S, ForTakingAddress);
12860 }
12861
12862 if (I != E)
12863 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12864}
12865
12866// [PossiblyAFunctionType] --> [Return]
12867// NonFunctionType --> NonFunctionType
12868// R (A) --> R(A)
12869// R (*)(A) --> R (A)
12870// R (&)(A) --> R (A)
12871// R (S::*)(A) --> R (A)
12873 QualType Ret = PossiblyAFunctionType;
12874 if (const PointerType *ToTypePtr =
12875 PossiblyAFunctionType->getAs<PointerType>())
12876 Ret = ToTypePtr->getPointeeType();
12877 else if (const ReferenceType *ToTypeRef =
12878 PossiblyAFunctionType->getAs<ReferenceType>())
12879 Ret = ToTypeRef->getPointeeType();
12880 else if (const MemberPointerType *MemTypePtr =
12881 PossiblyAFunctionType->getAs<MemberPointerType>())
12882 Ret = MemTypePtr->getPointeeType();
12883 Ret =
12884 Context.getCanonicalType(Ret).getUnqualifiedType();
12885 return Ret;
12886}
12887
12889 bool Complain = true) {
12890 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12891 S.DeduceReturnType(FD, Loc, Complain))
12892 return true;
12893
12894 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12895 if (S.getLangOpts().CPlusPlus17 &&
12896 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12897 !S.ResolveExceptionSpec(Loc, FPT))
12898 return true;
12899
12900 return false;
12901}
12902
12903namespace {
12904// A helper class to help with address of function resolution
12905// - allows us to avoid passing around all those ugly parameters
12906class AddressOfFunctionResolver {
12907 Sema& S;
12908 Expr* SourceExpr;
12909 const QualType& TargetType;
12910 QualType TargetFunctionType; // Extracted function type from target type
12911
12912 bool Complain;
12913 //DeclAccessPair& ResultFunctionAccessPair;
12914 ASTContext& Context;
12915
12916 bool TargetTypeIsNonStaticMemberFunction;
12917 bool FoundNonTemplateFunction;
12918 bool StaticMemberFunctionFromBoundPointer;
12919 bool HasComplained;
12920
12921 OverloadExpr::FindResult OvlExprInfo;
12922 OverloadExpr *OvlExpr;
12923 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12925 TemplateSpecCandidateSet FailedCandidates;
12926
12927public:
12928 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12929 const QualType &TargetType, bool Complain)
12930 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12931 Complain(Complain), Context(S.getASTContext()),
12932 TargetTypeIsNonStaticMemberFunction(
12933 !!TargetType->getAs<MemberPointerType>()),
12934 FoundNonTemplateFunction(false),
12935 StaticMemberFunctionFromBoundPointer(false),
12936 HasComplained(false),
12937 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12938 OvlExpr(OvlExprInfo.Expression),
12939 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12940 ExtractUnqualifiedFunctionTypeFromTargetType();
12941
12942 if (TargetFunctionType->isFunctionType()) {
12943 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12944 if (!UME->isImplicitAccess() &&
12946 StaticMemberFunctionFromBoundPointer = true;
12947 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12948 DeclAccessPair dap;
12950 OvlExpr, false, &dap)) {
12951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12952 if (!Method->isStatic()) {
12953 // If the target type is a non-function type and the function found
12954 // is a non-static member function, pretend as if that was the
12955 // target, it's the only possible type to end up with.
12956 TargetTypeIsNonStaticMemberFunction = true;
12957
12958 // And skip adding the function if its not in the proper form.
12959 // We'll diagnose this due to an empty set of functions.
12960 if (!OvlExprInfo.HasFormOfMemberPointer)
12961 return;
12962 }
12963
12964 Matches.push_back(std::make_pair(dap, Fn));
12965 }
12966 return;
12967 }
12968
12969 if (OvlExpr->hasExplicitTemplateArgs())
12970 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12971
12972 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12973 // C++ [over.over]p4:
12974 // If more than one function is selected, [...]
12975 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12976 if (FoundNonTemplateFunction)
12977 EliminateAllTemplateMatches();
12978 else
12979 EliminateAllExceptMostSpecializedTemplate();
12980 }
12981 }
12982
12983 if (S.getLangOpts().CUDA && Matches.size() > 1)
12984 EliminateSuboptimalCudaMatches();
12985 }
12986
12987 bool hasComplained() const { return HasComplained; }
12988
12989private:
12990 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12991 QualType Discard;
12992 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12993 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12994 }
12995
12996 /// \return true if A is considered a better overload candidate for the
12997 /// desired type than B.
12998 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12999 // If A doesn't have exactly the correct type, we don't want to classify it
13000 // as "better" than anything else. This way, the user is required to
13001 // disambiguate for us if there are multiple candidates and no exact match.
13002 return candidateHasExactlyCorrectType(A) &&
13003 (!candidateHasExactlyCorrectType(B) ||
13004 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13005 }
13006
13007 /// \return true if we were able to eliminate all but one overload candidate,
13008 /// false otherwise.
13009 bool eliminiateSuboptimalOverloadCandidates() {
13010 // Same algorithm as overload resolution -- one pass to pick the "best",
13011 // another pass to be sure that nothing is better than the best.
13012 auto Best = Matches.begin();
13013 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13014 if (isBetterCandidate(I->second, Best->second))
13015 Best = I;
13016
13017 const FunctionDecl *BestFn = Best->second;
13018 auto IsBestOrInferiorToBest = [this, BestFn](
13019 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13020 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13021 };
13022
13023 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13024 // option, so we can potentially give the user a better error
13025 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13026 return false;
13027 Matches[0] = *Best;
13028 Matches.resize(1);
13029 return true;
13030 }
13031
13032 bool isTargetTypeAFunction() const {
13033 return TargetFunctionType->isFunctionType();
13034 }
13035
13036 // [ToType] [Return]
13037
13038 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13039 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13040 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13041 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13042 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13043 }
13044
13045 // return true if any matching specializations were found
13046 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13047 const DeclAccessPair& CurAccessFunPair) {
13048 if (CXXMethodDecl *Method
13049 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13050 // Skip non-static function templates when converting to pointer, and
13051 // static when converting to member pointer.
13052 bool CanConvertToFunctionPointer =
13053 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13054 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13055 return false;
13056 }
13057 else if (TargetTypeIsNonStaticMemberFunction)
13058 return false;
13059
13060 // C++ [over.over]p2:
13061 // If the name is a function template, template argument deduction is
13062 // done (14.8.2.2), and if the argument deduction succeeds, the
13063 // resulting template argument list is used to generate a single
13064 // function template specialization, which is added to the set of
13065 // overloaded functions considered.
13066 FunctionDecl *Specialization = nullptr;
13067 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13069 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13070 Specialization, Info, /*IsAddressOfFunction*/ true);
13071 Result != TemplateDeductionResult::Success) {
13072 // Make a note of the failed deduction for diagnostics.
13073 FailedCandidates.addCandidate()
13074 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13075 MakeDeductionFailureInfo(Context, Result, Info));
13076 return false;
13077 }
13078
13079 // Template argument deduction ensures that we have an exact match or
13080 // compatible pointer-to-function arguments that would be adjusted by ICS.
13081 // This function template specicalization works.
13083 Context.getCanonicalType(Specialization->getType()),
13084 Context.getCanonicalType(TargetFunctionType)));
13085
13087 return false;
13088
13089 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13090 return true;
13091 }
13092
13093 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13094 const DeclAccessPair& CurAccessFunPair) {
13095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13096 // Skip non-static functions when converting to pointer, and static
13097 // when converting to member pointer.
13098 bool CanConvertToFunctionPointer =
13099 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13100 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13101 return false;
13102 }
13103 else if (TargetTypeIsNonStaticMemberFunction)
13104 return false;
13105
13106 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13107 if (S.getLangOpts().CUDA) {
13108 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13109 if (!(Caller && Caller->isImplicit()) &&
13110 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13111 return false;
13112 }
13113 if (FunDecl->isMultiVersion()) {
13114 const auto *TA = FunDecl->getAttr<TargetAttr>();
13115 if (TA && !TA->isDefaultVersion())
13116 return false;
13117 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13118 if (TVA && !TVA->isDefaultVersion())
13119 return false;
13120 }
13121
13122 // If any candidate has a placeholder return type, trigger its deduction
13123 // now.
13124 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13125 Complain)) {
13126 HasComplained |= Complain;
13127 return false;
13128 }
13129
13130 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13131 return false;
13132
13133 // If we're in C, we need to support types that aren't exactly identical.
13134 if (!S.getLangOpts().CPlusPlus ||
13135 candidateHasExactlyCorrectType(FunDecl)) {
13136 Matches.push_back(std::make_pair(
13137 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13138 FoundNonTemplateFunction = true;
13139 return true;
13140 }
13141 }
13142
13143 return false;
13144 }
13145
13146 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13147 bool Ret = false;
13148
13149 // If the overload expression doesn't have the form of a pointer to
13150 // member, don't try to convert it to a pointer-to-member type.
13151 if (IsInvalidFormOfPointerToMemberFunction())
13152 return false;
13153
13154 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13155 E = OvlExpr->decls_end();
13156 I != E; ++I) {
13157 // Look through any using declarations to find the underlying function.
13158 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13159
13160 // C++ [over.over]p3:
13161 // Non-member functions and static member functions match
13162 // targets of type "pointer-to-function" or "reference-to-function."
13163 // Nonstatic member functions match targets of
13164 // type "pointer-to-member-function."
13165 // Note that according to DR 247, the containing class does not matter.
13166 if (FunctionTemplateDecl *FunctionTemplate
13167 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13168 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13169 Ret = true;
13170 }
13171 // If we have explicit template arguments supplied, skip non-templates.
13172 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13173 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13174 Ret = true;
13175 }
13176 assert(Ret || Matches.empty());
13177 return Ret;
13178 }
13179
13180 void EliminateAllExceptMostSpecializedTemplate() {
13181 // [...] and any given function template specialization F1 is
13182 // eliminated if the set contains a second function template
13183 // specialization whose function template is more specialized
13184 // than the function template of F1 according to the partial
13185 // ordering rules of 14.5.5.2.
13186
13187 // The algorithm specified above is quadratic. We instead use a
13188 // two-pass algorithm (similar to the one used to identify the
13189 // best viable function in an overload set) that identifies the
13190 // best function template (if it exists).
13191
13192 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13193 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13194 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13195
13196 // TODO: It looks like FailedCandidates does not serve much purpose
13197 // here, since the no_viable diagnostic has index 0.
13199 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13200 SourceExpr->getBeginLoc(), S.PDiag(),
13201 S.PDiag(diag::err_addr_ovl_ambiguous)
13202 << Matches[0].second->getDeclName(),
13203 S.PDiag(diag::note_ovl_candidate)
13204 << (unsigned)oc_function << (unsigned)ocs_described_template,
13205 Complain, TargetFunctionType);
13206
13207 if (Result != MatchesCopy.end()) {
13208 // Make it the first and only element
13209 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13210 Matches[0].second = cast<FunctionDecl>(*Result);
13211 Matches.resize(1);
13212 } else
13213 HasComplained |= Complain;
13214 }
13215
13216 void EliminateAllTemplateMatches() {
13217 // [...] any function template specializations in the set are
13218 // eliminated if the set also contains a non-template function, [...]
13219 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13220 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13221 ++I;
13222 else {
13223 Matches[I] = Matches[--N];
13224 Matches.resize(N);
13225 }
13226 }
13227 }
13228
13229 void EliminateSuboptimalCudaMatches() {
13230 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13231 Matches);
13232 }
13233
13234public:
13235 void ComplainNoMatchesFound() const {
13236 assert(Matches.empty());
13237 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13238 << OvlExpr->getName() << TargetFunctionType
13239 << OvlExpr->getSourceRange();
13240 if (FailedCandidates.empty())
13241 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13242 /*TakingAddress=*/true);
13243 else {
13244 // We have some deduction failure messages. Use them to diagnose
13245 // the function templates, and diagnose the non-template candidates
13246 // normally.
13247 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13248 IEnd = OvlExpr->decls_end();
13249 I != IEnd; ++I)
13250 if (FunctionDecl *Fun =
13251 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13253 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13254 /*TakingAddress=*/true);
13255 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13256 }
13257 }
13258
13259 bool IsInvalidFormOfPointerToMemberFunction() const {
13260 return TargetTypeIsNonStaticMemberFunction &&
13261 !OvlExprInfo.HasFormOfMemberPointer;
13262 }
13263
13264 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13265 // TODO: Should we condition this on whether any functions might
13266 // have matched, or is it more appropriate to do that in callers?
13267 // TODO: a fixit wouldn't hurt.
13268 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13269 << TargetType << OvlExpr->getSourceRange();
13270 }
13271
13272 bool IsStaticMemberFunctionFromBoundPointer() const {
13273 return StaticMemberFunctionFromBoundPointer;
13274 }
13275
13276 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13277 S.Diag(OvlExpr->getBeginLoc(),
13278 diag::err_invalid_form_pointer_member_function)
13279 << OvlExpr->getSourceRange();
13280 }
13281
13282 void ComplainOfInvalidConversion() const {
13283 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13284 << OvlExpr->getName() << TargetType;
13285 }
13286
13287 void ComplainMultipleMatchesFound() const {
13288 assert(Matches.size() > 1);
13289 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13290 << OvlExpr->getName() << OvlExpr->getSourceRange();
13291 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13292 /*TakingAddress=*/true);
13293 }
13294
13295 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13296
13297 int getNumMatches() const { return Matches.size(); }
13298
13299 FunctionDecl* getMatchingFunctionDecl() const {
13300 if (Matches.size() != 1) return nullptr;
13301 return Matches[0].second;
13302 }
13303
13304 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13305 if (Matches.size() != 1) return nullptr;
13306 return &Matches[0].first;
13307 }
13308};
13309}
13310
13313 QualType TargetType,
13314 bool Complain,
13315 DeclAccessPair &FoundResult,
13316 bool *pHadMultipleCandidates) {
13317 assert(AddressOfExpr->getType() == Context.OverloadTy);
13318
13319 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13320 Complain);
13321 int NumMatches = Resolver.getNumMatches();
13322 FunctionDecl *Fn = nullptr;
13323 bool ShouldComplain = Complain && !Resolver.hasComplained();
13324 if (NumMatches == 0 && ShouldComplain) {
13325 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13326 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13327 else
13328 Resolver.ComplainNoMatchesFound();
13329 }
13330 else if (NumMatches > 1 && ShouldComplain)
13331 Resolver.ComplainMultipleMatchesFound();
13332 else if (NumMatches == 1) {
13333 Fn = Resolver.getMatchingFunctionDecl();
13334 assert(Fn);
13335 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13336 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13337 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13338 if (Complain) {
13339 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13340 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13341 else
13342 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13343 }
13344 }
13345
13346 if (pHadMultipleCandidates)
13347 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13348 return Fn;
13349}
13350
13354 OverloadExpr *Ovl = R.Expression;
13355 bool IsResultAmbiguous = false;
13356 FunctionDecl *Result = nullptr;
13357 DeclAccessPair DAP;
13358 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13359
13360 // Return positive for better, negative for worse, 0 for equal preference.
13361 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13362 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13363 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13364 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13365 };
13366
13367 // Don't use the AddressOfResolver because we're specifically looking for
13368 // cases where we have one overload candidate that lacks
13369 // enable_if/pass_object_size/...
13370 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13371 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13372 if (!FD)
13373 return nullptr;
13374
13376 continue;
13377
13378 // If we found a better result, update Result.
13379 auto FoundBetter = [&]() {
13380 IsResultAmbiguous = false;
13381 DAP = I.getPair();
13382 Result = FD;
13383 };
13384
13385 // We have more than one result - see if it is more constrained than the
13386 // previous one.
13387 if (Result) {
13388 // Check CUDA preference first. If the candidates have differennt CUDA
13389 // preference, choose the one with higher CUDA preference. Otherwise,
13390 // choose the one with more constraints.
13391 if (getLangOpts().CUDA) {
13392 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13393 // FD has different preference than Result.
13394 if (PreferenceByCUDA != 0) {
13395 // FD is more preferable than Result.
13396 if (PreferenceByCUDA > 0)
13397 FoundBetter();
13398 continue;
13399 }
13400 }
13401 // FD has the same CUDA prefernece than Result. Continue check
13402 // constraints.
13403 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13404 if (MoreConstrained != FD) {
13405 if (!MoreConstrained) {
13406 IsResultAmbiguous = true;
13407 AmbiguousDecls.push_back(FD);
13408 }
13409 continue;
13410 }
13411 // FD is more constrained - replace Result with it.
13412 }
13413 FoundBetter();
13414 }
13415
13416 if (IsResultAmbiguous)
13417 return nullptr;
13418
13419 if (Result) {
13421 // We skipped over some ambiguous declarations which might be ambiguous with
13422 // the selected result.
13423 for (FunctionDecl *Skipped : AmbiguousDecls) {
13424 // If skipped candidate has different CUDA preference than the result,
13425 // there is no ambiguity. Otherwise check whether they have different
13426 // constraints.
13427 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13428 continue;
13429 if (!getMoreConstrainedFunction(Skipped, Result))
13430 return nullptr;
13431 }
13432 Pair = DAP;
13433 }
13434 return Result;
13435}
13436
13438 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13439 Expr *E = SrcExpr.get();
13440 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13441
13442 DeclAccessPair DAP;
13443 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13444 if (!Found || Found->isCPUDispatchMultiVersion() ||
13445 Found->isCPUSpecificMultiVersion())
13446 return false;
13447
13448 // Emitting multiple diagnostics for a function that is both inaccessible and
13449 // unavailable is consistent with our behavior elsewhere. So, always check
13450 // for both.
13451 DiagnoseUseOfDecl(Found, E->getExprLoc());
13452 CheckAddressOfMemberAccess(E, DAP);
13453 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13454 if (Res.isInvalid())
13455 return false;
13456 Expr *Fixed = Res.get();
13457 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13458 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13459 else
13460 SrcExpr = Fixed;
13461 return true;
13462}
13463
13465 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13466 TemplateSpecCandidateSet *FailedTSC) {
13467 // C++ [over.over]p1:
13468 // [...] [Note: any redundant set of parentheses surrounding the
13469 // overloaded function name is ignored (5.1). ]
13470 // C++ [over.over]p1:
13471 // [...] The overloaded function name can be preceded by the &
13472 // operator.
13473
13474 // If we didn't actually find any template-ids, we're done.
13475 if (!ovl->hasExplicitTemplateArgs())
13476 return nullptr;
13477
13478 TemplateArgumentListInfo ExplicitTemplateArgs;
13479 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13480
13481 // Look through all of the overloaded functions, searching for one
13482 // whose type matches exactly.
13483 FunctionDecl *Matched = nullptr;
13484 for (UnresolvedSetIterator I = ovl->decls_begin(),
13485 E = ovl->decls_end(); I != E; ++I) {
13486 // C++0x [temp.arg.explicit]p3:
13487 // [...] In contexts where deduction is done and fails, or in contexts
13488 // where deduction is not done, if a template argument list is
13489 // specified and it, along with any default template arguments,
13490 // identifies a single function template specialization, then the
13491 // template-id is an lvalue for the function template specialization.
13492 FunctionTemplateDecl *FunctionTemplate
13493 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13494
13495 // C++ [over.over]p2:
13496 // If the name is a function template, template argument deduction is
13497 // done (14.8.2.2), and if the argument deduction succeeds, the
13498 // resulting template argument list is used to generate a single
13499 // function template specialization, which is added to the set of
13500 // overloaded functions considered.
13501 FunctionDecl *Specialization = nullptr;
13502 TemplateDeductionInfo Info(ovl->getNameLoc());
13504 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13505 /*IsAddressOfFunction*/ true);
13507 // Make a note of the failed deduction for diagnostics.
13508 if (FailedTSC)
13509 FailedTSC->addCandidate().set(
13510 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13511 MakeDeductionFailureInfo(Context, Result, Info));
13512 continue;
13513 }
13514
13515 assert(Specialization && "no specialization and no error?");
13516
13517 // Multiple matches; we can't resolve to a single declaration.
13518 if (Matched) {
13519 if (Complain) {
13520 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13521 << ovl->getName();
13522 NoteAllOverloadCandidates(ovl);
13523 }
13524 return nullptr;
13525 }
13526
13527 Matched = Specialization;
13528 if (FoundResult) *FoundResult = I.getPair();
13529 }
13530
13531 if (Matched &&
13532 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13533 return nullptr;
13534
13535 return Matched;
13536}
13537
13539 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13540 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13541 unsigned DiagIDForComplaining) {
13542 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13543
13545
13546 DeclAccessPair found;
13547 ExprResult SingleFunctionExpression;
13548 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13549 ovl.Expression, /*complain*/ false, &found)) {
13550 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13551 SrcExpr = ExprError();
13552 return true;
13553 }
13554
13555 // It is only correct to resolve to an instance method if we're
13556 // resolving a form that's permitted to be a pointer to member.
13557 // Otherwise we'll end up making a bound member expression, which
13558 // is illegal in all the contexts we resolve like this.
13559 if (!ovl.HasFormOfMemberPointer &&
13560 isa<CXXMethodDecl>(fn) &&
13561 cast<CXXMethodDecl>(fn)->isInstance()) {
13562 if (!complain) return false;
13563
13564 Diag(ovl.Expression->getExprLoc(),
13565 diag::err_bound_member_function)
13566 << 0 << ovl.Expression->getSourceRange();
13567
13568 // TODO: I believe we only end up here if there's a mix of
13569 // static and non-static candidates (otherwise the expression
13570 // would have 'bound member' type, not 'overload' type).
13571 // Ideally we would note which candidate was chosen and why
13572 // the static candidates were rejected.
13573 SrcExpr = ExprError();
13574 return true;
13575 }
13576
13577 // Fix the expression to refer to 'fn'.
13578 SingleFunctionExpression =
13579 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13580
13581 // If desired, do function-to-pointer decay.
13582 if (doFunctionPointerConversion) {
13583 SingleFunctionExpression =
13584 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13585 if (SingleFunctionExpression.isInvalid()) {
13586 SrcExpr = ExprError();
13587 return true;
13588 }
13589 }
13590 }
13591
13592 if (!SingleFunctionExpression.isUsable()) {
13593 if (complain) {
13594 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13595 << ovl.Expression->getName()
13596 << DestTypeForComplaining
13597 << OpRangeForComplaining
13599 NoteAllOverloadCandidates(SrcExpr.get());
13600
13601 SrcExpr = ExprError();
13602 return true;
13603 }
13604
13605 return false;
13606 }
13607
13608 SrcExpr = SingleFunctionExpression;
13609 return true;
13610}
13611
13612/// Add a single candidate to the overload set.
13614 DeclAccessPair FoundDecl,
13615 TemplateArgumentListInfo *ExplicitTemplateArgs,
13616 ArrayRef<Expr *> Args,
13617 OverloadCandidateSet &CandidateSet,
13618 bool PartialOverloading,
13619 bool KnownValid) {
13620 NamedDecl *Callee = FoundDecl.getDecl();
13621 if (isa<UsingShadowDecl>(Callee))
13622 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13623
13624 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13625 if (ExplicitTemplateArgs) {
13626 assert(!KnownValid && "Explicit template arguments?");
13627 return;
13628 }
13629 // Prevent ill-formed function decls to be added as overload candidates.
13630 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13631 return;
13632
13633 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13634 /*SuppressUserConversions=*/false,
13635 PartialOverloading);
13636 return;
13637 }
13638
13639 if (FunctionTemplateDecl *FuncTemplate
13640 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13641 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13642 ExplicitTemplateArgs, Args, CandidateSet,
13643 /*SuppressUserConversions=*/false,
13644 PartialOverloading);
13645 return;
13646 }
13647
13648 assert(!KnownValid && "unhandled case in overloaded call candidate");
13649}
13650
13652 ArrayRef<Expr *> Args,
13653 OverloadCandidateSet &CandidateSet,
13654 bool PartialOverloading) {
13655
13656#ifndef NDEBUG
13657 // Verify that ArgumentDependentLookup is consistent with the rules
13658 // in C++0x [basic.lookup.argdep]p3:
13659 //
13660 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13661 // and let Y be the lookup set produced by argument dependent
13662 // lookup (defined as follows). If X contains
13663 //
13664 // -- a declaration of a class member, or
13665 //
13666 // -- a block-scope function declaration that is not a
13667 // using-declaration, or
13668 //
13669 // -- a declaration that is neither a function or a function
13670 // template
13671 //
13672 // then Y is empty.
13673
13674 if (ULE->requiresADL()) {
13676 E = ULE->decls_end(); I != E; ++I) {
13677 assert(!(*I)->getDeclContext()->isRecord());
13678 assert(isa<UsingShadowDecl>(*I) ||
13679 !(*I)->getDeclContext()->isFunctionOrMethod());
13680 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13681 }
13682 }
13683#endif
13684
13685 // It would be nice to avoid this copy.
13686 TemplateArgumentListInfo TABuffer;
13687 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13688 if (ULE->hasExplicitTemplateArgs()) {
13689 ULE->copyTemplateArgumentsInto(TABuffer);
13690 ExplicitTemplateArgs = &TABuffer;
13691 }
13692
13694 E = ULE->decls_end(); I != E; ++I)
13695 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13696 CandidateSet, PartialOverloading,
13697 /*KnownValid*/ true);
13698
13699 if (ULE->requiresADL())
13700 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13701 Args, ExplicitTemplateArgs,
13702 CandidateSet, PartialOverloading);
13703}
13704
13706 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13707 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13708 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13709 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13710 CandidateSet, false, /*KnownValid*/ false);
13711}
13712
13713/// Determine whether a declaration with the specified name could be moved into
13714/// a different namespace.
13716 switch (Name.getCXXOverloadedOperator()) {
13717 case OO_New: case OO_Array_New:
13718 case OO_Delete: case OO_Array_Delete:
13719 return false;
13720
13721 default:
13722 return true;
13723 }
13724}
13725
13726/// Attempt to recover from an ill-formed use of a non-dependent name in a
13727/// template, where the non-dependent name was declared after the template
13728/// was defined. This is common in code written for a compilers which do not
13729/// correctly implement two-stage name lookup.
13730///
13731/// Returns true if a viable candidate was found and a diagnostic was issued.
13733 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13735 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13736 CXXRecordDecl **FoundInClass = nullptr) {
13737 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13738 return false;
13739
13740 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13741 if (DC->isTransparentContext())
13742 continue;
13743
13744 SemaRef.LookupQualifiedName(R, DC);
13745
13746 if (!R.empty()) {
13748
13749 OverloadCandidateSet Candidates(FnLoc, CSK);
13750 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13751 Candidates);
13752
13755 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13756
13757 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13758 // We either found non-function declarations or a best viable function
13759 // at class scope. A class-scope lookup result disables ADL. Don't
13760 // look past this, but let the caller know that we found something that
13761 // either is, or might be, usable in this class.
13762 if (FoundInClass) {
13763 *FoundInClass = RD;
13764 if (OR == OR_Success) {
13765 R.clear();
13766 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13767 R.resolveKind();
13768 }
13769 }
13770 return false;
13771 }
13772
13773 if (OR != OR_Success) {
13774 // There wasn't a unique best function or function template.
13775 return false;
13776 }
13777
13778 // Find the namespaces where ADL would have looked, and suggest
13779 // declaring the function there instead.
13780 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13781 Sema::AssociatedClassSet AssociatedClasses;
13782 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13783 AssociatedNamespaces,
13784 AssociatedClasses);
13785 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13787 DeclContext *Std = SemaRef.getStdNamespace();
13788 for (Sema::AssociatedNamespaceSet::iterator
13789 it = AssociatedNamespaces.begin(),
13790 end = AssociatedNamespaces.end(); it != end; ++it) {
13791 // Never suggest declaring a function within namespace 'std'.
13792 if (Std && Std->Encloses(*it))
13793 continue;
13794
13795 // Never suggest declaring a function within a namespace with a
13796 // reserved name, like __gnu_cxx.
13797 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13798 if (NS &&
13799 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13800 continue;
13801
13802 SuggestedNamespaces.insert(*it);
13803 }
13804 }
13805
13806 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13807 << R.getLookupName();
13808 if (SuggestedNamespaces.empty()) {
13809 SemaRef.Diag(Best->Function->getLocation(),
13810 diag::note_not_found_by_two_phase_lookup)
13811 << R.getLookupName() << 0;
13812 } else if (SuggestedNamespaces.size() == 1) {
13813 SemaRef.Diag(Best->Function->getLocation(),
13814 diag::note_not_found_by_two_phase_lookup)
13815 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13816 } else {
13817 // FIXME: It would be useful to list the associated namespaces here,
13818 // but the diagnostics infrastructure doesn't provide a way to produce
13819 // a localized representation of a list of items.
13820 SemaRef.Diag(Best->Function->getLocation(),
13821 diag::note_not_found_by_two_phase_lookup)
13822 << R.getLookupName() << 2;
13823 }
13824
13825 // Try to recover by calling this function.
13826 return true;
13827 }
13828
13829 R.clear();
13830 }
13831
13832 return false;
13833}
13834
13835/// Attempt to recover from ill-formed use of a non-dependent operator in a
13836/// template, where the non-dependent operator was declared after the template
13837/// was defined.
13838///
13839/// Returns true if a viable candidate was found and a diagnostic was issued.
13840static bool
13842 SourceLocation OpLoc,
13843 ArrayRef<Expr *> Args) {
13844 DeclarationName OpName =
13846 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13847 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13849 /*ExplicitTemplateArgs=*/nullptr, Args);
13850}
13851
13852namespace {
13853class BuildRecoveryCallExprRAII {
13854 Sema &SemaRef;
13856
13857public:
13858 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13859 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13860 SemaRef.IsBuildingRecoveryCallExpr = true;
13861 }
13862
13863 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13864};
13865}
13866
13867/// Attempts to recover from a call where no functions were found.
13868///
13869/// This function will do one of three things:
13870/// * Diagnose, recover, and return a recovery expression.
13871/// * Diagnose, fail to recover, and return ExprError().
13872/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13873/// expected to diagnose as appropriate.
13874static ExprResult
13877 SourceLocation LParenLoc,
13879 SourceLocation RParenLoc,
13880 bool EmptyLookup, bool AllowTypoCorrection) {
13881 // Do not try to recover if it is already building a recovery call.
13882 // This stops infinite loops for template instantiations like
13883 //
13884 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13885 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13886 if (SemaRef.IsBuildingRecoveryCallExpr)
13887 return ExprResult();
13888 BuildRecoveryCallExprRAII RCE(SemaRef);
13889
13890 CXXScopeSpec SS;
13891 SS.Adopt(ULE->getQualifierLoc());
13892 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13893
13894 TemplateArgumentListInfo TABuffer;
13895 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13896 if (ULE->hasExplicitTemplateArgs()) {
13897 ULE->copyTemplateArgumentsInto(TABuffer);
13898 ExplicitTemplateArgs = &TABuffer;
13899 }
13900
13901 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13903 CXXRecordDecl *FoundInClass = nullptr;
13904 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13906 ExplicitTemplateArgs, Args, &FoundInClass)) {
13907 // OK, diagnosed a two-phase lookup issue.
13908 } else if (EmptyLookup) {
13909 // Try to recover from an empty lookup with typo correction.
13910 R.clear();
13911 NoTypoCorrectionCCC NoTypoValidator{};
13912 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13913 ExplicitTemplateArgs != nullptr,
13914 dyn_cast<MemberExpr>(Fn));
13915 CorrectionCandidateCallback &Validator =
13916 AllowTypoCorrection
13917 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13918 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13919 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13920 Args))
13921 return ExprError();
13922 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13923 // We found a usable declaration of the name in a dependent base of some
13924 // enclosing class.
13925 // FIXME: We should also explain why the candidates found by name lookup
13926 // were not viable.
13927 if (SemaRef.DiagnoseDependentMemberLookup(R))
13928 return ExprError();
13929 } else {
13930 // We had viable candidates and couldn't recover; let the caller diagnose
13931 // this.
13932 return ExprResult();
13933 }
13934
13935 // If we get here, we should have issued a diagnostic and formed a recovery
13936 // lookup result.
13937 assert(!R.empty() && "lookup results empty despite recovery");
13938
13939 // If recovery created an ambiguity, just bail out.
13940 if (R.isAmbiguous()) {
13942 return ExprError();
13943 }
13944
13945 // Build an implicit member call if appropriate. Just drop the
13946 // casts and such from the call, we don't really care.
13947 ExprResult NewFn = ExprError();
13948 if ((*R.begin())->isCXXClassMember())
13949 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13950 ExplicitTemplateArgs, S);
13951 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13952 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13953 ExplicitTemplateArgs);
13954 else
13955 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13956
13957 if (NewFn.isInvalid())
13958 return ExprError();
13959
13960 // This shouldn't cause an infinite loop because we're giving it
13961 // an expression with viable lookup results, which should never
13962 // end up here.
13963 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13964 MultiExprArg(Args.data(), Args.size()),
13965 RParenLoc);
13966}
13967
13970 MultiExprArg Args,
13971 SourceLocation RParenLoc,
13972 OverloadCandidateSet *CandidateSet,
13973 ExprResult *Result) {
13974#ifndef NDEBUG
13975 if (ULE->requiresADL()) {
13976 // To do ADL, we must have found an unqualified name.
13977 assert(!ULE->getQualifier() && "qualified name with ADL");
13978
13979 // We don't perform ADL for implicit declarations of builtins.
13980 // Verify that this was correctly set up.
13981 FunctionDecl *F;
13982 if (ULE->decls_begin() != ULE->decls_end() &&
13983 ULE->decls_begin() + 1 == ULE->decls_end() &&
13984 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13985 F->getBuiltinID() && F->isImplicit())
13986 llvm_unreachable("performing ADL for builtin");
13987
13988 // We don't perform ADL in C.
13989 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13990 }
13991#endif
13992
13993 UnbridgedCastsSet UnbridgedCasts;
13994 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13995 *Result = ExprError();
13996 return true;
13997 }
13998
13999 // Add the functions denoted by the callee to the set of candidate
14000 // functions, including those from argument-dependent lookup.
14001 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14002
14003 if (getLangOpts().MSVCCompat &&
14004 CurContext->isDependentContext() && !isSFINAEContext() &&
14005 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14006
14008 if (CandidateSet->empty() ||
14009 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14011 // In Microsoft mode, if we are inside a template class member function
14012 // then create a type dependent CallExpr. The goal is to postpone name
14013 // lookup to instantiation time to be able to search into type dependent
14014 // base classes.
14015 CallExpr *CE =
14016 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14017 RParenLoc, CurFPFeatureOverrides());
14019 *Result = CE;
14020 return true;
14021 }
14022 }
14023
14024 if (CandidateSet->empty())
14025 return false;
14026
14027 UnbridgedCasts.restore();
14028 return false;
14029}
14030
14031// Guess at what the return type for an unresolvable overload should be.
14034 std::optional<QualType> Result;
14035 // Adjust Type after seeing a candidate.
14036 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14037 if (!Candidate.Function)
14038 return;
14039 if (Candidate.Function->isInvalidDecl())
14040 return;
14041 QualType T = Candidate.Function->getReturnType();
14042 if (T.isNull())
14043 return;
14044 if (!Result)
14045 Result = T;
14046 else if (Result != T)
14047 Result = QualType();
14048 };
14049
14050 // Look for an unambiguous type from a progressively larger subset.
14051 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14052 //
14053 // First, consider only the best candidate.
14054 if (Best && *Best != CS.end())
14055 ConsiderCandidate(**Best);
14056 // Next, consider only viable candidates.
14057 if (!Result)
14058 for (const auto &C : CS)
14059 if (C.Viable)
14060 ConsiderCandidate(C);
14061 // Finally, consider all candidates.
14062 if (!Result)
14063 for (const auto &C : CS)
14064 ConsiderCandidate(C);
14065
14066 if (!Result)
14067 return QualType();
14068 auto Value = *Result;
14069 if (Value.isNull() || Value->isUndeducedType())
14070 return QualType();
14071 return Value;
14072}
14073
14074/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14075/// the completed call expression. If overload resolution fails, emits
14076/// diagnostics and returns ExprError()
14079 SourceLocation LParenLoc,
14080 MultiExprArg Args,
14081 SourceLocation RParenLoc,
14082 Expr *ExecConfig,
14083 OverloadCandidateSet *CandidateSet,
14085 OverloadingResult OverloadResult,
14086 bool AllowTypoCorrection) {
14087 switch (OverloadResult) {
14088 case OR_Success: {
14089 FunctionDecl *FDecl = (*Best)->Function;
14090 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14091 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14092 return ExprError();
14093 ExprResult Res =
14094 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14095 if (Res.isInvalid())
14096 return ExprError();
14097 return SemaRef.BuildResolvedCallExpr(
14098 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14099 /*IsExecConfig=*/false,
14100 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14101 }
14102
14103 case OR_No_Viable_Function: {
14104 if (*Best != CandidateSet->end() &&
14105 CandidateSet->getKind() ==
14107 if (CXXMethodDecl *M =
14108 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14110 CandidateSet->NoteCandidates(
14112 Fn->getBeginLoc(),
14113 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14114 SemaRef, OCD_AmbiguousCandidates, Args);
14115 return ExprError();
14116 }
14117 }
14118
14119 // Try to recover by looking for viable functions which the user might
14120 // have meant to call.
14121 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14122 Args, RParenLoc,
14123 CandidateSet->empty(),
14124 AllowTypoCorrection);
14125 if (Recovery.isInvalid() || Recovery.isUsable())
14126 return Recovery;
14127
14128 // If the user passes in a function that we can't take the address of, we
14129 // generally end up emitting really bad error messages. Here, we attempt to
14130 // emit better ones.
14131 for (const Expr *Arg : Args) {
14132 if (!Arg->getType()->isFunctionType())
14133 continue;
14134 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14135 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14136 if (FD &&
14137 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14138 Arg->getExprLoc()))
14139 return ExprError();
14140 }
14141 }
14142
14143 CandidateSet->NoteCandidates(
14145 Fn->getBeginLoc(),
14146 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14147 << ULE->getName() << Fn->getSourceRange()),
14148 SemaRef, OCD_AllCandidates, Args);
14149 break;
14150 }
14151
14152 case OR_Ambiguous:
14153 CandidateSet->NoteCandidates(
14154 PartialDiagnosticAt(Fn->getBeginLoc(),
14155 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14156 << ULE->getName() << Fn->getSourceRange()),
14157 SemaRef, OCD_AmbiguousCandidates, Args);
14158 break;
14159
14160 case OR_Deleted: {
14161 FunctionDecl *FDecl = (*Best)->Function;
14162 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14163 Fn->getSourceRange(), ULE->getName(),
14164 *CandidateSet, FDecl, Args);
14165
14166 // We emitted an error for the unavailable/deleted function call but keep
14167 // the call in the AST.
14168 ExprResult Res =
14169 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14170 if (Res.isInvalid())
14171 return ExprError();
14172 return SemaRef.BuildResolvedCallExpr(
14173 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14174 /*IsExecConfig=*/false,
14175 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14176 }
14177 }
14178
14179 // Overload resolution failed, try to recover.
14180 SmallVector<Expr *, 8> SubExprs = {Fn};
14181 SubExprs.append(Args.begin(), Args.end());
14182 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14183 chooseRecoveryType(*CandidateSet, Best));
14184}
14185
14188 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14189 if (I->Viable &&
14190 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14191 I->Viable = false;
14192 I->FailureKind = ovl_fail_addr_not_available;
14193 }
14194 }
14195}
14196
14199 SourceLocation LParenLoc,
14200 MultiExprArg Args,
14201 SourceLocation RParenLoc,
14202 Expr *ExecConfig,
14203 bool AllowTypoCorrection,
14204 bool CalleesAddressIsTaken) {
14205 OverloadCandidateSet CandidateSet(
14206 Fn->getExprLoc(), CalleesAddressIsTaken
14209 ExprResult result;
14210
14211 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14212 &result))
14213 return result;
14214
14215 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14216 // functions that aren't addressible are considered unviable.
14217 if (CalleesAddressIsTaken)
14218 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14219
14221 OverloadingResult OverloadResult =
14222 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14223
14224 // Model the case with a call to a templated function whose definition
14225 // encloses the call and whose return type contains a placeholder type as if
14226 // the UnresolvedLookupExpr was type-dependent.
14227 if (OverloadResult == OR_Success) {
14228 const FunctionDecl *FDecl = Best->Function;
14229 if (FDecl && FDecl->isTemplateInstantiation() &&
14230 FDecl->getReturnType()->isUndeducedType()) {
14231 if (const auto *TP =
14232 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14233 TP && TP->willHaveBody()) {
14234 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14235 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14236 }
14237 }
14238 }
14239
14240 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14241 ExecConfig, &CandidateSet, &Best,
14242 OverloadResult, AllowTypoCorrection);
14243}
14244
14248 const UnresolvedSetImpl &Fns,
14249 bool PerformADL) {
14251 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14252 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14253}
14254
14256 CXXConversionDecl *Method,
14257 bool HadMultipleCandidates) {
14258 // Convert the expression to match the conversion function's implicit object
14259 // parameter.
14260 ExprResult Exp;
14261 if (Method->isExplicitObjectMemberFunction())
14262 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14263 else
14264 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14265 FoundDecl, Method);
14266 if (Exp.isInvalid())
14267 return true;
14268
14269 if (Method->getParent()->isLambda() &&
14271 // This is a lambda conversion to block pointer; check if the argument
14272 // was a LambdaExpr.
14273 Expr *SubE = E;
14274 auto *CE = dyn_cast<CastExpr>(SubE);
14275 if (CE && CE->getCastKind() == CK_NoOp)
14276 SubE = CE->getSubExpr();
14277 SubE = SubE->IgnoreParens();
14278 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14279 SubE = BE->getSubExpr();
14280 if (isa<LambdaExpr>(SubE)) {
14281 // For the conversion to block pointer on a lambda expression, we
14282 // construct a special BlockLiteral instead; this doesn't really make
14283 // a difference in ARC, but outside of ARC the resulting block literal
14284 // follows the normal lifetime rules for block literals instead of being
14285 // autoreleased.
14286 PushExpressionEvaluationContext(
14287 ExpressionEvaluationContext::PotentiallyEvaluated);
14288 ExprResult BlockExp = BuildBlockForLambdaConversion(
14289 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14290 PopExpressionEvaluationContext();
14291
14292 // FIXME: This note should be produced by a CodeSynthesisContext.
14293 if (BlockExp.isInvalid())
14294 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14295 return BlockExp;
14296 }
14297 }
14298 CallExpr *CE;
14299 QualType ResultType = Method->getReturnType();
14301 ResultType = ResultType.getNonLValueExprType(Context);
14302 if (Method->isExplicitObjectMemberFunction()) {
14303 ExprResult FnExpr =
14304 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14305 HadMultipleCandidates, E->getBeginLoc());
14306 if (FnExpr.isInvalid())
14307 return ExprError();
14308 Expr *ObjectParam = Exp.get();
14309 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14310 ResultType, VK, Exp.get()->getEndLoc(),
14311 CurFPFeatureOverrides());
14312 } else {
14313 MemberExpr *ME =
14314 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14316 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14317 HadMultipleCandidates, DeclarationNameInfo(),
14319
14320 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14321 Exp.get()->getEndLoc(),
14322 CurFPFeatureOverrides());
14323 }
14324
14325 if (CheckFunctionCall(Method, CE,
14326 Method->getType()->castAs<FunctionProtoType>()))
14327 return ExprError();
14328
14329 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14330}
14331
14334 const UnresolvedSetImpl &Fns,
14335 Expr *Input, bool PerformADL) {
14337 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14339 // TODO: provide better source location info.
14340 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14341
14342 if (checkPlaceholderForOverload(*this, Input))
14343 return ExprError();
14344
14345 Expr *Args[2] = { Input, nullptr };
14346 unsigned NumArgs = 1;
14347
14348 // For post-increment and post-decrement, add the implicit '0' as
14349 // the second argument, so that we know this is a post-increment or
14350 // post-decrement.
14351 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14352 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14353 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14354 SourceLocation());
14355 NumArgs = 2;
14356 }
14357
14358 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14359
14360 if (Input->isTypeDependent()) {
14362 // [C++26][expr.unary.op][expr.pre.incr]
14363 // The * operator yields an lvalue of type
14364 // The pre/post increment operators yied an lvalue.
14365 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14366 VK = VK_LValue;
14367
14368 if (Fns.empty())
14369 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14370 OK_Ordinary, OpLoc, false,
14371 CurFPFeatureOverrides());
14372
14373 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14374 ExprResult Fn = CreateUnresolvedLookupExpr(
14375 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14376 if (Fn.isInvalid())
14377 return ExprError();
14378 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14379 Context.DependentTy, VK_PRValue, OpLoc,
14380 CurFPFeatureOverrides());
14381 }
14382
14383 // Build an empty overload set.
14385
14386 // Add the candidates from the given function set.
14387 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14388
14389 // Add operator candidates that are member functions.
14390 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14391
14392 // Add candidates from ADL.
14393 if (PerformADL) {
14394 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14395 /*ExplicitTemplateArgs*/nullptr,
14396 CandidateSet);
14397 }
14398
14399 // Add builtin operator candidates.
14400 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14401
14402 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14403
14404 // Perform overload resolution.
14406 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14407 case OR_Success: {
14408 // We found a built-in operator or an overloaded operator.
14409 FunctionDecl *FnDecl = Best->Function;
14410
14411 if (FnDecl) {
14412 Expr *Base = nullptr;
14413 // We matched an overloaded operator. Build a call to that
14414 // operator.
14415
14416 // Convert the arguments.
14417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14418 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14419
14420 ExprResult InputInit;
14421 if (Method->isExplicitObjectMemberFunction())
14422 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14423 else
14424 InputInit = PerformImplicitObjectArgumentInitialization(
14425 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14426 if (InputInit.isInvalid())
14427 return ExprError();
14428 Base = Input = InputInit.get();
14429 } else {
14430 // Convert the arguments.
14431 ExprResult InputInit
14432 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14433 Context,
14434 FnDecl->getParamDecl(0)),
14436 Input);
14437 if (InputInit.isInvalid())
14438 return ExprError();
14439 Input = InputInit.get();
14440 }
14441
14442 // Build the actual expression node.
14443 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14444 Base, HadMultipleCandidates,
14445 OpLoc);
14446 if (FnExpr.isInvalid())
14447 return ExprError();
14448
14449 // Determine the result type.
14450 QualType ResultTy = FnDecl->getReturnType();
14452 ResultTy = ResultTy.getNonLValueExprType(Context);
14453
14454 Args[0] = Input;
14456 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14457 CurFPFeatureOverrides(),
14458 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
14459
14460 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14461 return ExprError();
14462
14463 if (CheckFunctionCall(FnDecl, TheCall,
14464 FnDecl->getType()->castAs<FunctionProtoType>()))
14465 return ExprError();
14466 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14467 } else {
14468 // We matched a built-in operator. Convert the arguments, then
14469 // break out so that we will build the appropriate built-in
14470 // operator node.
14471 ExprResult InputRes = PerformImplicitConversion(
14472 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
14475 if (InputRes.isInvalid())
14476 return ExprError();
14477 Input = InputRes.get();
14478 break;
14479 }
14480 }
14481
14483 // This is an erroneous use of an operator which can be overloaded by
14484 // a non-member function. Check for non-member operators which were
14485 // defined too late to be candidates.
14486 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14487 // FIXME: Recover by calling the found function.
14488 return ExprError();
14489
14490 // No viable function; fall through to handling this as a
14491 // built-in operator, which will produce an error message for us.
14492 break;
14493
14494 case OR_Ambiguous:
14495 CandidateSet.NoteCandidates(
14496 PartialDiagnosticAt(OpLoc,
14497 PDiag(diag::err_ovl_ambiguous_oper_unary)
14499 << Input->getType() << Input->getSourceRange()),
14500 *this, OCD_AmbiguousCandidates, ArgsArray,
14501 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14502 return ExprError();
14503
14504 case OR_Deleted: {
14505 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14506 // object whose method was called. Later in NoteCandidates size of ArgsArray
14507 // is passed further and it eventually ends up compared to number of
14508 // function candidate parameters which never includes the object parameter,
14509 // so slice ArgsArray to make sure apples are compared to apples.
14510 StringLiteral *Msg = Best->Function->getDeletedMessage();
14511 CandidateSet.NoteCandidates(
14512 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14514 << (Msg != nullptr)
14515 << (Msg ? Msg->getString() : StringRef())
14516 << Input->getSourceRange()),
14517 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14518 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14519 return ExprError();
14520 }
14521 }
14522
14523 // Either we found no viable overloaded operator or we matched a
14524 // built-in operator. In either case, fall through to trying to
14525 // build a built-in operation.
14526 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14527}
14528
14531 const UnresolvedSetImpl &Fns,
14532 ArrayRef<Expr *> Args, bool PerformADL) {
14533 SourceLocation OpLoc = CandidateSet.getLocation();
14534
14535 OverloadedOperatorKind ExtraOp =
14538 : OO_None;
14539
14540 // Add the candidates from the given function set. This also adds the
14541 // rewritten candidates using these functions if necessary.
14542 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14543
14544 // Add operator candidates that are member functions.
14545 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14546 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14547 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14549
14550 // In C++20, also add any rewritten member candidates.
14551 if (ExtraOp) {
14552 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14553 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14554 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14555 CandidateSet,
14557 }
14558
14559 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14560 // performed for an assignment operator (nor for operator[] nor operator->,
14561 // which don't get here).
14562 if (Op != OO_Equal && PerformADL) {
14564 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14565 /*ExplicitTemplateArgs*/ nullptr,
14566 CandidateSet);
14567 if (ExtraOp) {
14568 DeclarationName ExtraOpName =
14569 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14570 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14571 /*ExplicitTemplateArgs*/ nullptr,
14572 CandidateSet);
14573 }
14574 }
14575
14576 // Add builtin operator candidates.
14577 //
14578 // FIXME: We don't add any rewritten candidates here. This is strictly
14579 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14580 // resulting in our selecting a rewritten builtin candidate. For example:
14581 //
14582 // enum class E { e };
14583 // bool operator!=(E, E) requires false;
14584 // bool k = E::e != E::e;
14585 //
14586 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14587 // it seems unreasonable to consider rewritten builtin candidates. A core
14588 // issue has been filed proposing to removed this requirement.
14589 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14590}
14591
14594 const UnresolvedSetImpl &Fns, Expr *LHS,
14595 Expr *RHS, bool PerformADL,
14596 bool AllowRewrittenCandidates,
14597 FunctionDecl *DefaultedFn) {
14598 Expr *Args[2] = { LHS, RHS };
14599 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14600
14601 if (!getLangOpts().CPlusPlus20)
14602 AllowRewrittenCandidates = false;
14603
14605
14606 // If either side is type-dependent, create an appropriate dependent
14607 // expression.
14608 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14609 if (Fns.empty()) {
14610 // If there are no functions to store, just build a dependent
14611 // BinaryOperator or CompoundAssignment.
14614 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14615 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14616 Context.DependentTy);
14618 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14619 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14620 }
14621
14622 // FIXME: save results of ADL from here?
14623 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14624 // TODO: provide better source location info in DNLoc component.
14626 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14627 ExprResult Fn = CreateUnresolvedLookupExpr(
14628 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14629 if (Fn.isInvalid())
14630 return ExprError();
14631 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14632 Context.DependentTy, VK_PRValue, OpLoc,
14633 CurFPFeatureOverrides());
14634 }
14635
14636 // If this is the .* operator, which is not overloadable, just
14637 // create a built-in binary operator.
14638 if (Opc == BO_PtrMemD) {
14639 auto CheckPlaceholder = [&](Expr *&Arg) {
14640 ExprResult Res = CheckPlaceholderExpr(Arg);
14641 if (Res.isUsable())
14642 Arg = Res.get();
14643 return !Res.isUsable();
14644 };
14645
14646 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14647 // expression that contains placeholders (in either the LHS or RHS).
14648 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14649 return ExprError();
14650 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14651 }
14652
14653 // Always do placeholder-like conversions on the RHS.
14654 if (checkPlaceholderForOverload(*this, Args[1]))
14655 return ExprError();
14656
14657 // Do placeholder-like conversion on the LHS; note that we should
14658 // not get here with a PseudoObject LHS.
14659 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14660 if (checkPlaceholderForOverload(*this, Args[0]))
14661 return ExprError();
14662
14663 // If this is the assignment operator, we only perform overload resolution
14664 // if the left-hand side is a class or enumeration type. This is actually
14665 // a hack. The standard requires that we do overload resolution between the
14666 // various built-in candidates, but as DR507 points out, this can lead to
14667 // problems. So we do it this way, which pretty much follows what GCC does.
14668 // Note that we go the traditional code path for compound assignment forms.
14669 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14670 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14671
14672 // Build the overload set.
14675 Op, OpLoc, AllowRewrittenCandidates));
14676 if (DefaultedFn)
14677 CandidateSet.exclude(DefaultedFn);
14678 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14679
14680 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14681
14682 // Perform overload resolution.
14684 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14685 case OR_Success: {
14686 // We found a built-in operator or an overloaded operator.
14687 FunctionDecl *FnDecl = Best->Function;
14688
14689 bool IsReversed = Best->isReversed();
14690 if (IsReversed)
14691 std::swap(Args[0], Args[1]);
14692
14693 if (FnDecl) {
14694
14695 if (FnDecl->isInvalidDecl())
14696 return ExprError();
14697
14698 Expr *Base = nullptr;
14699 // We matched an overloaded operator. Build a call to that
14700 // operator.
14701
14702 OverloadedOperatorKind ChosenOp =
14704
14705 // C++2a [over.match.oper]p9:
14706 // If a rewritten operator== candidate is selected by overload
14707 // resolution for an operator@, its return type shall be cv bool
14708 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14709 !FnDecl->getReturnType()->isBooleanType()) {
14710 bool IsExtension =
14712 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14713 : diag::err_ovl_rewrite_equalequal_not_bool)
14714 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14715 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14716 Diag(FnDecl->getLocation(), diag::note_declared_at);
14717 if (!IsExtension)
14718 return ExprError();
14719 }
14720
14721 if (AllowRewrittenCandidates && !IsReversed &&
14722 CandidateSet.getRewriteInfo().isReversible()) {
14723 // We could have reversed this operator, but didn't. Check if some
14724 // reversed form was a viable candidate, and if so, if it had a
14725 // better conversion for either parameter. If so, this call is
14726 // formally ambiguous, and allowing it is an extension.
14728 for (OverloadCandidate &Cand : CandidateSet) {
14729 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14730 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14731 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14733 *this, OpLoc, Cand.Conversions[ArgIdx],
14734 Best->Conversions[ArgIdx]) ==
14736 AmbiguousWith.push_back(Cand.Function);
14737 break;
14738 }
14739 }
14740 }
14741 }
14742
14743 if (!AmbiguousWith.empty()) {
14744 bool AmbiguousWithSelf =
14745 AmbiguousWith.size() == 1 &&
14746 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14747 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14749 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14750 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14751 if (AmbiguousWithSelf) {
14752 Diag(FnDecl->getLocation(),
14753 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14754 // Mark member== const or provide matching != to disallow reversed
14755 // args. Eg.
14756 // struct S { bool operator==(const S&); };
14757 // S()==S();
14758 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14759 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14760 !MD->isConst() &&
14761 !MD->hasCXXExplicitFunctionObjectParameter() &&
14762 Context.hasSameUnqualifiedType(
14763 MD->getFunctionObjectParameterType(),
14764 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14765 Context.hasSameUnqualifiedType(
14766 MD->getFunctionObjectParameterType(),
14767 Args[0]->getType()) &&
14768 Context.hasSameUnqualifiedType(
14769 MD->getFunctionObjectParameterType(),
14770 Args[1]->getType()))
14771 Diag(FnDecl->getLocation(),
14772 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14773 } else {
14774 Diag(FnDecl->getLocation(),
14775 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14776 for (auto *F : AmbiguousWith)
14777 Diag(F->getLocation(),
14778 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14779 }
14780 }
14781 }
14782
14783 // Check for nonnull = nullable.
14784 // This won't be caught in the arg's initialization: the parameter to
14785 // the assignment operator is not marked nonnull.
14786 if (Op == OO_Equal)
14787 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14788 Args[1]->getType(), OpLoc);
14789
14790 // Convert the arguments.
14791 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14792 // Best->Access is only meaningful for class members.
14793 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14794
14795 ExprResult Arg0, Arg1;
14796 unsigned ParamIdx = 0;
14797 if (Method->isExplicitObjectMemberFunction()) {
14798 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14799 ParamIdx = 1;
14800 } else {
14801 Arg0 = PerformImplicitObjectArgumentInitialization(
14802 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14803 }
14804 Arg1 = PerformCopyInitialization(
14806 Context, FnDecl->getParamDecl(ParamIdx)),
14807 SourceLocation(), Args[1]);
14808 if (Arg0.isInvalid() || Arg1.isInvalid())
14809 return ExprError();
14810
14811 Base = Args[0] = Arg0.getAs<Expr>();
14812 Args[1] = RHS = Arg1.getAs<Expr>();
14813 } else {
14814 // Convert the arguments.
14815 ExprResult Arg0 = PerformCopyInitialization(
14817 FnDecl->getParamDecl(0)),
14818 SourceLocation(), Args[0]);
14819 if (Arg0.isInvalid())
14820 return ExprError();
14821
14822 ExprResult Arg1 =
14823 PerformCopyInitialization(
14825 FnDecl->getParamDecl(1)),
14826 SourceLocation(), Args[1]);
14827 if (Arg1.isInvalid())
14828 return ExprError();
14829 Args[0] = LHS = Arg0.getAs<Expr>();
14830 Args[1] = RHS = Arg1.getAs<Expr>();
14831 }
14832
14833 // Build the actual expression node.
14834 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14835 Best->FoundDecl, Base,
14836 HadMultipleCandidates, OpLoc);
14837 if (FnExpr.isInvalid())
14838 return ExprError();
14839
14840 // Determine the result type.
14841 QualType ResultTy = FnDecl->getReturnType();
14843 ResultTy = ResultTy.getNonLValueExprType(Context);
14844
14845 CallExpr *TheCall;
14846 ArrayRef<const Expr *> ArgsArray(Args, 2);
14847 const Expr *ImplicitThis = nullptr;
14848
14849 // We always create a CXXOperatorCallExpr, even for explicit object
14850 // members; CodeGen should take care not to emit the this pointer.
14852 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14853 CurFPFeatureOverrides(),
14854 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
14855
14856 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14857 Method && Method->isImplicitObjectMemberFunction()) {
14858 // Cut off the implicit 'this'.
14859 ImplicitThis = ArgsArray[0];
14860 ArgsArray = ArgsArray.slice(1);
14861 }
14862
14863 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14864 FnDecl))
14865 return ExprError();
14866
14867 if (Op == OO_Equal) {
14868 // Check for a self move.
14869 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14870 // lifetime check.
14872 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
14873 Args[1]);
14874 }
14875 if (ImplicitThis) {
14876 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14877 QualType ThisTypeFromDecl = Context.getPointerType(
14878 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14879
14880 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14881 ThisTypeFromDecl);
14882 }
14883
14884 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14885 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14886 VariadicDoesNotApply);
14887
14888 ExprResult R = MaybeBindToTemporary(TheCall);
14889 if (R.isInvalid())
14890 return ExprError();
14891
14892 R = CheckForImmediateInvocation(R, FnDecl);
14893 if (R.isInvalid())
14894 return ExprError();
14895
14896 // For a rewritten candidate, we've already reversed the arguments
14897 // if needed. Perform the rest of the rewrite now.
14898 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14899 (Op == OO_Spaceship && IsReversed)) {
14900 if (Op == OO_ExclaimEqual) {
14901 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14902 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14903 } else {
14904 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14905 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14906 Expr *ZeroLiteral =
14907 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14908
14911 Ctx.Entity = FnDecl;
14912 pushCodeSynthesisContext(Ctx);
14913
14914 R = CreateOverloadedBinOp(
14915 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14916 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14917 /*AllowRewrittenCandidates=*/false);
14918
14919 popCodeSynthesisContext();
14920 }
14921 if (R.isInvalid())
14922 return ExprError();
14923 } else {
14924 assert(ChosenOp == Op && "unexpected operator name");
14925 }
14926
14927 // Make a note in the AST if we did any rewriting.
14928 if (Best->RewriteKind != CRK_None)
14929 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14930
14931 return R;
14932 } else {
14933 // We matched a built-in operator. Convert the arguments, then
14934 // break out so that we will build the appropriate built-in
14935 // operator node.
14936 ExprResult ArgsRes0 = PerformImplicitConversion(
14937 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14940 if (ArgsRes0.isInvalid())
14941 return ExprError();
14942 Args[0] = ArgsRes0.get();
14943
14944 ExprResult ArgsRes1 = PerformImplicitConversion(
14945 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14948 if (ArgsRes1.isInvalid())
14949 return ExprError();
14950 Args[1] = ArgsRes1.get();
14951 break;
14952 }
14953 }
14954
14955 case OR_No_Viable_Function: {
14956 // C++ [over.match.oper]p9:
14957 // If the operator is the operator , [...] and there are no
14958 // viable functions, then the operator is assumed to be the
14959 // built-in operator and interpreted according to clause 5.
14960 if (Opc == BO_Comma)
14961 break;
14962
14963 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14964 // compare result using '==' and '<'.
14965 if (DefaultedFn && Opc == BO_Cmp) {
14966 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14967 Args[1], DefaultedFn);
14968 if (E.isInvalid() || E.isUsable())
14969 return E;
14970 }
14971
14972 // For class as left operand for assignment or compound assignment
14973 // operator do not fall through to handling in built-in, but report that
14974 // no overloaded assignment operator found
14976 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14977 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14978 Args, OpLoc);
14979 DeferDiagsRAII DDR(*this,
14980 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14981 if (Args[0]->getType()->isRecordType() &&
14982 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14983 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14985 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14986 if (Args[0]->getType()->isIncompleteType()) {
14987 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14988 << Args[0]->getType()
14989 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14990 }
14991 } else {
14992 // This is an erroneous use of an operator which can be overloaded by
14993 // a non-member function. Check for non-member operators which were
14994 // defined too late to be candidates.
14995 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14996 // FIXME: Recover by calling the found function.
14997 return ExprError();
14998
14999 // No viable function; try to create a built-in operation, which will
15000 // produce an error. Then, show the non-viable candidates.
15001 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15002 }
15003 assert(Result.isInvalid() &&
15004 "C++ binary operator overloading is missing candidates!");
15005 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15006 return Result;
15007 }
15008
15009 case OR_Ambiguous:
15010 CandidateSet.NoteCandidates(
15011 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15013 << Args[0]->getType()
15014 << Args[1]->getType()
15015 << Args[0]->getSourceRange()
15016 << Args[1]->getSourceRange()),
15018 OpLoc);
15019 return ExprError();
15020
15021 case OR_Deleted: {
15022 if (isImplicitlyDeleted(Best->Function)) {
15023 FunctionDecl *DeletedFD = Best->Function;
15024 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15025 if (DFK.isSpecialMember()) {
15026 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15027 << Args[0]->getType()
15028 << llvm::to_underlying(DFK.asSpecialMember());
15029 } else {
15030 assert(DFK.isComparison());
15031 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15032 << Args[0]->getType() << DeletedFD;
15033 }
15034
15035 // The user probably meant to call this special member. Just
15036 // explain why it's deleted.
15037 NoteDeletedFunction(DeletedFD);
15038 return ExprError();
15039 }
15040
15041 StringLiteral *Msg = Best->Function->getDeletedMessage();
15042 CandidateSet.NoteCandidates(
15044 OpLoc,
15045 PDiag(diag::err_ovl_deleted_oper)
15046 << getOperatorSpelling(Best->Function->getDeclName()
15047 .getCXXOverloadedOperator())
15048 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15049 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15051 OpLoc);
15052 return ExprError();
15053 }
15054 }
15055
15056 // We matched a built-in operator; build it.
15057 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15058}
15059
15061 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15062 FunctionDecl *DefaultedFn) {
15063 const ComparisonCategoryInfo *Info =
15064 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15065 // If we're not producing a known comparison category type, we can't
15066 // synthesize a three-way comparison. Let the caller diagnose this.
15067 if (!Info)
15068 return ExprResult((Expr*)nullptr);
15069
15070 // If we ever want to perform this synthesis more generally, we will need to
15071 // apply the temporary materialization conversion to the operands.
15072 assert(LHS->isGLValue() && RHS->isGLValue() &&
15073 "cannot use prvalue expressions more than once");
15074 Expr *OrigLHS = LHS;
15075 Expr *OrigRHS = RHS;
15076
15077 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15078 // each of them multiple times below.
15079 LHS = new (Context)
15080 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15081 LHS->getObjectKind(), LHS);
15082 RHS = new (Context)
15083 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15084 RHS->getObjectKind(), RHS);
15085
15086 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15087 DefaultedFn);
15088 if (Eq.isInvalid())
15089 return ExprError();
15090
15091 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15092 true, DefaultedFn);
15093 if (Less.isInvalid())
15094 return ExprError();
15095
15097 if (Info->isPartial()) {
15098 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15099 DefaultedFn);
15100 if (Greater.isInvalid())
15101 return ExprError();
15102 }
15103
15104 // Form the list of comparisons we're going to perform.
15105 struct Comparison {
15106 ExprResult Cmp;
15108 } Comparisons[4] =
15114 };
15115
15116 int I = Info->isPartial() ? 3 : 2;
15117
15118 // Combine the comparisons with suitable conditional expressions.
15120 for (; I >= 0; --I) {
15121 // Build a reference to the comparison category constant.
15122 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15123 // FIXME: Missing a constant for a comparison category. Diagnose this?
15124 if (!VI)
15125 return ExprResult((Expr*)nullptr);
15126 ExprResult ThisResult =
15127 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15128 if (ThisResult.isInvalid())
15129 return ExprError();
15130
15131 // Build a conditional unless this is the final case.
15132 if (Result.get()) {
15133 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15134 ThisResult.get(), Result.get());
15135 if (Result.isInvalid())
15136 return ExprError();
15137 } else {
15138 Result = ThisResult;
15139 }
15140 }
15141
15142 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15143 // bind the OpaqueValueExprs before they're (repeatedly) used.
15144 Expr *SyntacticForm = BinaryOperator::Create(
15145 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15146 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15147 CurFPFeatureOverrides());
15148 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15149 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15150}
15151
15153 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15154 MultiExprArg Args, SourceLocation LParenLoc) {
15155
15156 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15157 unsigned NumParams = Proto->getNumParams();
15158 unsigned NumArgsSlots =
15159 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15160 // Build the full argument list for the method call (the implicit object
15161 // parameter is placed at the beginning of the list).
15162 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15163 bool IsError = false;
15164 // Initialize the implicit object parameter.
15165 // Check the argument types.
15166 for (unsigned i = 0; i != NumParams; i++) {
15167 Expr *Arg;
15168 if (i < Args.size()) {
15169 Arg = Args[i];
15170 ExprResult InputInit =
15172 S.Context, Method->getParamDecl(i)),
15173 SourceLocation(), Arg);
15174 IsError |= InputInit.isInvalid();
15175 Arg = InputInit.getAs<Expr>();
15176 } else {
15177 ExprResult DefArg =
15178 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15179 if (DefArg.isInvalid()) {
15180 IsError = true;
15181 break;
15182 }
15183 Arg = DefArg.getAs<Expr>();
15184 }
15185
15186 MethodArgs.push_back(Arg);
15187 }
15188 return IsError;
15189}
15190
15192 SourceLocation RLoc,
15193 Expr *Base,
15194 MultiExprArg ArgExpr) {
15196 Args.push_back(Base);
15197 for (auto *e : ArgExpr) {
15198 Args.push_back(e);
15199 }
15200 DeclarationName OpName =
15201 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15202
15203 SourceRange Range = ArgExpr.empty()
15204 ? SourceRange{}
15205 : SourceRange(ArgExpr.front()->getBeginLoc(),
15206 ArgExpr.back()->getEndLoc());
15207
15208 // If either side is type-dependent, create an appropriate dependent
15209 // expression.
15211
15212 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15213 // CHECKME: no 'operator' keyword?
15214 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15215 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15216 ExprResult Fn = CreateUnresolvedLookupExpr(
15217 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15218 if (Fn.isInvalid())
15219 return ExprError();
15220 // Can't add any actual overloads yet
15221
15222 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15223 Context.DependentTy, VK_PRValue, RLoc,
15224 CurFPFeatureOverrides());
15225 }
15226
15227 // Handle placeholders
15228 UnbridgedCastsSet UnbridgedCasts;
15229 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15230 return ExprError();
15231 }
15232 // Build an empty overload set.
15234
15235 // Subscript can only be overloaded as a member function.
15236
15237 // Add operator candidates that are member functions.
15238 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15239
15240 // Add builtin operator candidates.
15241 if (Args.size() == 2)
15242 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15243
15244 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15245
15246 // Perform overload resolution.
15248 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15249 case OR_Success: {
15250 // We found a built-in operator or an overloaded operator.
15251 FunctionDecl *FnDecl = Best->Function;
15252
15253 if (FnDecl) {
15254 // We matched an overloaded operator. Build a call to that
15255 // operator.
15256
15257 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15258
15259 // Convert the arguments.
15260 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15261 SmallVector<Expr *, 2> MethodArgs;
15262
15263 // Initialize the object parameter.
15264 if (Method->isExplicitObjectMemberFunction()) {
15265 ExprResult Res =
15266 InitializeExplicitObjectArgument(*this, Args[0], Method);
15267 if (Res.isInvalid())
15268 return ExprError();
15269 Args[0] = Res.get();
15270 ArgExpr = Args;
15271 } else {
15272 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15273 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15274 if (Arg0.isInvalid())
15275 return ExprError();
15276
15277 MethodArgs.push_back(Arg0.get());
15278 }
15279
15281 *this, MethodArgs, Method, ArgExpr, LLoc);
15282 if (IsError)
15283 return ExprError();
15284
15285 // Build the actual expression node.
15286 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15287 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15289 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15290 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15291 if (FnExpr.isInvalid())
15292 return ExprError();
15293
15294 // Determine the result type
15295 QualType ResultTy = FnDecl->getReturnType();
15297 ResultTy = ResultTy.getNonLValueExprType(Context);
15298
15300 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15301 CurFPFeatureOverrides());
15302
15303 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15304 return ExprError();
15305
15306 if (CheckFunctionCall(Method, TheCall,
15307 Method->getType()->castAs<FunctionProtoType>()))
15308 return ExprError();
15309
15310 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15311 FnDecl);
15312 } else {
15313 // We matched a built-in operator. Convert the arguments, then
15314 // break out so that we will build the appropriate built-in
15315 // operator node.
15316 ExprResult ArgsRes0 = PerformImplicitConversion(
15317 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15320 if (ArgsRes0.isInvalid())
15321 return ExprError();
15322 Args[0] = ArgsRes0.get();
15323
15324 ExprResult ArgsRes1 = PerformImplicitConversion(
15325 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15328 if (ArgsRes1.isInvalid())
15329 return ExprError();
15330 Args[1] = ArgsRes1.get();
15331
15332 break;
15333 }
15334 }
15335
15336 case OR_No_Viable_Function: {
15338 CandidateSet.empty()
15339 ? (PDiag(diag::err_ovl_no_oper)
15340 << Args[0]->getType() << /*subscript*/ 0
15341 << Args[0]->getSourceRange() << Range)
15342 : (PDiag(diag::err_ovl_no_viable_subscript)
15343 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15344 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15345 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15346 return ExprError();
15347 }
15348
15349 case OR_Ambiguous:
15350 if (Args.size() == 2) {
15351 CandidateSet.NoteCandidates(
15353 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15354 << "[]" << Args[0]->getType() << Args[1]->getType()
15355 << Args[0]->getSourceRange() << Range),
15356 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15357 } else {
15358 CandidateSet.NoteCandidates(
15360 PDiag(diag::err_ovl_ambiguous_subscript_call)
15361 << Args[0]->getType()
15362 << Args[0]->getSourceRange() << Range),
15363 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15364 }
15365 return ExprError();
15366
15367 case OR_Deleted: {
15368 StringLiteral *Msg = Best->Function->getDeletedMessage();
15369 CandidateSet.NoteCandidates(
15371 PDiag(diag::err_ovl_deleted_oper)
15372 << "[]" << (Msg != nullptr)
15373 << (Msg ? Msg->getString() : StringRef())
15374 << Args[0]->getSourceRange() << Range),
15375 *this, OCD_AllCandidates, Args, "[]", LLoc);
15376 return ExprError();
15377 }
15378 }
15379
15380 // We matched a built-in operator; build it.
15381 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15382}
15383
15385 SourceLocation LParenLoc,
15386 MultiExprArg Args,
15387 SourceLocation RParenLoc,
15388 Expr *ExecConfig, bool IsExecConfig,
15389 bool AllowRecovery) {
15390 assert(MemExprE->getType() == Context.BoundMemberTy ||
15391 MemExprE->getType() == Context.OverloadTy);
15392
15393 // Dig out the member expression. This holds both the object
15394 // argument and the member function we're referring to.
15395 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15396
15397 // Determine whether this is a call to a pointer-to-member function.
15398 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15399 assert(op->getType() == Context.BoundMemberTy);
15400 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15401
15402 QualType fnType =
15403 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15404
15405 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15406 QualType resultType = proto->getCallResultType(Context);
15408
15409 // Check that the object type isn't more qualified than the
15410 // member function we're calling.
15411 Qualifiers funcQuals = proto->getMethodQuals();
15412
15413 QualType objectType = op->getLHS()->getType();
15414 if (op->getOpcode() == BO_PtrMemI)
15415 objectType = objectType->castAs<PointerType>()->getPointeeType();
15416 Qualifiers objectQuals = objectType.getQualifiers();
15417
15418 Qualifiers difference = objectQuals - funcQuals;
15419 difference.removeObjCGCAttr();
15420 difference.removeAddressSpace();
15421 if (difference) {
15422 std::string qualsString = difference.getAsString();
15423 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15424 << fnType.getUnqualifiedType()
15425 << qualsString
15426 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15427 }
15428
15430 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15431 CurFPFeatureOverrides(), proto->getNumParams());
15432
15433 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15434 call, nullptr))
15435 return ExprError();
15436
15437 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15438 return ExprError();
15439
15440 if (CheckOtherCall(call, proto))
15441 return ExprError();
15442
15443 return MaybeBindToTemporary(call);
15444 }
15445
15446 // We only try to build a recovery expr at this level if we can preserve
15447 // the return type, otherwise we return ExprError() and let the caller
15448 // recover.
15449 auto BuildRecoveryExpr = [&](QualType Type) {
15450 if (!AllowRecovery)
15451 return ExprError();
15452 std::vector<Expr *> SubExprs = {MemExprE};
15453 llvm::append_range(SubExprs, Args);
15454 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15455 Type);
15456 };
15457 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15458 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15459 RParenLoc, CurFPFeatureOverrides());
15460
15461 UnbridgedCastsSet UnbridgedCasts;
15462 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15463 return ExprError();
15464
15465 MemberExpr *MemExpr;
15466 CXXMethodDecl *Method = nullptr;
15467 bool HadMultipleCandidates = false;
15468 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15469 NestedNameSpecifier *Qualifier = nullptr;
15470 if (isa<MemberExpr>(NakedMemExpr)) {
15471 MemExpr = cast<MemberExpr>(NakedMemExpr);
15472 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15473 FoundDecl = MemExpr->getFoundDecl();
15474 Qualifier = MemExpr->getQualifier();
15475 UnbridgedCasts.restore();
15476 } else {
15477 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15478 Qualifier = UnresExpr->getQualifier();
15479
15480 QualType ObjectType = UnresExpr->getBaseType();
15481 Expr::Classification ObjectClassification
15483 : UnresExpr->getBase()->Classify(Context);
15484
15485 // Add overload candidates
15486 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15488
15489 // FIXME: avoid copy.
15490 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15491 if (UnresExpr->hasExplicitTemplateArgs()) {
15492 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15493 TemplateArgs = &TemplateArgsBuffer;
15494 }
15495
15497 E = UnresExpr->decls_end(); I != E; ++I) {
15498
15499 QualType ExplicitObjectType = ObjectType;
15500
15501 NamedDecl *Func = *I;
15502 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15503 if (isa<UsingShadowDecl>(Func))
15504 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15505
15506 bool HasExplicitParameter = false;
15507 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15508 M && M->hasCXXExplicitFunctionObjectParameter())
15509 HasExplicitParameter = true;
15510 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15511 M &&
15512 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15513 HasExplicitParameter = true;
15514
15515 if (HasExplicitParameter)
15516 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15517
15518 // Microsoft supports direct constructor calls.
15519 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15520 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15521 CandidateSet,
15522 /*SuppressUserConversions*/ false);
15523 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15524 // If explicit template arguments were provided, we can't call a
15525 // non-template member function.
15526 if (TemplateArgs)
15527 continue;
15528
15529 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15530 ObjectClassification, Args, CandidateSet,
15531 /*SuppressUserConversions=*/false);
15532 } else {
15533 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15534 I.getPair(), ActingDC, TemplateArgs,
15535 ExplicitObjectType, ObjectClassification,
15536 Args, CandidateSet,
15537 /*SuppressUserConversions=*/false);
15538 }
15539 }
15540
15541 HadMultipleCandidates = (CandidateSet.size() > 1);
15542
15543 DeclarationName DeclName = UnresExpr->getMemberName();
15544
15545 UnbridgedCasts.restore();
15546
15548 bool Succeeded = false;
15549 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15550 Best)) {
15551 case OR_Success:
15552 Method = cast<CXXMethodDecl>(Best->Function);
15553 FoundDecl = Best->FoundDecl;
15554 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15555 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15556 break;
15557 // If FoundDecl is different from Method (such as if one is a template
15558 // and the other a specialization), make sure DiagnoseUseOfDecl is
15559 // called on both.
15560 // FIXME: This would be more comprehensively addressed by modifying
15561 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15562 // being used.
15563 if (Method != FoundDecl.getDecl() &&
15564 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15565 break;
15566 Succeeded = true;
15567 break;
15568
15570 CandidateSet.NoteCandidates(
15572 UnresExpr->getMemberLoc(),
15573 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15574 << DeclName << MemExprE->getSourceRange()),
15575 *this, OCD_AllCandidates, Args);
15576 break;
15577 case OR_Ambiguous:
15578 CandidateSet.NoteCandidates(
15579 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15580 PDiag(diag::err_ovl_ambiguous_member_call)
15581 << DeclName << MemExprE->getSourceRange()),
15582 *this, OCD_AmbiguousCandidates, Args);
15583 break;
15584 case OR_Deleted:
15585 DiagnoseUseOfDeletedFunction(
15586 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15587 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15588 break;
15589 }
15590 // Overload resolution fails, try to recover.
15591 if (!Succeeded)
15592 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15593
15594 ExprResult Res =
15595 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15596 if (Res.isInvalid())
15597 return ExprError();
15598 MemExprE = Res.get();
15599
15600 // If overload resolution picked a static member
15601 // build a non-member call based on that function.
15602 if (Method->isStatic()) {
15603 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15604 ExecConfig, IsExecConfig);
15605 }
15606
15607 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15608 }
15609
15610 QualType ResultType = Method->getReturnType();
15612 ResultType = ResultType.getNonLValueExprType(Context);
15613
15614 assert(Method && "Member call to something that isn't a method?");
15615 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15616
15617 CallExpr *TheCall = nullptr;
15619 if (Method->isExplicitObjectMemberFunction()) {
15620 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15621 NewArgs))
15622 return ExprError();
15623
15624 // Build the actual expression node.
15625 ExprResult FnExpr =
15626 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15627 HadMultipleCandidates, MemExpr->getExprLoc());
15628 if (FnExpr.isInvalid())
15629 return ExprError();
15630
15631 TheCall =
15632 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15633 CurFPFeatureOverrides(), Proto->getNumParams());
15634 } else {
15635 // Convert the object argument (for a non-static member function call).
15636 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15637 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15638 if (ObjectArg.isInvalid())
15639 return ExprError();
15640 MemExpr->setBase(ObjectArg.get());
15641 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15642 RParenLoc, CurFPFeatureOverrides(),
15643 Proto->getNumParams());
15644 }
15645
15646 // Check for a valid return type.
15647 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15648 TheCall, Method))
15649 return BuildRecoveryExpr(ResultType);
15650
15651 // Convert the rest of the arguments
15652 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15653 RParenLoc))
15654 return BuildRecoveryExpr(ResultType);
15655
15656 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15657
15658 if (CheckFunctionCall(Method, TheCall, Proto))
15659 return ExprError();
15660
15661 // In the case the method to call was not selected by the overloading
15662 // resolution process, we still need to handle the enable_if attribute. Do
15663 // that here, so it will not hide previous -- and more relevant -- errors.
15664 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15665 if (const EnableIfAttr *Attr =
15666 CheckEnableIf(Method, LParenLoc, Args, true)) {
15667 Diag(MemE->getMemberLoc(),
15668 diag::err_ovl_no_viable_member_function_in_call)
15669 << Method << Method->getSourceRange();
15670 Diag(Method->getLocation(),
15671 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15672 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15673 return ExprError();
15674 }
15675 }
15676
15677 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15678 TheCall->getDirectCallee()->isPureVirtual()) {
15679 const FunctionDecl *MD = TheCall->getDirectCallee();
15680
15681 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15682 MemExpr->performsVirtualDispatch(getLangOpts())) {
15683 Diag(MemExpr->getBeginLoc(),
15684 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15685 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15686 << MD->getParent();
15687
15688 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15689 if (getLangOpts().AppleKext)
15690 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15691 << MD->getParent() << MD->getDeclName();
15692 }
15693 }
15694
15695 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15696 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15697 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15698 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15699 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15700 MemExpr->getMemberLoc());
15701 }
15702
15703 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15704 TheCall->getDirectCallee());
15705}
15706
15709 SourceLocation LParenLoc,
15710 MultiExprArg Args,
15711 SourceLocation RParenLoc) {
15712 if (checkPlaceholderForOverload(*this, Obj))
15713 return ExprError();
15714 ExprResult Object = Obj;
15715
15716 UnbridgedCastsSet UnbridgedCasts;
15717 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15718 return ExprError();
15719
15720 assert(Object.get()->getType()->isRecordType() &&
15721 "Requires object type argument");
15722
15723 // C++ [over.call.object]p1:
15724 // If the primary-expression E in the function call syntax
15725 // evaluates to a class object of type "cv T", then the set of
15726 // candidate functions includes at least the function call
15727 // operators of T. The function call operators of T are obtained by
15728 // ordinary lookup of the name operator() in the context of
15729 // (E).operator().
15730 OverloadCandidateSet CandidateSet(LParenLoc,
15732 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15733
15734 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15735 diag::err_incomplete_object_call, Object.get()))
15736 return true;
15737
15738 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15739 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15740 LookupQualifiedName(R, Record->getDecl());
15741 R.suppressAccessDiagnostics();
15742
15743 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15744 Oper != OperEnd; ++Oper) {
15745 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15746 Object.get()->Classify(Context), Args, CandidateSet,
15747 /*SuppressUserConversion=*/false);
15748 }
15749
15750 // When calling a lambda, both the call operator, and
15751 // the conversion operator to function pointer
15752 // are considered. But when constraint checking
15753 // on the call operator fails, it will also fail on the
15754 // conversion operator as the constraints are always the same.
15755 // As the user probably does not intend to perform a surrogate call,
15756 // we filter them out to produce better error diagnostics, ie to avoid
15757 // showing 2 failed overloads instead of one.
15758 bool IgnoreSurrogateFunctions = false;
15759 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15760 const OverloadCandidate &Candidate = *CandidateSet.begin();
15761 if (!Candidate.Viable &&
15763 IgnoreSurrogateFunctions = true;
15764 }
15765
15766 // C++ [over.call.object]p2:
15767 // In addition, for each (non-explicit in C++0x) conversion function
15768 // declared in T of the form
15769 //
15770 // operator conversion-type-id () cv-qualifier;
15771 //
15772 // where cv-qualifier is the same cv-qualification as, or a
15773 // greater cv-qualification than, cv, and where conversion-type-id
15774 // denotes the type "pointer to function of (P1,...,Pn) returning
15775 // R", or the type "reference to pointer to function of
15776 // (P1,...,Pn) returning R", or the type "reference to function
15777 // of (P1,...,Pn) returning R", a surrogate call function [...]
15778 // is also considered as a candidate function. Similarly,
15779 // surrogate call functions are added to the set of candidate
15780 // functions for each conversion function declared in an
15781 // accessible base class provided the function is not hidden
15782 // within T by another intervening declaration.
15783 const auto &Conversions =
15784 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15785 for (auto I = Conversions.begin(), E = Conversions.end();
15786 !IgnoreSurrogateFunctions && I != E; ++I) {
15787 NamedDecl *D = *I;
15788 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15789 if (isa<UsingShadowDecl>(D))
15790 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15791
15792 // Skip over templated conversion functions; they aren't
15793 // surrogates.
15794 if (isa<FunctionTemplateDecl>(D))
15795 continue;
15796
15797 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15798 if (!Conv->isExplicit()) {
15799 // Strip the reference type (if any) and then the pointer type (if
15800 // any) to get down to what might be a function type.
15801 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15802 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15803 ConvType = ConvPtrType->getPointeeType();
15804
15805 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15806 {
15807 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15808 Object.get(), Args, CandidateSet);
15809 }
15810 }
15811 }
15812
15813 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15814
15815 // Perform overload resolution.
15817 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15818 Best)) {
15819 case OR_Success:
15820 // Overload resolution succeeded; we'll build the appropriate call
15821 // below.
15822 break;
15823
15824 case OR_No_Viable_Function: {
15826 CandidateSet.empty()
15827 ? (PDiag(diag::err_ovl_no_oper)
15828 << Object.get()->getType() << /*call*/ 1
15829 << Object.get()->getSourceRange())
15830 : (PDiag(diag::err_ovl_no_viable_object_call)
15831 << Object.get()->getType() << Object.get()->getSourceRange());
15832 CandidateSet.NoteCandidates(
15833 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15834 OCD_AllCandidates, Args);
15835 break;
15836 }
15837 case OR_Ambiguous:
15838 if (!R.isAmbiguous())
15839 CandidateSet.NoteCandidates(
15840 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15841 PDiag(diag::err_ovl_ambiguous_object_call)
15842 << Object.get()->getType()
15843 << Object.get()->getSourceRange()),
15844 *this, OCD_AmbiguousCandidates, Args);
15845 break;
15846
15847 case OR_Deleted: {
15848 // FIXME: Is this diagnostic here really necessary? It seems that
15849 // 1. we don't have any tests for this diagnostic, and
15850 // 2. we already issue err_deleted_function_use for this later on anyway.
15851 StringLiteral *Msg = Best->Function->getDeletedMessage();
15852 CandidateSet.NoteCandidates(
15853 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15854 PDiag(diag::err_ovl_deleted_object_call)
15855 << Object.get()->getType() << (Msg != nullptr)
15856 << (Msg ? Msg->getString() : StringRef())
15857 << Object.get()->getSourceRange()),
15858 *this, OCD_AllCandidates, Args);
15859 break;
15860 }
15861 }
15862
15863 if (Best == CandidateSet.end())
15864 return true;
15865
15866 UnbridgedCasts.restore();
15867
15868 if (Best->Function == nullptr) {
15869 // Since there is no function declaration, this is one of the
15870 // surrogate candidates. Dig out the conversion function.
15871 CXXConversionDecl *Conv
15872 = cast<CXXConversionDecl>(
15873 Best->Conversions[0].UserDefined.ConversionFunction);
15874
15875 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15876 Best->FoundDecl);
15877 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15878 return ExprError();
15879 assert(Conv == Best->FoundDecl.getDecl() &&
15880 "Found Decl & conversion-to-functionptr should be same, right?!");
15881 // We selected one of the surrogate functions that converts the
15882 // object parameter to a function pointer. Perform the conversion
15883 // on the object argument, then let BuildCallExpr finish the job.
15884
15885 // Create an implicit member expr to refer to the conversion operator.
15886 // and then call it.
15887 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15888 Conv, HadMultipleCandidates);
15889 if (Call.isInvalid())
15890 return ExprError();
15891 // Record usage of conversion in an implicit cast.
15893 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15894 nullptr, VK_PRValue, CurFPFeatureOverrides());
15895
15896 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15897 }
15898
15899 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15900
15901 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15902 // that calls this method, using Object for the implicit object
15903 // parameter and passing along the remaining arguments.
15904 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15905
15906 // An error diagnostic has already been printed when parsing the declaration.
15907 if (Method->isInvalidDecl())
15908 return ExprError();
15909
15910 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15911 unsigned NumParams = Proto->getNumParams();
15912
15913 DeclarationNameInfo OpLocInfo(
15914 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15915 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15916 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15917 Obj, HadMultipleCandidates,
15918 OpLocInfo.getLoc(),
15919 OpLocInfo.getInfo());
15920 if (NewFn.isInvalid())
15921 return true;
15922
15923 SmallVector<Expr *, 8> MethodArgs;
15924 MethodArgs.reserve(NumParams + 1);
15925
15926 bool IsError = false;
15927
15928 // Initialize the object parameter.
15930 if (Method->isExplicitObjectMemberFunction()) {
15931 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15932 } else {
15933 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15934 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15935 if (ObjRes.isInvalid())
15936 IsError = true;
15937 else
15938 Object = ObjRes;
15939 MethodArgs.push_back(Object.get());
15940 }
15941
15943 *this, MethodArgs, Method, Args, LParenLoc);
15944
15945 // If this is a variadic call, handle args passed through "...".
15946 if (Proto->isVariadic()) {
15947 // Promote the arguments (C99 6.5.2.2p7).
15948 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15949 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15950 nullptr);
15951 IsError |= Arg.isInvalid();
15952 MethodArgs.push_back(Arg.get());
15953 }
15954 }
15955
15956 if (IsError)
15957 return true;
15958
15959 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15960
15961 // Once we've built TheCall, all of the expressions are properly owned.
15962 QualType ResultTy = Method->getReturnType();
15964 ResultTy = ResultTy.getNonLValueExprType(Context);
15965
15967 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15968 CurFPFeatureOverrides());
15969
15970 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15971 return true;
15972
15973 if (CheckFunctionCall(Method, TheCall, Proto))
15974 return true;
15975
15976 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15977}
15978
15980 SourceLocation OpLoc,
15981 bool *NoArrowOperatorFound) {
15982 assert(Base->getType()->isRecordType() &&
15983 "left-hand side must have class type");
15984
15986 return ExprError();
15987
15988 SourceLocation Loc = Base->getExprLoc();
15989
15990 // C++ [over.ref]p1:
15991 //
15992 // [...] An expression x->m is interpreted as (x.operator->())->m
15993 // for a class object x of type T if T::operator->() exists and if
15994 // the operator is selected as the best match function by the
15995 // overload resolution mechanism (13.3).
15996 DeclarationName OpName =
15997 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15999
16000 if (RequireCompleteType(Loc, Base->getType(),
16001 diag::err_typecheck_incomplete_tag, Base))
16002 return ExprError();
16003
16004 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16005 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16007
16008 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16009 Oper != OperEnd; ++Oper) {
16010 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16011 {}, CandidateSet,
16012 /*SuppressUserConversion=*/false);
16013 }
16014
16015 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16016
16017 // Perform overload resolution.
16019 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16020 case OR_Success:
16021 // Overload resolution succeeded; we'll build the call below.
16022 break;
16023
16024 case OR_No_Viable_Function: {
16025 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16026 if (CandidateSet.empty()) {
16027 QualType BaseType = Base->getType();
16028 if (NoArrowOperatorFound) {
16029 // Report this specific error to the caller instead of emitting a
16030 // diagnostic, as requested.
16031 *NoArrowOperatorFound = true;
16032 return ExprError();
16033 }
16034 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16035 << BaseType << Base->getSourceRange();
16036 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16037 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16038 << FixItHint::CreateReplacement(OpLoc, ".");
16039 }
16040 } else
16041 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16042 << "operator->" << Base->getSourceRange();
16043 CandidateSet.NoteCandidates(*this, Base, Cands);
16044 return ExprError();
16045 }
16046 case OR_Ambiguous:
16047 if (!R.isAmbiguous())
16048 CandidateSet.NoteCandidates(
16049 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16050 << "->" << Base->getType()
16051 << Base->getSourceRange()),
16053 return ExprError();
16054
16055 case OR_Deleted: {
16056 StringLiteral *Msg = Best->Function->getDeletedMessage();
16057 CandidateSet.NoteCandidates(
16058 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16059 << "->" << (Msg != nullptr)
16060 << (Msg ? Msg->getString() : StringRef())
16061 << Base->getSourceRange()),
16062 *this, OCD_AllCandidates, Base);
16063 return ExprError();
16064 }
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
16110 DeclarationNameInfo &SuffixInfo,
16111 ArrayRef<Expr*> Args,
16112 SourceLocation LitEndLoc,
16113 TemplateArgumentListInfo *TemplateArgs) {
16114 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16115
16116 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16118 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16119 TemplateArgs);
16120
16121 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16122
16123 // Perform overload resolution. This will usually be trivial, but might need
16124 // to perform substitutions for a literal operator template.
16126 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16127 case OR_Success:
16128 case OR_Deleted:
16129 break;
16130
16132 CandidateSet.NoteCandidates(
16133 PartialDiagnosticAt(UDSuffixLoc,
16134 PDiag(diag::err_ovl_no_viable_function_in_call)
16135 << R.getLookupName()),
16136 *this, OCD_AllCandidates, Args);
16137 return ExprError();
16138
16139 case OR_Ambiguous:
16140 CandidateSet.NoteCandidates(
16141 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16142 << R.getLookupName()),
16143 *this, OCD_AmbiguousCandidates, Args);
16144 return ExprError();
16145 }
16146
16147 FunctionDecl *FD = Best->Function;
16148 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16149 nullptr, HadMultipleCandidates,
16150 SuffixInfo.getLoc(),
16151 SuffixInfo.getInfo());
16152 if (Fn.isInvalid())
16153 return true;
16154
16155 // Check the argument types. This should almost always be a no-op, except
16156 // that array-to-pointer decay is applied to string literals.
16157 Expr *ConvArgs[2];
16158 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16159 ExprResult InputInit = PerformCopyInitialization(
16161 SourceLocation(), Args[ArgIdx]);
16162 if (InputInit.isInvalid())
16163 return true;
16164 ConvArgs[ArgIdx] = InputInit.get();
16165 }
16166
16167 QualType ResultTy = FD->getReturnType();
16169 ResultTy = ResultTy.getNonLValueExprType(Context);
16170
16172 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16173 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16174
16175 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16176 return ExprError();
16177
16178 if (CheckFunctionCall(FD, UDL, nullptr))
16179 return ExprError();
16180
16181 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16182}
16183
16186 SourceLocation RangeLoc,
16187 const DeclarationNameInfo &NameInfo,
16188 LookupResult &MemberLookup,
16189 OverloadCandidateSet *CandidateSet,
16191 Scope *S = nullptr;
16192
16194 if (!MemberLookup.empty()) {
16195 ExprResult MemberRef =
16196 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16197 /*IsPtr=*/false, CXXScopeSpec(),
16198 /*TemplateKWLoc=*/SourceLocation(),
16199 /*FirstQualifierInScope=*/nullptr,
16200 MemberLookup,
16201 /*TemplateArgs=*/nullptr, S);
16202 if (MemberRef.isInvalid()) {
16203 *CallExpr = ExprError();
16204 return FRS_DiagnosticIssued;
16205 }
16206 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16207 if (CallExpr->isInvalid()) {
16208 *CallExpr = ExprError();
16209 return FRS_DiagnosticIssued;
16210 }
16211 } else {
16212 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16214 NameInfo, UnresolvedSet<0>());
16215 if (FnR.isInvalid())
16216 return FRS_DiagnosticIssued;
16217 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16218
16219 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16220 CandidateSet, CallExpr);
16221 if (CandidateSet->empty() || CandidateSetError) {
16222 *CallExpr = ExprError();
16223 return FRS_NoViableFunction;
16224 }
16226 OverloadingResult OverloadResult =
16227 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16228
16229 if (OverloadResult == OR_No_Viable_Function) {
16230 *CallExpr = ExprError();
16231 return FRS_NoViableFunction;
16232 }
16233 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16234 Loc, nullptr, CandidateSet, &Best,
16235 OverloadResult,
16236 /*AllowTypoCorrection=*/false);
16237 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16238 *CallExpr = ExprError();
16239 return FRS_DiagnosticIssued;
16240 }
16241 }
16242 return FRS_Success;
16243}
16244
16246 FunctionDecl *Fn) {
16247 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16248 ExprResult SubExpr =
16249 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16250 if (SubExpr.isInvalid())
16251 return ExprError();
16252 if (SubExpr.get() == PE->getSubExpr())
16253 return PE;
16254
16255 return new (Context)
16256 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16257 }
16258
16259 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16260 ExprResult SubExpr =
16261 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16262 if (SubExpr.isInvalid())
16263 return ExprError();
16264 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16265 SubExpr.get()->getType()) &&
16266 "Implicit cast type cannot be determined from overload");
16267 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16268 if (SubExpr.get() == ICE->getSubExpr())
16269 return ICE;
16270
16271 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16272 SubExpr.get(), nullptr, ICE->getValueKind(),
16273 CurFPFeatureOverrides());
16274 }
16275
16276 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16277 if (!GSE->isResultDependent()) {
16278 ExprResult SubExpr =
16279 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16280 if (SubExpr.isInvalid())
16281 return ExprError();
16282 if (SubExpr.get() == GSE->getResultExpr())
16283 return GSE;
16284
16285 // Replace the resulting type information before rebuilding the generic
16286 // selection expression.
16287 ArrayRef<Expr *> A = GSE->getAssocExprs();
16288 SmallVector<Expr *, 4> AssocExprs(A);
16289 unsigned ResultIdx = GSE->getResultIndex();
16290 AssocExprs[ResultIdx] = SubExpr.get();
16291
16292 if (GSE->isExprPredicate())
16294 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16295 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16296 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16297 ResultIdx);
16299 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16300 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16301 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16302 ResultIdx);
16303 }
16304 // Rather than fall through to the unreachable, return the original generic
16305 // selection expression.
16306 return GSE;
16307 }
16308
16309 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16310 assert(UnOp->getOpcode() == UO_AddrOf &&
16311 "Can only take the address of an overloaded function");
16312 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16313 if (!Method->isImplicitObjectMemberFunction()) {
16314 // Do nothing: the address of static and
16315 // explicit object member functions is a (non-member) function pointer.
16316 } else {
16317 // Fix the subexpression, which really has to be an
16318 // UnresolvedLookupExpr holding an overloaded member function
16319 // or template.
16320 ExprResult SubExpr =
16321 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16322 if (SubExpr.isInvalid())
16323 return ExprError();
16324 if (SubExpr.get() == UnOp->getSubExpr())
16325 return UnOp;
16326
16327 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16328 SubExpr.get(), Method))
16329 return ExprError();
16330
16331 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16332 "fixed to something other than a decl ref");
16333 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16334 "fixed to a member ref with no nested name qualifier");
16335
16336 // We have taken the address of a pointer to member
16337 // function. Perform the computation here so that we get the
16338 // appropriate pointer to member type.
16339 QualType ClassType
16340 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16341 QualType MemPtrType
16342 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16343 // Under the MS ABI, lock down the inheritance model now.
16344 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16345 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16346
16347 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16348 MemPtrType, VK_PRValue, OK_Ordinary,
16349 UnOp->getOperatorLoc(), false,
16350 CurFPFeatureOverrides());
16351 }
16352 }
16353 ExprResult SubExpr =
16354 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16355 if (SubExpr.isInvalid())
16356 return ExprError();
16357 if (SubExpr.get() == UnOp->getSubExpr())
16358 return UnOp;
16359
16360 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16361 SubExpr.get());
16362 }
16363
16364 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16365 // FIXME: avoid copy.
16366 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16367 if (ULE->hasExplicitTemplateArgs()) {
16368 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16369 TemplateArgs = &TemplateArgsBuffer;
16370 }
16371
16372 QualType Type = Fn->getType();
16373 ExprValueKind ValueKind =
16374 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16375 ? VK_LValue
16376 : VK_PRValue;
16377
16378 // FIXME: Duplicated from BuildDeclarationNameExpr.
16379 if (unsigned BID = Fn->getBuiltinID()) {
16380 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16381 Type = Context.BuiltinFnTy;
16382 ValueKind = VK_PRValue;
16383 }
16384 }
16385
16386 DeclRefExpr *DRE = BuildDeclRefExpr(
16387 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16388 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16389 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16390 return DRE;
16391 }
16392
16393 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16394 // FIXME: avoid copy.
16395 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16396 if (MemExpr->hasExplicitTemplateArgs()) {
16397 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16398 TemplateArgs = &TemplateArgsBuffer;
16399 }
16400
16401 Expr *Base;
16402
16403 // If we're filling in a static method where we used to have an
16404 // implicit member access, rewrite to a simple decl ref.
16405 if (MemExpr->isImplicitAccess()) {
16406 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16407 DeclRefExpr *DRE = BuildDeclRefExpr(
16408 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16409 MemExpr->getQualifierLoc(), Found.getDecl(),
16410 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16411 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16412 return DRE;
16413 } else {
16414 SourceLocation Loc = MemExpr->getMemberLoc();
16415 if (MemExpr->getQualifier())
16416 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16417 Base =
16418 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16419 }
16420 } else
16421 Base = MemExpr->getBase();
16422
16423 ExprValueKind valueKind;
16424 QualType type;
16425 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16426 valueKind = VK_LValue;
16427 type = Fn->getType();
16428 } else {
16429 valueKind = VK_PRValue;
16430 type = Context.BoundMemberTy;
16431 }
16432
16433 return BuildMemberExpr(
16434 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16435 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16436 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16437 type, valueKind, OK_Ordinary, TemplateArgs);
16438 }
16439
16440 llvm_unreachable("Invalid reference to overloaded function");
16441}
16442
16445 FunctionDecl *Fn) {
16446 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16447}
16448
16449bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16451 if (!PartialOverloading || !Function)
16452 return true;
16453 if (Function->isVariadic())
16454 return false;
16455 if (const auto *Proto =
16456 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16457 if (Proto->isTemplateVariadic())
16458 return false;
16459 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16460 if (const auto *Proto =
16461 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16462 if (Proto->isTemplateVariadic())
16463 return false;
16464 return true;
16465}
16466
16468 DeclarationName Name,
16469 OverloadCandidateSet &CandidateSet,
16470 FunctionDecl *Fn, MultiExprArg Args,
16471 bool IsMember) {
16472 StringLiteral *Msg = Fn->getDeletedMessage();
16473 CandidateSet.NoteCandidates(
16474 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16475 << IsMember << Name << (Msg != nullptr)
16476 << (Msg ? Msg->getString() : StringRef())
16477 << Range),
16478 *this, OCD_AllCandidates, Args);
16479}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
StringRef P
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
const Decl * D
Expr * E
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:144
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static std::string getName(const CallEvent &Call)
static bool hasExplicitAttr(const VarDecl *D)
Definition: SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5958
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool 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 bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static 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 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void 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.
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
__device__ __2f16 b
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
iterator end()
Definition: Lookup.h:893
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:885
iterator begin()
Definition: Lookup.h:892
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:890
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:463
bool isFloat() const
Definition: APValue.h:468
bool isInt() const
Definition: APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:957
APFloat & getFloat()
Definition: APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2922
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:1169
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:1169
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.
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:684
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2723
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:2739
CanQualType DoubleTy
Definition: ASTContext.h:1172
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
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:1188
CanQualType NullPtrTy
Definition: ASTContext.h:1187
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:1703
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
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:834
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:1172
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2420
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:1161
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:800
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3021
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1372
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType CharTy
Definition: ASTContext.h:1162
CanQualType IntTy
Definition: ASTContext.h:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1188
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2203
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
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:2489
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1381
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
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:1681
CanQualType ShortTy
Definition: ASTContext.h:1169
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
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:1168
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2291
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:799
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
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:1169
CanQualType WCharTy
Definition: ASTContext.h:1163
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1166
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition: Type.cpp:270
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7766
Attr - This represents one attribute.
Definition: Attr.h:43
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2196
StringRef getOpcodeStr() const
Definition: Expr.h:3975
bool isCompoundAssignmentOp() const
Definition: Expr.h:4053
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:4902
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:189
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:2553
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2885
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2921
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2925
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:675
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:2590
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2597
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2709
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2254
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2698
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2623
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2228
bool isStatic() const
Definition: DeclCXX.cpp:2321
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:611
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:1030
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1939
bool hasDefinition() const
Definition: DeclCXX.h:572
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1700
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:74
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
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:1499
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3206
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:1513
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
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 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:3145
QualType getElementType() const
Definition: Type.h:3155
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:4924
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
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:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2233
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2028
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
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:1452
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:266
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1188
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:301
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:254
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:572
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:567
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
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.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:769
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:754
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:745
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3861
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1936
const Expr * getExpr() const
Definition: DeclCXX.h:1921
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2278
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1446
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, modifiable 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:3102
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:3093
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:3317
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4131
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
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:806
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:3970
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:276
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
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
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:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3734
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4063
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3649
param_iterator param_end()
Definition: Decl.h:2662
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3553
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3752
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
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:4134
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4183
param_iterator param_begin()
Definition: Decl.h:2661
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4259
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4199
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3331
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4127
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3756
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3324
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4419
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4000
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4288
bool isConsteval() const
Definition: Decl.h:2410
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3597
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:2737
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition: Decl.cpp:3602
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3713
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
unsigned getNumParams() const
Definition: Type.h:5360
Qualifiers getMethodQuals() const
Definition: Type.h:5502
QualType getParamType(unsigned i) const
Definition: Type.h:5362
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ArrayRef< QualType > param_types() const
Definition: Type.h:5516
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:4432
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getNoReturn() const
Definition: Type.h:4480
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4360
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4660
CallingConv getCallConv() const
Definition: Type.h:4659
QualType getReturnType() const
Definition: Type.h:4648
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4672
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:4522
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:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2089
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
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:618
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:715
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
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:766
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:626
bool hasInitializerListContainerType() const
Definition: Overload.h:748
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:679
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:755
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:630
QualType getInitializerListContainerType() const
Definition: Overload.h:758
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5088
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5195
unsigned getNumInits() const
Definition: Expr.h:5118
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2501
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2519
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:980
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
bool isAmbiguous() const
Definition: Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:641
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3425
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3333
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3454
Expr * getBase() const
Definition: Expr.h:3313
void setBase(Expr *E)
Definition: Expr.h:3312
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3347
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1813
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3431
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3323
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Describes a module or submodule.
Definition: Module.h:115
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:240
This represents a decl that may have a name.
Definition: Decl.h:253
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1668
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:551
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7529
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:7585
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7674
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7643
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7597
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7637
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7649
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1021
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:1182
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1209
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1175
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition: Overload.h:1046
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1042
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:1037
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1025
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1032
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1198
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:1190
SourceLocation getLocation() const
Definition: Overload.h:1173
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1222
CandidateSetKind getKind() const
Definition: Overload.h:1174
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:2983
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3099
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3135
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3096
decls_iterator decls_begin() const
Definition: ExprCXX.h:3076
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3087
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3109
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3105
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3155
decls_iterator decls_end() const
Definition: ExprCXX.h:3079
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3093
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4996
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8014
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
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:8139
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1081
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:8108
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8057
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:8119
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7968
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
bool hasAtomic() const
Definition: Type.h:833
bool hasRestrict() const
Definition: Type.h:832
QualifiersAndAtomic withVolatile()
Definition: Type.h:845
QualifiersAndAtomic withAtomic()
Definition: Type.h:852
bool hasVolatile() const
Definition: Type.h:830
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:512
bool hasOnlyConst() const
Definition: Type.h:451
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
void removeObjCLifetime()
Definition: Type.h:544
bool hasConst() const
Definition: Type.h:450
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:720
void addRestrict()
Definition: Type.h:473
bool hasRestrict() const
Definition: Type.h:470
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:701
void removeObjCGCAttr()
Definition: Type.h:516
void removeUnaligned()
Definition: Type.h:508
void removeAddressSpace()
Definition: Type.h:589
void addConst()
Definition: Type.h:453
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasVolatile() const
Definition: Type.h:460
bool hasObjCGCAttr() const
Definition: Type.h:511
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
void removeVolatile()
Definition: Type.h:462
std::string getAsString() const
LangAS getAddressSpace() const
Definition: Type.h:564
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:743
void addVolatile()
Definition: Type.h:463
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4162
field_range fields() const
Definition: Decl.h:4376
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: SemaCUDA.h:186
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:370
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:312
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:318
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:225
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1318
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:10031
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:5891
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
RAII class to control scope of DeferDiags.
Definition: Sema.h:9758
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:12093
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12123
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:9774
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:8990
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9002
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2452
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:165
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool HasMatchedPackOnParmToNonPackOnArg=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
SemaCUDA & CUDA()
Definition: Sema.h:1071
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:10114
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10117
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10123
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10121
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
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:1665
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:1570
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:909
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool HasMatchedPackOnParmToNonPackOnArg=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
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.
SemaObjC & ObjC()
Definition: Sema.h:1111
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:532
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:692
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:10482
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:9834
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
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:11796
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:82
const LangOptions & getLangOpts() const
Definition: Sema.h:525
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:6476
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
const LangOptions & LangOpts
Definition: Sema.h:907
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:6733
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9634
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:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15009
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:1044
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.
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7580
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7619
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7598
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7582
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7615
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20021
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20977
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:13509
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5488
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7564
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:7601
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14964
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3469
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:9998
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10003
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:10004
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10002
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10001
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:9776
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...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:912
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2393
DiagnosticsEngine & Diags
Definition: Sema.h:911
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9771
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21174
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:9756
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:395
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
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:292
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:381
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:379
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:351
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
QualType getFromType() const
Definition: Overload.h:394
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:356
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:333
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:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:378
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:361
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:323
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
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:371
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:343
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:347
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:338
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:388
QualType getToType(unsigned Idx) const
Definition: Overload.h:398
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
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:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
StringRef getString() const
Definition: Expr.h:1855
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:1262
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:665
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:718
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:703
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:250
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:398
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
Definition: TemplateName.h:237
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:6666
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3409
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
bool isBlockPointerType() const
Definition: Type.h:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isObjCBuiltinType() const
Definition: Type.h:8384
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
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:1933
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8271
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isFloat16Type() const
Definition: Type.h:8524
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isRValueReferenceType() const
Definition: Type.h:8217
bool isConstantArrayType() const
Definition: Type.h:8267
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8673
bool isArrayType() const
Definition: Type.h:8263
bool isCharType() const
Definition: Type.cpp:2123
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:8580
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isPointerType() const
Definition: Type.h:8191
bool isArrayParameterType() const
Definition: Type.h:8279
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8354
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8341
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8213
bool isBitIntType() const
Definition: Type.h:8429
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isAnyComplexType() const
Definition: Type.h:8299
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8568
bool isHalfType() const
Definition: Type.h:8519
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8497
bool isQueueT() const
Definition: Type.h:8410
bool isMemberPointerType() const
Definition: Type.h:8245
bool isObjCIdType() const
Definition: Type.h:8366
bool isMatrixType() const
Definition: Type.h:8321
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isEventT() const
Definition: Type.h:8402
bool isBFloat16Type() const
Definition: Type.h:8536
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isVectorType() const
Definition: Type.h:8303
bool isObjCClassType() const
Definition: Type.h:8372
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isHLSLAttributedResourceType() const
Definition: Type.h:8476
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:2230
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSamplerT() const
Definition: Type.h:8398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1432
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:4959
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1408
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3272
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3943
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4051
QualType getBaseType() const
Definition: ExprCXX.h:4025
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4035
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4016
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4061
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4055
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
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:949
QualType getType() const
Definition: Decl.h:682
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
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:35
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC)
Definition: Interp.h:318
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
CUDAFunctionTarget
Definition: Cuda.h:147
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:798
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:826
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:835
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:818
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:822
@ 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:863
@ ovl_fail_too_few_arguments
Definition: Overload.h:800
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:842
@ ovl_fail_too_many_arguments
Definition: Overload.h:799
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:850
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:859
@ ovl_fail_bad_conversion
Definition: Overload.h:801
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:831
@ ovl_fail_bad_deduction
Definition: Overload.h:802
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:846
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:855
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:839
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:807
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1771
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:215
@ ICR_Conversion
Conversion.
Definition: Overload.h:229
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:241
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition: Overload.h:251
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition: Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition: Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:244
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:232
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:238
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition: Overload.h:235
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition: Overload.h:254
@ ICR_Promotion
Promotion.
Definition: Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:248
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition: Overload.h:226
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:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
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_HLSL_Vector_Splat
Definition: Overload.h:205
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:208
@ 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.
AssignmentAction
Definition: Sema.h:211
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
@ 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:1278
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:365
@ 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.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
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:1285
@ None
The alignment was not explicit in code.
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:467
ConversionSet::const_iterator const_iterator
Definition: Overload.h:503
ConversionSet & conversions()
Definition: Overload.h:486
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:494
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:469
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:552
QualType getFromType() const
Definition: Overload.h:551
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:5192
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1051
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:1064
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1100
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1073
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1090
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:928
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:982
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:970
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:940
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:918
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:886
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:882
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:877
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:944
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:898
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:912
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:961
unsigned getNumParams() const
Definition: Overload.h:995
unsigned TookAddressOfOverload
Definition: Overload.h:931
bool HasMatchedPackOnParmToNonPackOnArg
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition: Overload.h:936
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:952
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:948
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:895
DeductionFailureInfo DeductionFailure
Definition: Overload.h:955
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:902
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:890
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:966
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12669
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12757
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10131
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7858
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
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:422
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:434
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:456
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:447
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:442
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:461
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.